use std::error::Error;

use clap::Parser;
use letterbox_notmuch::Notmuch;
use letterbox_server::nm::label_unprocessed;
use sqlx::postgres::PgPool;
use tracing::info;

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    #[arg(short, long)]
    newsreader_database_url: String,
    #[arg(short, long, default_value = "10")]
    /// Set to 0 to process all matches
    messages_to_process: usize,
    #[arg(short, long, default_value = "false")]
    execute: bool,
    /// Process messages matching this notmuch query
    #[arg(short, long, default_value = "tag:unprocessed")]
    query: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let cli = Cli::parse();
    let _guard = xtracing::init(env!("CARGO_BIN_NAME"))?;
    build_info::build_info!(fn bi);
    info!("Build Info: {}", letterbox_shared::build_version(bi));
    let pool = PgPool::connect(&cli.newsreader_database_url).await?;
    let nm = Notmuch::default();
    let limit = if cli.messages_to_process > 0 {
        Some(cli.messages_to_process)
    } else {
        None
    };
    label_unprocessed(&nm, &pool, !cli.execute, limit, &cli.query).await?;
    Ok(())
}
