use super::util::current_dir;
use koala_health::{
    build_trend, collect_snapshot, list_redlines, redlines_from, render_markdown,
    render_trend_report, sync_redlines, History,
};
use std::path::PathBuf;
use std::process::ExitCode;

pub fn run(root: Option<PathBuf>, write: bool) -> ExitCode {
    let root = root.unwrap_or_else(current_dir);
    let snap = collect_snapshot(&root);
    let body = render_markdown(&snap);
    print!("{body}");

    let active_redlines = redlines_from(&snap);
    if !active_redlines.is_empty() {
        println!("\nActive redlines (this snapshot):");
        for r in &active_redlines {
            println!(
                "  ✗ {name} = {value}  (id: {id})",
                name = r.metric_name,
                value = r.value,
                id = r.metric_id,
            );
        }
    } else {
        let on_disk = list_redlines(&root);
        if !on_disk.is_empty() {
            println!(
                "\n{} stale redline file(s) on disk; `health update` will clean them up.",
                on_disk.len()
            );
        }
    }

    if write {
        let target = root.join("wiki/health.md");
        if let Some(parent) = target.parent() {
            if let Err(e) = std::fs::create_dir_all(parent) {
                eprintln!("error: cannot create {}: {e}", parent.display());
                return ExitCode::from(1);
            }
        }
        if let Err(e) = std::fs::write(&target, body) {
            eprintln!("error: cannot write {}: {e}", target.display());
            return ExitCode::from(1);
        }

        let mut history = History::read(&root);
        history.upsert(&snap);
        if let Err(e) = history.write(&root) {
            eprintln!("error: cannot write history: {e}");
            return ExitCode::from(1);
        }

        let diff = match sync_redlines(&root, &active_redlines) {
            Ok(d) => d,
            Err(e) => {
                eprintln!("error: cannot sync redlines: {e}");
                return ExitCode::from(1);
            }
        };

        println!();
        println!("wrote {}", target.display());
        println!("wrote {}", History::path(&root).display());
        if !diff.added.is_empty() {
            println!("redlines opened: {}", diff.added.join(", "));
        }
        if !diff.removed.is_empty() {
            println!("redlines cleared: {}", diff.removed.join(", "));
        }
    }
    ExitCode::SUCCESS
}

pub fn trend(root: Option<PathBuf>, metric: String, window: usize) -> ExitCode {
    let root = root.unwrap_or_else(current_dir);
    let history = History::read(&root);
    let mut filtered: Vec<_> = history.for_metric(&metric).cloned().collect();
    if filtered.is_empty() {
        eprintln!("no history entries for metric `{metric}`");
        eprintln!("hint : run `koala-core health update` after a few commits, or check the metric name with `koala-core health show`");
        return ExitCode::from(2);
    }
    if filtered.len() > window {
        let start = filtered.len() - window;
        filtered = filtered.split_off(start);
    }
    let report = build_trend(&metric, filtered);
    print!("{}", render_trend_report(&report));
    ExitCode::SUCCESS
}
