use crate::shortcut::screenshot::{self, CAPTURING};
use std::sync::atomic::Ordering;
use crate::core::log;
/// 需要自动截图的窗口标题关键词
/// "微信/企业微信/钉钉/飞书/小红书"等
const TARGET_KEYWORDS: &[&str] = &[
    "微信",
    "企业微信",
    "钉钉",
    "飞书",
    "小红书",
    "淘宝",
    "天猫",
    "京东",
    "拼多多",
    "抖音",
    "海外",
    "tiktok",
    "快手",
    "B站",
    "bilibili",
    "哔哩哔哩",
    "哔哩哔哩 (゜-゜)つロ 干杯~-bilibili",
    "微博",
    "知乎",
    "cnblogs",
    "掘金",
    "ai",
    "aigc",
    "deepseek",
    "元宝",
    "豆包",
    "gpt",
    "视频",
    "短视频",
    "ai视频",
    "ai短剧",
];

/// 检测当前前台窗口标题是否包含目标关键词
#[cfg(target_os = "windows")]
fn is_target_foreground() -> bool {
    let title = match active_win_pos_rs::get_active_window() {
        Ok(win) => win.title,
        Err(_) => return false,
    };

    crate::core::log::info!("[DEBUG] 当前前台窗口标题: {}", title);
    TARGET_KEYWORDS.iter().any(|kw| title.contains(kw))
}

#[cfg(not(target_os = "windows"))]
fn is_target_foreground() -> bool {
    false
}

/// 启动定时截图：检测前台窗口是否为微信，是则截图发送
pub fn start_auto_capture(nums: u64) {
    std::thread::spawn(move || {
        log::info!("定时截图已启动（每30秒检测目标窗口）");
        loop {
            std::thread::sleep(std::time::Duration::from_secs(nums));

            if CAPTURING.load(Ordering::SeqCst) {
                continue;
            }

            if !is_target_foreground() {
                continue;
            }

            log::info!("=== 检测到目标窗口在前台，自动截图 ===");
            CAPTURING.store(true, Ordering::SeqCst);
            screenshot::do_capture_and_send();
        }
    });
}
