use crate::cli::{err, hint, ok, DEFAULT_PORT};
use anyhow::Result;
use clap::Parser;
use std::time::Duration;

#[derive(Parser)]
pub struct Args {
    #[arg(long, default_value_t = DEFAULT_PORT)]
    pub port: u16,
    /// Print result as a single JSON line (machine-parseable).
    /// Per gallia/skills/adom-cli-design — every status command supports
    /// `--json` so AI agents can consume it without scraping OK:/ERROR: lines.
    #[arg(long)]
    pub json: bool,
}

pub fn run(args: Args) -> Result<()> {
    let url = format!("http://127.0.0.1:{}/health", args.port);
    match ureq::get(&url).timeout(Duration::from_secs(2)).call() {
        Ok(resp) => {
            let body: serde_json::Value = resp.into_json()?;
            if args.json {
                println!(
                    "{}",
                    serde_json::json!({"ok": true, "port": args.port, "body": body})
                );
            } else {
                ok(format!("healthy on port {} — {}", args.port, body));
            }
            Ok(())
        }
        Err(e) => {
            if args.json {
                println!(
                    "{}",
                    serde_json::json!({"ok": false, "port": args.port, "error": format!("{e}")})
                );
            } else {
                err(format!("not running on port {}: {e}", args.port));
                hint("start it with `adom-chipsmith view <file.step>`");
            }
            Err(anyhow::anyhow!("not running"))
        }
    }
}