// Steam related path utils, including:
// - Steam Path
// - CS2(CS:GO) Path
#![allow(unused)]

use std::fs::{self, exists};
use std::path::{Path, PathBuf};

use crate::tool::common::get_exe_path;
use anyhow::Result;

use super::reg;
pub fn get_steam_path() -> Result<String, String> {
    // Running steam.exe
    #[cfg(target_os = "windows")]
    if let Ok(steam_path) = get_exe_path("steam") {
        // 去除结尾的 steam.exe 不区分大小写
        if let Some(parent_path) = Path::new(&steam_path).parent() {
            return Ok(parent_path.to_string_lossy().to_string());
        } else {
            return Err("Failed to get parent directory".into());
        }
    }

    // Windows Registry
    #[cfg(target_os = "windows")]
    if let Ok(reg) = reg::SteamReg::get_all() {
        return Ok(reg.steam_path);
    }

    Err("no steam path found".into())
}

pub fn get_cs_path(name: &str, steam_dir: &str) -> Result<String, String> {
    if name != "csgo" && name != "cs2" {
        return Err("invalid cs name".into());
    }

    // 1. 优先检查 steam_dir 参数
    let steam_path = if steam_dir.is_empty() || !Path::new(steam_dir).exists() {
        // 如果 steam_dir 不满足条件，调用 get_steam_path 获取路径
        let p = get_steam_path().map_err(|e| e.to_string())?;
        PathBuf::from(p)
    } else {
        PathBuf::from(steam_dir) // 同样转换为PathBuf
    };

    let cs_path = steam_path
        .join("steamapps\\common\\Counter-Strike Global Offensive\\game\\bin\\win64\\cs2.exe");
    if cs_path.exists() {
        if let Some(parent) = cs_path.parent() {
            return Ok(parent.to_string_lossy().to_string());
        }
    }

    // 2. 通过注册表读取所有磁盘盘符
    #[cfg(target_os = "windows")]
    {
        use winreg::enums::HKEY_LOCAL_MACHINE;
        use winreg::RegKey;

        let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
        let mounted_devices = hklm
            .open_subkey("SYSTEM\\MountedDevices")
            .map_err(|e| e.to_string())?;

        // 获取所有盘符
        let drives: Vec<String> = mounted_devices
            .enum_values()
            .filter_map(|v| {
                let (name, _) = v.ok()?;
                let name = name.to_string();
                if name.starts_with("\\DosDevices\\") {
                    Some(name.replace("\\DosDevices\\", ""))
                } else {
                    None
                }
            })
            .collect();

        // 遍历盘符，尝试查找 cs2.exe
        let cs_path_suffix = "SteamLibrary\\steamapps\\common\\Counter-Strike Global Offensive\\game\\bin\\win64\\cs2.exe";
        for drive in drives {
            let cs_path = Path::new(&drive).join(cs_path_suffix);
            if cs_path.exists() {
                if let Some(parent) = cs_path.parent() {
                    return Ok(parent.to_string_lossy().to_string());
                }
            }
        }
    }

    // 3. 查找正在运行的cs2进程
    #[cfg(target_os = "windows")]
    if let Ok(cs2_path) = get_exe_path("cs2") {
        // 去除结尾的 steam.exe 不区分大小写
        if let Some(parent_path) = Path::new(&cs2_path).parent() {
            return Ok(parent_path.to_string_lossy().to_string());
        } else {
            return Err("Failed to get parent directory".into());
        }
    }

    Err("no cs path found".into())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_get_steam_path() {
        let path = get_steam_path().unwrap();
        println!("{}", path);
    }

    #[test]
    fn test_get_cs_path() {
        let result = get_cs_path("cs2", "");
        assert!(result.is_ok() || result.is_err());
        println!("CS2 Path: {:?}", result);

        // 使用get_steam_path给到的路径
        let steam_dir = get_steam_path().unwrap();
        let result = get_cs_path("cs2", &steam_dir);
        assert!(result.is_ok() || result.is_err());
        println!("CS2 Path: {:?}", result)
    }
}
