//! Windows 防火墙自动配置
//! 
//! 在应用启动时自动添加防火墙规则，避免用户手动配置

#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;
use std::process::Command;

#[cfg(target_os = "windows")]
const CREATE_NO_WINDOW: u32 = 0x08000000;

/// 检查并配置 Windows 防火墙规则
/// 如果规则不存在，则静默添加（需要管理员权限时会自动请求）
#[cfg(target_os = "windows")]
pub fn configure_firewall(app_name: &str, udp_port: u16, ws_port: u16, http_port: u16) {
    // 检查规则是否已存在
    let check_result = Command::new("netsh")
        .args(["advfirewall", "firewall", "show", "rule", &format!("name={}", app_name)])
        .creation_flags(CREATE_NO_WINDOW)
        .output();

    if let Ok(output) = check_result {
        let output_str = String::from_utf8_lossy(&output.stdout);
        if output_str.contains(app_name) {
            log::info!("Firewall rules already configured");
            return;
        }
    }

    log::info!("Configuring firewall rules...");

    // 添加 UDP 规则（设备发现）
    let _ = Command::new("netsh")
        .args([
            "advfirewall", "firewall", "add", "rule",
            &format!("name={} UDP", app_name),
            "dir=in",
            "action=allow",
            "protocol=UDP",
            &format!("localport={}", udp_port),
        ])
        .creation_flags(CREATE_NO_WINDOW)
        .output();

    // 添加 WebSocket TCP 规则
    let _ = Command::new("netsh")
        .args([
            "advfirewall", "firewall", "add", "rule",
            &format!("name={} WebSocket", app_name),
            "dir=in",
            "action=allow",
            "protocol=TCP",
            &format!("localport={}", ws_port),
        ])
        .creation_flags(CREATE_NO_WINDOW)
        .output();

    // 添加 HTTP TCP 规则
    let _ = Command::new("netsh")
        .args([
            "advfirewall", "firewall", "add", "rule",
            &format!("name={} HTTP", app_name),
            "dir=in",
            "action=allow",
            "protocol=TCP",
            &format!("localport={}", http_port),
        ])
        .creation_flags(CREATE_NO_WINDOW)
        .output();

    log::info!("Firewall rules configuration attempted");
}

#[cfg(not(target_os = "windows"))]
pub fn configure_firewall(_app_name: &str, _udp_port: u16, _ws_port: u16, _http_port: u16) {
    // macOS 和 Linux 通常不需要手动配置防火墙
    log::info!("Firewall configuration not needed on this platform");
}
