#![allow(dead_code)]

use super::{Platform, PlatformInfo};
use crate::error::AppResult;

pub fn get_platform_info() -> AppResult<PlatformInfo> {
    Ok(PlatformInfo {
        platform: Platform::Windows,
        version: "11".to_string(), // TODO: Read actual Windows version
        supports_ios_supervision: true, // Once supervise-magic Windows build is verified
    })
}

pub fn install_doh(dns_token: &str) -> AppResult<()> {
    use std::process::Command;

    let doh_url = format!("https://dns.rebreak.org/dns-query/{}", dns_token);
    let script = format!(
        r#"
$iface = Get-NetAdapter | Where-Object {{ $_.Status -eq 'Up' }} | Select-Object -First 1
if (-not $iface) {{ exit 1 }}
Set-DnsClientDohServerAddress -ServerAddress '142.132.245.42' -DohTemplate '{}' -AutoUpgrade $true
Set-DnsClientServerAddress -InterfaceAlias $iface.Name -ServerAddresses ('142.132.245.42')
"#,
        doh_url
    );

    let status = Command::new("powershell.exe")
        .args([
            "-NonInteractive",
            "-NoProfile",
            "-ExecutionPolicy",
            "Bypass",
            "-Command",
            &script,
        ])
        .status()
        .map_err(|e| crate::error::AppError::new(format!("Failed to run PowerShell: {}", e)))?;

    if !status.success() {
        return Err(crate::error::AppError::new(
            "DoH-Konfiguration fehlgeschlagen. Bitte ReBreak Magic mit Administratorrechten starten.".to_string(),
        ));
    }
    Ok(())
}

pub fn store_token(token: &str) -> AppResult<()> {
    // TODO: Implement using Windows Credential Manager via keyring crate
    Ok(())
}

pub fn read_token() -> AppResult<Option<String>> {
    // TODO: Implement using Windows Credential Manager via keyring crate
    Ok(None)
}

pub fn activate_protection(token: &str) -> AppResult<()> {
    install_doh(token)
}

pub fn deactivate_protection(_token: &str) -> AppResult<()> {
    Ok(())
}

/// Returns the Windows machine GUID (Registry: HKLM\SOFTWARE\Microsoft\Cryptography\MachineGuid).
pub fn get_hardware_id() -> AppResult<String> {
    use std::process::Command;
    let output = Command::new("reg")
        .args([
            "query",
            "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography",
            "/v",
            "MachineGuid",
        ])
        .output()
        .map_err(|e| crate::error::AppError::new(format!("Failed to read hardware ID: {}", e)))?;

    let text = String::from_utf8_lossy(&output.stdout);
    for line in text.lines() {
        if line.contains("MachineGuid") {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if let Some(uuid) = parts.last() {
                if uuid.contains('-') {
                    return Ok(uuid.to_string());
                }
            }
        }
    }

    Err(crate::error::AppError::new(
        "Could not parse Windows machine GUID".to_string(),
    ))
}
