use clap::{CommandFactory, Parser};

#[derive(Parser)]
#[command(name = "picobot")]
#[command(about = "A CLI chatbot", long_about = None)]
enum Command {
    /// Interactive configuration wizard
    Init {
        /// Force overwrite existing config
        #[arg(short, long)]
        force: bool,
        /// Only configure provider, skip channels
        #[arg(long)]
        skip_channels: bool,
    },
    /// Connect to gateway
    Agent {
        /// Gateway WebSocket URL (e.g., ws://127.0.0.1:19876/ws)
        #[arg(long)]
        gateway_url: Option<String>,
    },
    /// Start gateway server
    Gateway {
        /// Host to bind to
        #[arg(long)]
        host: Option<String>,
        /// Port to listen on
        #[arg(long)]
        port: Option<u16>,
    },
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    picobot::bootstrap::initialize_process_runtime();

    let mut cmd = Command::command();

    // If no arguments, print help
    if std::env::args().len() <= 1 {
        cmd.print_help()?;
        println!();
        return Ok(())
    }

    match Command::parse() {
        Command::Init { force, skip_channels } => {
            let mut wizard = picobot::cli::InitWizard::new();
            wizard.run(force, skip_channels).await?;
        }
        Command::Agent { gateway_url } => {
            let config = picobot::config::Config::load_default().ok();
            let url = gateway_url
                .or_else(|| config.as_ref().map(|c| c.client.gateway_url.clone()))
                .unwrap_or_else(|| "ws://127.0.0.1:19876/ws".to_string());
            picobot::client::run(&url).await?;
        }
        Command::Gateway { host, port } => {
            picobot::gateway::run(host, port).await?;
        }
    }
    Ok(())
}
