//! K4000 MCP Server
//!
//! Unified MCP server providing tools for task analysis, Q&A management,
//! task development tracking, and code review.

use k4000::servers::K4000Server;
use rmcp::ServiceExt;
use tokio::io::{stdin, stdout};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Initialize logging to stderr (stdout is used for MCP protocol)
    tracing_subscriber::registry()
        .with(
            tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()),
        )
        .with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr))
        .init();

    tracing::info!("Starting K4000 MCP Server");

    // Get project path (current working directory)
    let project_path = std::env::current_dir()
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|_| std::path::PathBuf::from("."));

    // Get max iterations from environment or use default
    let max_iterations: u32 = std::env::var("K4000_MAX_ITERATIONS")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(3);

    tracing::info!("Using project path: {:?}", project_path);
    tracing::info!("Max review iterations: {}", max_iterations);

    // Create the unified server
    let server = K4000Server::new(project_path).with_max_iterations(max_iterations);

    // Serve over stdio
    let transport = (stdin(), stdout());
    let service = server.serve(transport).await?;

    tracing::info!("Server running on stdio transport");

    // Wait for the service to complete
    service.waiting().await?;

    tracing::info!("Server shutting down");
    Ok(())
}
