use night_fury_core::BrowserSession;
use serde_json::json;

use crate::output::{output_err, output_ok, OutputMode};

pub async fn dispatch(session: &BrowserSession, parts: &[&str], mode: OutputMode) {
    let sub = parts.first().copied().unwrap_or("");
    match sub {
        "start" => start(session, mode).await,
        "stop" => stop(session, mode).await,
        other => output_err(
            mode,
            &format!("Unknown coverage subcommand: {other}. Use 'start' or 'stop'"),
        ),
    }
}

async fn start(session: &BrowserSession, mode: OutputMode) {
    match session.start_coverage().await {
        Ok(()) => output_ok(
            mode,
            "Coverage collection started",
            json!({"action": "coverage_start"}),
        ),
        Err(e) => output_err(mode, &e.to_string()),
    }
}

async fn stop(session: &BrowserSession, mode: OutputMode) {
    match session.stop_coverage().await {
        Ok(report) => {
            let js_count = report.js_entries.len();
            let css_count = report.css_entries.len();
            let human =
                format!("Coverage collected: {js_count} JS entries, {css_count} CSS entries");
            output_ok(
                mode,
                &human,
                json!({
                    "action": "coverage_stop",
                    "js_entries": js_count,
                    "css_entries": css_count,
                    "report": serde_json::to_value(&report).unwrap_or(json!(null)),
                }),
            );
        }
        Err(e) => output_err(mode, &e.to_string()),
    }
}
