mod config;
mod run_config;
mod runner;
mod strategy;
mod worker;

use chrono::{Duration, Utc};
use config::ExecutorConfig;
use swym_dal::repo::paper_run;
use tracing::{info, warn};
use tracing_subscriber::{EnvFilter, fmt};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    fmt()
        .with_env_filter(EnvFilter::from_default_env())
        .init();

    let config_path = std::env::args()
        .nth(1)
        .unwrap_or_else(|| "config/paper_executor.json".to_owned());

    let config: ExecutorConfig = {
        let file = std::fs::File::open(&config_path)?;
        serde_json::from_reader(std::io::BufReader::new(file))?
    };

    info!(?config_path, "loaded executor config");

    // Connect to database (runs migrations)
    let pool = swym_dal::connect(&config.database).await?;

    // Reset stale running runs back to queued
    let stale_cutoff = Utc::now() - Duration::seconds(config.stale_timeout_secs);
    let reset_count = paper_run::reset_stale_running(&pool, stale_cutoff).await?;
    if reset_count > 0 {
        warn!(reset_count, "reset stale running runs back to queued");
    }

    // Start the poll loop
    worker::run_poll_loop(pool, &config).await;

    Ok(())
}
