//! OSTP Windows Installer - Setup Wizard
//!
//! Installs:
//! - Wintun driver
//! - OspabGuard Windows Service  
//! - Firewall rules
//! - GUI shortcuts

#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use anyhow::Result;
use std::path::PathBuf;

mod wizard;
mod wintun;
mod service;
mod firewall;

// Placeholder - download actual wintun.dll from https://www.wintun.net/
// const WINTUN_DLL: &[u8] = include_bytes!("../../assets/wintun.dll");

fn main() -> Result<()> {
    // Check for admin privileges
    if !is_elevated() {
        anyhow::bail!("Installer must be run as Administrator");
    }

    // Initialize logging
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        .init();

    tracing::info!("OSTP Installer starting");

    // Show wizard UI
    wizard::run_wizard()?;

    Ok(())
}

#[cfg(windows)]
fn is_elevated() -> bool {
    use winapi::um::securitybaseapi::*;
    use winapi::um::processthreadsapi::*;
    use winapi::um::winnt::*;
    use std::mem;
    use std::ptr;

    unsafe {
        let mut handle: HANDLE = ptr::null_mut();
        if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut handle) == 0 {
            return false;
        }

        let mut elevation: TOKEN_ELEVATION = mem::zeroed();
        let mut size = mem::size_of::<TOKEN_ELEVATION>() as u32;

        if GetTokenInformation(
            handle,
            TokenElevation,
            &mut elevation as *mut _ as *mut _,
            size,
            &mut size,
        ) == 0
        {
            return false;
        }

        elevation.TokenIsElevated != 0
    }
}

pub fn get_install_path() -> PathBuf {
    PathBuf::from(r"C:\Program Files\Ospab\OSTP")
}

pub fn install_wintun_dll() -> Result<()> {
    let install_path = get_install_path();
    std::fs::create_dir_all(&install_path)?;

    // TODO: Copy wintun.dll when available
    // let wintun_path = install_path.join("wintun.dll");
    // std::fs::write(&wintun_path, WINTUN_DLL)
    //     .context("Failed to write wintun.dll")?;

    tracing::info!("Wintun DLL installation placeholder");
    Ok(())
}
