// src/mfplat_installer.rs
use std::{collections::HashMap, error::Error, fs, path::Path, process::Command};
use tempfile::NamedTempFile;
use std::io::Write;

// قبل از اجرا:
// cargo add reqwest tempfile

pub fn ensure_mfplat() -> Result<(), Box<dyn Error>> {
    // 1. Check DLL
    if Path::new(r"C:\Windows\System32\mfplat.dll").exists()
        || Path::new(r"C:\Windows\SysWOW64\mfplat.dll").exists()
    {
        println!("mfplat.dll already exists");
        return Ok(());
    }
    println!("mfplat.dll missing — installing Media Feature Pack...");

    // 2. Detect OS & Build & Arch
    let os_caption = get_ps("(Get-WmiObject -class Win32_OperatingSystem).Caption")?;
    let build_str = get_ps("(Get-ComputerInfo).OsBuildNumber")?;
    let build: u32 = build_str.trim().parse().unwrap_or(0);
    let arch = if cfg!(target_pointer_width = "64") {
        "x64"
    } else {
        "x86"
    };

    println!("Detected: {} | Build {} | Arch {}", os_caption.trim(), build, arch);

    // 3. Pick URL
    let url = pick_url(os_caption.trim(), build, arch)?;
    println!("Download URL: {}", url);

    // 4. Download
    let mut tmpfile = NamedTempFile::new()?;
    let bytes = reqwest::blocking::get(url)?.bytes()?;
    tmpfile.write_all(&bytes)?;
    let path_str = tmpfile.path().to_str().unwrap();

    // 5. Install
    println!("Installing silently...");
    Command::new("wusa.exe")
        .args([path_str, "/quiet", "/norestart"])
        .status()?;

    println!("Installation finished. System will restart now...");
    Command::new("shutdown")
        .args(["/r", "/t", "0"])
        .status()?;

    Ok(())
}

fn get_ps(cmd: &str) -> Result<String, Box<dyn Error>> {
    let out = Command::new("powershell")
        .args(["-NoProfile", "-Command", cmd])
        .output()?;
    Ok(String::from_utf8_lossy(&out.stdout).to_string())
}

fn pick_url(os_caption: &str, build: u32, arch: &str) -> Result<&'static str, Box<dyn Error>> {
    // جدول لینک‌ها
    let mut map: HashMap<(&str, u32, u32, &str), &str> = HashMap::new();

    // --- Windows 7 SP1 N/KN ---
    map.insert((
        "Windows 7",
        0,
        99999,
        "x64",
    ), "https://download.microsoft.com/download/9/7/0/9703BBB9-6515-41C0-9E54-AD9946BDD47F/Windows6.1-KB968211-x64-RefreshPkg.msu");
    map.insert((
        "Windows 7",
        0,
        99999,
        "x86",
    ), "https://download.microsoft.com/download/0/9/1/091AA22C-9593-4BB1-99BF-59B8A78E7D65/Windows6.1-KB968211-x86-RefreshPkg.msu");

    // --- Windows 8.1 N/KN ---
    map.insert((
        "Windows 8.1",
        0,
        99999,
        "x64",
    ), "https://download.microsoft.com/download/4/F/F/4FF20E44-086C-4EC5-86A4-32E9B220BF59/Windows8.1-KB2929699-x64.msu");
    map.insert((
        "Windows 8.1",
        0,
        99999,
        "x86",
    ), "https://download.microsoft.com/download/8/1/A/81A479A1-F980-4F44-AAD5-21B7F49CEE3C/Windows8.1-KB2929699-x86.msu");

    // --- Windows 10 N/KN ---
    map.insert((
        "Windows 10",
        19041,
        19045,
        "x64",
    ), "https://download.microsoft.com/download/4/2/4/424D403A-69D6-49BE-9BC0-89E36C35FAF3/Microsoft.Media.Feature.Pack.19041.msu");
    map.insert((
        "Windows 10",
        19041,
        19045,
        "x86",
    ), "https://download.microsoft.com/download/9/0/2/90218E87-349B-437B-AAA0-0ABA8A112B7B/Microsoft.Media.Feature.Pack.19041.x86.msu");

    // --- Windows 11 N/KN ---
    map.insert((
        "Windows 11",
        22000,
        22635,
        "x64",
    ), "https://download.microsoft.com/download/A/0/3/A037E28D-51CD-495D-AE7A-3B873BB61C0F/Microsoft.Media.Feature.Pack.22000.msu");

    for ((os, min_b, max_b, a), url) in map {
        if os_caption.contains(os) && build >= min_b && build <= max_b && arch == a {
            return Ok(url);
        }
    }
    Err("No Media Feature Pack link found for this OS/build".into())
}
