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

#[derive(Parser)]
pub struct Args {
    #[command(subcommand)]
    pub action: Action,

    #[arg(long, default_value_t = DEFAULT_PORT, global = true)]
    pub port: u16,
}

#[derive(Subcommand)]
pub enum Action {
    /// Print the detected pin count + per-pin side classification.
    Count,
    /// Print all pin clusters with centroids (mm) — feeds footprint-matching tools.
    List,
    /// Isolate a single pin by 1-based index. Use `pins list` to see available IDs.
    Isolate {
        /// 1-based pin index.
        id: u32,
    },
    /// Restore visibility on every pin.
    ShowAll,
}

pub fn run(args: Args) -> Result<()> {
    match args.action {
        Action::Count => {
            let r = eval::eval_snippet(
                "return window.adomStep.pinCount();",
                5,
                args.port,
                true,
            )?;
            ok(format!("{} pins", r));
        }
        Action::List => {
            let r = eval::eval_snippet(
                "return window.adomStep.pins();",
                5,
                args.port,
                true,
            )?;
            println!("{}", serde_json::to_string_pretty(&r)?);
        }
        Action::Isolate { id } => {
            let code = format!("return window.adomStep.isolatePin({});", id);
            let r = eval::eval_snippet(&code, 5, args.port, true)?;
            ok(format!("isolated pin {id}: {r}"));
        }
        Action::ShowAll => {
            eval::eval_snippet("return window.adomStep.showAllPins();", 5, args.port, true)?;
            ok("showed all pins");
        }
    }
    Ok(())
}