use winreg::enums::{HKEY_CURRENT_USER, KEY_READ};
use winreg::RegKey;

const MENU_TEXT: &str = "在 CCGUI 中打开";

fn exe_path() -> Result<String, String> {
    std::env::current_exe()
        .map(|p| p.to_string_lossy().into_owned())
        .map_err(|e| e.to_string())
}

const KEYS: [&str; 2] = [
    r"Software\Classes\Directory\shell\CCGUI",
    r"Software\Classes\Directory\Background\shell\CCGUI",
];

/// 写入 HKCU 注册表，为文件夹及文件夹空白处添加右键菜单项（无需管理员权限）。
/// Win11 下条目出现在"显示更多选项"二级菜单中。
pub fn install_context_menu() -> Result<(), String> {
    let exe = exe_path()?;
    let hkcu = RegKey::predef(HKEY_CURRENT_USER);
    for (i, key_path) in KEYS.iter().enumerate() {
        let (key, _) = hkcu.create_subkey(key_path).map_err(|e| e.to_string())?;
        key.set_value("", &MENU_TEXT).map_err(|e| e.to_string())?;
        key.set_value("Icon", &exe).map_err(|e| e.to_string())?;
        let (cmd_key, _) = key.create_subkey("command").map_err(|e| e.to_string())?;
        // 右键文件夹本身用 %1，文件夹背景用 %V
        let placeholder = if i == 0 { "%1" } else { "%V" };
        cmd_key
            .set_value("", &format!("\"{exe}\" --open \"{placeholder}\""))
            .map_err(|e| e.to_string())?;
    }
    Ok(())
}

pub fn uninstall_context_menu() -> Result<(), String> {
    let hkcu = RegKey::predef(HKEY_CURRENT_USER);
    for key_path in KEYS {
        match hkcu.delete_subkey_all(key_path) {
            Ok(_) => {}
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => return Err(e.to_string()),
        }
    }
    Ok(())
}

pub fn context_menu_installed() -> bool {
    RegKey::predef(HKEY_CURRENT_USER)
        .open_subkey_with_flags(KEYS[0], KEY_READ)
        .is_ok()
}
