//! Flash Send 应用入口
//! 跨平台局域网文件传输与聊天应用

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

use flash_send_lib::{
    database::Database,
    tls::CertificateManager,
    utils::{AppConfig, configure_firewall},
    AppState,
    get_handlers,
};
use std::path::PathBuf;
use tauri::Manager;

fn main() {
    // 初始化日志
    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"))
        .format_timestamp_millis()
        .init();

    log::info!("Starting Flash Send application");

    tauri::Builder::default()
        .plugin(tauri_plugin_dialog::init())
        .plugin(tauri_plugin_fs::init())
        .plugin(tauri_plugin_shell::init())
        .setup(|app| {
            let app_data_dir = app
                .path()
                .app_data_dir()
                .unwrap_or_else(|_| PathBuf::from("."));

            log::info!("App data directory: {:?}", app_data_dir);

            // 初始化应用状态
            AppState::init(app_data_dir.clone())
                .expect("Failed to initialize app state");

            // 初始化数据库（存储在 AppData 目录下）
            Database::init(app_data_dir.clone())
                .expect("Failed to initialize database");

            // 获取本机 IP 并初始化 TLS 证书
            let config = AppConfig::get();
            let ip_addresses = local_ip_address::local_ip()
                .map(|ip| vec![ip.to_string()])
                .unwrap_or_default();

            CertificateManager::init(&app_data_dir, &config.device_id, ip_addresses)
                .expect("Failed to initialize TLS certificate");

            // 配置防火墙规则（Windows）
            configure_firewall(
                "Flash Send",
                config.udp_port,
                config.ws_port,
                config.http_port,
            );

            log::info!("Application initialized successfully");
            log::info!("Device ID: {}", config.device_id);
            log::info!("Device Name: {}", config.device_name);

            Ok(())
        })
        .invoke_handler(get_handlers())
        .run(tauri::generate_context!())
        .expect("Error while running Flash Send application");
}
