use crate::cli::{eval, err, ok, DEFAULT_PORT};
use anyhow::Result;
use clap::Parser;

#[derive(Parser)]
pub struct Args {
    /// First node name.
    pub from: String,
    /// Second node name.
    pub to: String,
    #[arg(long, default_value_t = 5)]
    pub timeout_secs: u64,
    #[arg(long, default_value_t = DEFAULT_PORT)]
    pub port: u16,
}

pub fn run(args: Args) -> Result<()> {
    let code = format!(
        "return window.adomStep ? window.adomStep.measure({}, {}) : {{ error: 'adomStep not loaded' }};",
        serde_json::to_string(&args.from).unwrap(),
        serde_json::to_string(&args.to).unwrap()
    );
    let result = eval::eval_snippet(&code, args.timeout_secs, args.port, true)?;
    if let Some(e) = result.get("error").and_then(|v| v.as_str()) {
        err(format!("measure failed: {e}"));
        return Err(anyhow::anyhow!("{e}"));
    }
    let d = result
        .get("distance_mm")
        .and_then(|v| v.as_f64())
        .unwrap_or(0.0);
    ok(format!(
        "measured {} → {} = {:.3} mm",
        args.from, args.to, d
    ));
    println!("{}", serde_json::to_string_pretty(&result)?);
    Ok(())
}