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

#[derive(Parser)]
pub struct Args {
    /// Skip copying the binary; only drop SKILL.md.
    #[arg(long)]
    pub skill_only: bool,
}

pub fn run(args: Args) -> Result<()> {
    let home = std::env::var("HOME").unwrap_or_else(|_| "/home/adom".to_string());

    // 1) Drop SKILL.md so Claude Code agents pick up the chipsmith skill.
    let skill_dir = format!("{home}/.claude/skills/adom-chipsmith");
    if let Err(e) = std::fs::create_dir_all(&skill_dir) {
        err(format!("create {skill_dir}: {e}"));
        return Err(e.into());
    }
    let skill_md = include_str!("../../SKILL.md");
    let skill_path = format!("{skill_dir}/SKILL.md");
    std::fs::write(&skill_path, skill_md)?;
    ok(format!("wrote {skill_path}"));

    if args.skill_only {
        return Ok(());
    }

    // 2) Copy the running binary to ~/.local/bin/adom-chipsmith so it's
    //    on PATH for terminal use without an absolute path. Per the
    //    adom-cli-design skill: every Adom CLI installs into the
    //    user's local bin via this command.
    let bin_dir = format!("{home}/.local/bin");
    if let Err(e) = std::fs::create_dir_all(&bin_dir) {
        err(format!("create {bin_dir}: {e}"));
        return Err(e.into());
    }
    let target = format!("{bin_dir}/adom-chipsmith");
    let current_exe = match std::env::current_exe() {
        Ok(p) => p,
        Err(e) => {
            err(format!("can't locate current exe: {e}"));
            return Err(e.into());
        }
    };
    // Skip overwrite if the running binary IS already the target (avoids
    // ETXTBSY when self-replacing).
    if current_exe != std::path::PathBuf::from(&target) {
        if let Err(e) = std::fs::copy(&current_exe, &target) {
            err(format!("copy {} → {}: {}", current_exe.display(), target, e));
            return Err(e.into());
        }
        ok(format!("copied binary → {target}"));
    } else {
        ok(format!("binary already at {target}"));
    }

    if !std::env::var("PATH").unwrap_or_default().contains(&bin_dir) {
        hint(format!(
            "add {bin_dir} to PATH (e.g. via ~/.bashrc) — currently not on PATH"
        ));
    }

    Ok(())
}