use clap::{Parser, Subcommand};
use colored::*;
use std::process;

mod commands;
mod config;
mod error;
mod output;
mod ssh;
mod utils;

use commands::{
    env::EnvCommand, infra::InfraCommand, init::InitCommand, logs::LogsCommand,
    monitor::MonitorCommand, observe::ObserveCommand, services::ServicesCommand,
    version::VersionCommand,
};
use config::AppConfig;

#[derive(Parser)]
#[command(
    name = "optima-ops-rust",
    about = "System operations and monitoring CLI for Optima (Rust edition)",
    version,
    long_about = None
)]
struct Cli {
    /// Set environment (production/stage/development)
    #[arg(long, global = true)]
    env: Option<String>,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Initialize configuration and credentials from AWS SSM
    Init(InitCommand),

    /// Service management commands
    Services(ServicesCommand),

    /// Observability commands (optima-core integration)
    Observe(ObserveCommand),

    /// Infrastructure monitoring commands
    Infra(InfraCommand),

    /// Log viewing and analysis tools
    Logs(LogsCommand),

    /// Real-time monitoring dashboard
    Monitor(MonitorCommand),

    /// Display current environment information
    Env(EnvCommand),

    /// Display version information
    Version(VersionCommand),
}

#[tokio::main]
async fn main() {
    // 初始化日志
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::from_default_env()
                .add_directive(tracing::Level::WARN.into()),
        )
        .init();

    let cli = Cli::parse();

    // 加载配置
    let config = match AppConfig::load() {
        Ok(cfg) => cfg,
        Err(e) => {
            eprintln!("{} {}", "错误:".red().bold(), e);
            process::exit(1);
        }
    };

    // 执行命令
    let result = match cli.command {
        Some(Commands::Init(cmd)) => cmd.execute(&config).await,
        Some(Commands::Services(cmd)) => cmd.execute(&config).await,
        Some(Commands::Observe(cmd)) => cmd.execute(&config).await,
        Some(Commands::Infra(cmd)) => cmd.execute(&config).await,
        Some(Commands::Logs(cmd)) => cmd.execute(&config).await,
        Some(Commands::Monitor(cmd)) => cmd.execute(&config).await,
        Some(Commands::Env(cmd)) => cmd.execute(&config).await,
        Some(Commands::Version(cmd)) => cmd.execute(&config).await,
        None => {
            // 默认启动监控面板
            MonitorCommand::default_dashboard()
                .execute(&config)
                .await
        }
    };

    if let Err(e) = result {
        error::handle_error(&e);
        process::exit(1);
    }
}
