//! EasyRemote 服务端主入口

mod config;
mod db;
mod handlers;
mod models;
mod services;
mod stun_server;
mod turn_server;
mod websocket;

use axum::{
    routing::{get, post, delete},
    Router, Json, extract::State,
};
use std::sync::Arc;
use tower_http::cors::{Any, CorsLayer};
use tower_http::trace::TraceLayer;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

use crate::config::{Config, IceServersConfig};
use crate::db::Database;
use crate::services::AppState;
use crate::stun_server::StunServer;
use crate::turn_server::TurnServer;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // 初始化日志
    tracing_subscriber::registry()
        .with(tracing_subscriber::EnvFilter::new(
            std::env::var("RUST_LOG").unwrap_or_else(|_| "info,tower_http=debug".into()),
        ))
        .with(tracing_subscriber::fmt::layer())
        .init();

    // 加载配置
    dotenvy::dotenv().ok();
    let config = Config::from_env()?;

    tracing::info!("Starting EasyRemote Server on {}:{}", config.host, config.port);

    // 启动本地 STUN 服务
    if config.enable_local_stun {
        let stun_port = config.stun_port;
        tokio::spawn(async move {
            let stun_server = StunServer::new(stun_port);
            if let Err(e) = stun_server.start().await {
                tracing::error!("STUN server error: {}", e);
            }
        });
        tracing::info!("Local STUN server enabled on port {}", config.stun_port);
    }

    // 启动本地 TURN 服务
    if config.enable_local_turn {
        let turn_port = config.turn_port;
        let turn_realm = config.turn_realm.clone();
        let turn_username = config.turn_username.clone();
        let turn_password = config.turn_password.clone();
        tokio::spawn(async move {
            let turn_server = TurnServer::new(turn_port, turn_realm, turn_username, turn_password);
            if let Err(e) = turn_server.start().await {
                tracing::error!("TURN server error: {}", e);
            }
        });
        tracing::info!("Local TURN server enabled on port {}", config.turn_port);
    }

    // 初始化数据库
    let db = Database::new(&config.database_url).await?;
    db.migrate().await?;

    // 创建应用状态
    let state = Arc::new(AppState::new(db, config.clone()));
    
    // 启动时将所有设备设为离线（清理上次异常退出的状态）
    {
        let device_repo = crate::services::device::DeviceRepository::new(&state.db);
        match device_repo.set_all_offline().await {
            Ok(count) => {
                if count > 0 {
                    tracing::info!("Reset {} devices to offline status", count);
                }
            }
            Err(e) => {
                tracing::warn!("Failed to reset device status: {}", e);
            }
        }
    }

    // 构建路由
    let app = Router::new()
        // 初始化配置路由
        .route("/api/setup/status", get(handlers::setup::check_setup_status))
        .route("/api/setup/init", post(handlers::setup::init_setup))
        // 认证路由
        .route("/api/auth/register", post(handlers::auth::register))
        .route("/api/auth/login", post(handlers::auth::login))
        .route("/api/auth/logout", post(handlers::auth::logout))
        .route("/api/auth/refresh", post(handlers::auth::refresh_token))
        // 用户路由
        .route("/api/users/me", get(handlers::users::get_current_user))
        .route("/api/users/me", post(handlers::users::update_user))
        // 设备路由
        .route("/api/devices", get(handlers::devices::list_devices))
        .route("/api/devices/:id", get(handlers::devices::get_device))
        .route("/api/devices/:id", delete(handlers::devices::remove_device))
        .route("/api/devices/:id/offline", post(handlers::devices::force_offline))
        .route("/api/devices/register", post(handlers::devices::register_device))
        // ICE 服务器配置
        .route("/api/ice-servers", get(get_ice_servers))
        // 会话路由
        .route("/api/sessions", get(handlers::sessions::list_sessions))
        .route("/api/sessions/history", get(handlers::sessions::get_history))
        .route("/api/sessions/:id", get(handlers::sessions::get_session))
        .route("/api/sessions/:id/end", post(handlers::sessions::end_session))
        // 管理员路由
        .route("/api/admin/users", get(handlers::admin::list_users))
        .route("/api/admin/users/:id", delete(handlers::admin::delete_user))
        .route("/api/admin/devices", get(handlers::admin::list_all_devices))
        .route("/api/admin/sessions", get(handlers::admin::list_all_sessions))
        .route("/api/admin/stats", get(handlers::admin::get_stats))
        .route("/api/admin/config", get(handlers::admin::get_server_config))
        .route("/api/admin/env-config", get(handlers::admin::get_env_config))
        .route("/api/admin/env-config", post(handlers::admin::save_env_config))
        // WebSocket 信令
        .route("/ws/signal", get(websocket::signal_handler))
        // WebSocket 远程控制 (浏览器)
        .route("/ws/remote/:device_id", get(websocket::remote_handler))
        // 静态文件服务 (管理后台)
        .nest_service("/", tower_http::services::ServeDir::new("static"))
        // 中间件
        .layer(CorsLayer::new()
            .allow_origin(Any)
            .allow_methods(Any)
            .allow_headers(Any))
        .layer(TraceLayer::new_for_http())
        .with_state(state);

    // 打印 STUN 配置信息
    tracing::info!("ICE servers: {:?}", config.stun_servers);

    // 启动服务器
    let addr = format!("{}:{}", config.host, config.port);
    let listener = tokio::net::TcpListener::bind(&addr).await?;
    tracing::info!("Server listening on {}", addr);
    
    axum::serve(listener, app).await?;

    Ok(())
}

/// 获取 ICE 服务器配置 API
async fn get_ice_servers(State(state): State<Arc<AppState>>) -> Json<IceServersConfig> {
    Json(state.config.get_ice_servers())
}
