use crate::cli::InstallArgs;
use crate::ui::{ok, warn};
use clap::CommandFactory;
use std::borrow::Cow;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::time::Duration;

/// Bundled SKILL.md — used only when the wiki is unreachable.
/// SAFETY NET — do not rely on for release propagation.
const FALLBACK_SKILL_MD: &str = include_str!("../SKILL.md");

const SKILL_URL: &str = "https://wiki.adom.inc/blob/app/adom-step2glb/SKILL.md";

fn fetch_skill_md() -> Cow<'static, str> {
    match ureq::get(SKILL_URL).timeout(Duration::from_secs(5)).call() {
        Ok(r) => r.into_string().map(Cow::Owned).unwrap_or(Cow::Borrowed(FALLBACK_SKILL_MD)),
        Err(_) => {
            warn("wiki unreachable — installing bundled SKILL.md (may be stale)");
            Cow::Borrowed(FALLBACK_SKILL_MD)
        }
    }
}

pub fn run(_args: InstallArgs) {
    let home = std::env::var("HOME").unwrap_or_else(|_| "/home/adom".into());

    // 1. Skill file → ~/.claude/skills/step2glb/SKILL.md (fetched fresh from wiki).
    let skill_dir = PathBuf::from(&home).join(".claude/skills/step2glb");
    fs::create_dir_all(&skill_dir).expect("mkdir skill_dir");
    fs::write(skill_dir.join("SKILL.md"), fetch_skill_md().as_ref()).expect("write skill");
    ok(format!("skill installed at {}/SKILL.md", skill_dir.display()));

    // 2. Bash completions → ~/.local/share/bash-completion/completions/step2glb
    let comp_dir = PathBuf::from(&home).join(".local/share/bash-completion/completions");
    fs::create_dir_all(&comp_dir).ok();
    let mut cmd = crate::cli::Cli::command();
    let mut buf = Vec::new();
    clap_complete::generate(clap_complete::Shell::Bash, &mut cmd, "step2glb", &mut buf);
    fs::write(comp_dir.join("step2glb"), &buf).ok();
    ok(format!("bash completions at {}/step2glb", comp_dir.display()));

    // 3. .bashrc nudge (append once, idempotent).
    let bashrc_path = PathBuf::from(&home).join(".bashrc");
    let existing = fs::read_to_string(&bashrc_path).unwrap_or_default();
    if !existing.contains("# step2glb completions") {
        if let Ok(mut f) = fs::OpenOptions::new().append(true).open(&bashrc_path) {
            let _ = f.write_all(b"\n# step2glb completions\neval \"$(step2glb completions bash 2>/dev/null)\"\n");
            ok(".bashrc: completion hook appended (open a new shell or `source ~/.bashrc`)");
        }
    }

    // No venv, no Python. That lives on the shared service-step2glb container now.
    println!();
    ok("step2glb installed. Try `step2glb health` to reach the shared service.");
}