//! AI service binary - HTTP wrapper for AI capabilities including RAG, MCP tool
//! invocation, and knowledge graphs

use std::net::SocketAddr;
use std::sync::Arc;

use ai_service::{handlers, AiService, DEFAULT_PORT};
use axum::Router;
use clap::Parser;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

#[derive(Parser, Debug)]
#[command(name = "ai-service")]
#[command(about = "HTTP service for AI capabilities including RAG, MCP tool invocation, DAG operations, and knowledge graphs", long_about = None)]
struct Args {
    /// Service bind address
    #[arg(short, long, default_value = "127.0.0.1")]
    host: String,

    /// Service bind port
    #[arg(short, long, default_value_t = DEFAULT_PORT)]
    port: u16,
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Initialize tracing
    tracing_subscriber::registry()
        .with(tracing_subscriber::EnvFilter::new(
            std::env::var("RUST_LOG").unwrap_or_else(|_| "ai_service=info,axum=debug".to_string()),
        ))
        .with(tracing_subscriber::fmt::layer())
        .init();

    let args = Args::parse();
    let addr: SocketAddr = format!("{}:{}", args.host, args.port).parse()?;

    // Create service
    let service = Arc::new(AiService::new(addr));
    tracing::info!("Starting AI service on {}", addr);

    // Create router
    let app = Router::new()
        .merge(handlers::create_routes(service))
        .fallback(|| async { (axum::http::StatusCode::NOT_FOUND, "Not found") });

    // Start server
    let listener = tokio::net::TcpListener::bind(&addr).await?;
    axum::serve(listener, app).await?;

    Ok(())
}
