use super::util::{current_dir, is_iso_date, today_iso_date};
use koala_health::{record_friction, write_probe, FrictionOutcome, FrictionReport, Probe};
use std::path::PathBuf;
use std::process::ExitCode;

pub fn probe(root: Option<PathBuf>, date: Option<String>, label: Option<String>) -> ExitCode {
    let root = root.unwrap_or_else(current_dir);
    let date = match date {
        Some(d) => d,
        None => match today_iso_date() {
            Some(d) => d,
            None => {
                eprintln!("error: cannot determine today's date; pass --date YYYY-MM-DD");
                return ExitCode::from(1);
            }
        },
    };
    if !is_iso_date(&date) {
        eprintln!("error: date must be YYYY-MM-DD; got `{date}`");
        return ExitCode::from(2);
    }
    let probe = Probe { date, label };
    match write_probe(&root, &probe) {
        Ok(path) => {
            println!("wrote {}", path.display());
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("error: cannot write probe: {e}");
            ExitCode::from(1)
        }
    }
}

pub fn friction(
    root: Option<PathBuf>,
    date: Option<String>,
    count: usize,
    notes: Vec<String>,
) -> ExitCode {
    let root = root.unwrap_or_else(current_dir);
    let date = match date {
        Some(d) => d,
        None => match today_iso_date() {
            Some(d) => d,
            None => {
                eprintln!("error: cannot determine today's date; pass --date YYYY-MM-DD");
                return ExitCode::from(1);
            }
        },
    };
    if !is_iso_date(&date) {
        eprintln!("error: date must be YYYY-MM-DD; got `{date}`");
        return ExitCode::from(2);
    }
    let report = FrictionReport { date, count, notes };
    match record_friction(&root, &report) {
        Ok(FrictionOutcome::BelowThreshold { count }) => {
            println!("friction count: {count} — below threshold, no redline.");
            ExitCode::SUCCESS
        }
        Ok(FrictionOutcome::RedlineWritten { path, count }) => {
            println!(
                "friction count: {count} — REDLINE written to {}.",
                path.display()
            );
            println!("CI will open a `health-redline` GitHub issue on next push to main.");
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("error: cannot write friction redline: {e}");
            ExitCode::from(1)
        }
    }
}
