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

/// Toggle a chipsmith overlay layer on/off — CLI parity for the buttons
/// in the Footprint / Heatsink / Solder-jet tabs.
///
/// Supported layer kinds:
///   datasheet|kicad|fusion|altium     individual footprint sources
///   stock                              service-kicad authoritative ghost
///                                      (will fetch on first show)
///   all-sources                        every available user footprint at once
///   faux-pcb                           1.6 mm FR4 plate w/ CSG-drilled holes
///   heatsink                           auto-generated via grid under EP
///   solderjet                          300 µm domes per pad
///   pin1                               user-placed pin-1 indicator
#[derive(Parser)]
pub struct Args {
    /// Layer kind to toggle.
    pub kind: String,
    /// "on" or "off" (case-insensitive).
    pub state: String,
    #[arg(long, default_value_t = DEFAULT_PORT)]
    pub port: u16,
}

pub fn run(args: Args) -> Result<()> {
    let on = match args.state.to_lowercase().as_str() {
        "on" | "true" | "1" | "show" => true,
        "off" | "false" | "0" | "hide" => false,
        other => {
            err(format!("invalid state '{other}', expected on|off"));
            return Err(anyhow::anyhow!("bad state"));
        }
    };
    let snippet = match args.kind.to_lowercase().as_str() {
        "datasheet" | "kicad" | "fusion" | "altium" => format!(
            "return window.adomChipsmith.setFootprintOverlay('{}', {});",
            args.kind, on
        ),
        "stock" => format!(
            // Stock-library overlay is a two-step transaction: load (if
            // not cached) then toggle. Fold into one snippet so a single
            // CLI invocation Just Works.
            "{{ const r = await window.adomChipsmith.loadStockLibraryOverlay({{force:false}}); \
               if (r && r.error) return r; \
               return window.adomChipsmith.setStockOverlayVisible({on}); }}",
            on = on
        ),
        "all-sources" => format!("return window.adomChipsmith.setAllFootprintOverlays({on});"),
        "faux-pcb" => format!("return window.adomChipsmith.setFauxPcbVisible({on});"),
        "heatsink" => format!("return window.adomChipsmith.setHeatsinkVisible({on});"),
        "solderjet" | "solder-jet" => format!(
            "return window.adomChipsmith.setSolderJetVisible({on});"
        ),
        "pin1" => {
            if on {
                err("'pin1 on' is ambiguous — use `place-pin1 --corner ...` instead".to_string());
                return Err(anyhow::anyhow!("use place-pin1"));
            }
            "return window.adomChipsmith.removePin1Indicator();".to_string()
        }
        other => {
            err(format!("unknown kind '{other}'"));
            return Err(anyhow::anyhow!("bad kind"));
        }
    };
    let v = eval_snippet(&snippet, 8, args.port, true)?;
    if let Some(e) = v.get("error").and_then(|x| x.as_str()) {
        err(format!("set-overlay: {e}"));
        return Err(anyhow::anyhow!("toggle failed"));
    }
    ok(format!("set-overlay {} {}: {}", args.kind, if on {"on"} else {"off"}, serde_json::to_string(&v).unwrap_or_default()));
    Ok(())
}