use anyhow::{Context, Result};
use rmcp::{ServiceExt, transport::stdio};
use std::path::Path;
use suno_mcp_server::EnvironmentService;

const DOTENV_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../.env");

fn load_repo_env() -> Result<bool> {
    let env_path = Path::new(DOTENV_PATH);

    if env_path.exists() {
        dotenvy::from_path(env_path).with_context(|| {
            format!("loading environment variables from {}", env_path.display())
        })?;
        Ok(true)
    } else {
        Ok(false)
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_target(false)
        .compact()
        .with_writer(std::io::stderr)
        .with_ansi(false)
        .init();

    match load_repo_env()? {
        true => tracing::info!("Loaded environment variables from {}", DOTENV_PATH),
        false => tracing::debug!(
            "No .env file found at {}. Proceeding with process environment variables only.",
            DOTENV_PATH
        ),
    }

    if std::env::var("SUNO_BASE_URL").is_err() {
        tracing::warn!(
            "SUNO_BASE_URL is not set. Requests will fail until SUNO_BASE_URL is provided."
        );
    }

    tracing::info!("Starting Suno MCP server on stdio transport");

    let service = EnvironmentService::new().serve(stdio()).await?;

    service.waiting().await?;

    Ok(())
}
