#![cfg(feature = "cli")]

use anyhow::Context;
use clap::{Parser, Subcommand};
use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};

use cedros_sunscreen::config::{Config, HttpServerConfig};

#[derive(Debug, Parser)]
#[command(name = "cedros-sunscreen")]
#[command(about = "Sanctions screening API for blockchain addresses")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Debug, Subcommand)]
enum Commands {
    /// Run the HTTP server
    Serve {
        #[arg(long, default_value = "127.0.0.1:8080")]
        bind_addr: String,

        #[arg(long = "cors-origin", value_name = "ORIGIN")]
        cors_allowed_origins: Vec<String>,
    },
    /// Run a single ingestion cycle and exit
    Ingest,
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    init_tracing();
    dotenvy::dotenv().ok();
    let cli = Cli::parse();
    let config = Config::from_env().context("failed to load config")?;

    match cli.command {
        Commands::Serve {
            bind_addr,
            cors_allowed_origins,
        } => {
            let http_config = HttpServerConfig {
                bind_addr,
                cors_allowed_origins,
            };
            cedros_sunscreen::run_http_server(config, http_config)
                .await
                .map_err(anyhow::Error::from)
        }
        Commands::Ingest => {
            let storage =
                cedros_sunscreen::Storage::from_database_url(&config.database_url).await?;
            storage.migrate().await.context("failed to run migrations")?;
            let ingestion = cedros_sunscreen::IngestionService::new(
                config.ofac_xml_url,
                config.ransomware_url,
            );
            let count = ingestion
                .run_cycle(&storage.address_repo, &storage.country_repo)
                .await?;
            println!("ingested {count} addresses");
            Ok(())
        }
    }
}

fn init_tracing() {
    let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
    tracing_subscriber::registry()
        .with(env_filter)
        .with(fmt::layer().with_target(false))
        .init();
}
