use std::fs;

use anyhow::{bail, Context, Result};

use crate::config;
use crate::registry::{packages, tools};
use crate::ui::style;

use super::install::launch_editor;

/// `aimgr edit [name]`. With no name → global config. With a name:
///   1. custom tool def → edit it
///   2. custom package def → edit it
///   3. built-in tool → fork to custom, then edit
///   4. built-in package → fork to custom, then edit
pub fn run(name: Option<&str>) -> Result<()> {
    let Some(n) = name else {
        let path = config::config_file()?;
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
        }
        if !path.exists() {
            fs::write(&path, "tools = [\"claude\"]\npackages = []\n")
                .with_context(|| format!("writing {}", path.display()))?;
        }
        return launch_editor(&path);
    };

    let custom_tool_path = tools::custom::path_for(n)?;
    if custom_tool_path.exists() {
        return launch_editor(&custom_tool_path);
    }
    let custom_pkg_path = packages::custom::path_for(n)?;
    if custom_pkg_path.exists() {
        return launch_editor(&custom_pkg_path);
    }

    if let Some(builtin_tool) = tools::builtin::by_name(n) {
        if let Some(parent) = custom_tool_path.parent() {
            fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
        }
        let text =
            toml::to_string_pretty(&builtin_tool).context("serializing built-in tool for fork")?;
        fs::write(&custom_tool_path, text)
            .with_context(|| format!("writing {}", custom_tool_path.display()))?;
        println!(
            "{} forked built-in tool `{n}` to {} {}",
            style::ok_mark(),
            custom_tool_path.display(),
            style::dim("(custom overrides take effect immediately)")
        );
        return launch_editor(&custom_tool_path);
    }

    if let Some(builtin_pkg) = packages::builtin::by_name(n) {
        if let Some(parent) = custom_pkg_path.parent() {
            fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
        }
        let text = toml::to_string_pretty(&builtin_pkg)
            .context("serializing built-in package for fork")?;
        fs::write(&custom_pkg_path, text)
            .with_context(|| format!("writing {}", custom_pkg_path.display()))?;
        println!(
            "{} forked built-in package `{n}` to {} {}",
            style::ok_mark(),
            custom_pkg_path.display(),
            style::dim("(custom overrides take effect immediately)")
        );
        return launch_editor(&custom_pkg_path);
    }

    bail!("no tool or package `{n}` known")
}
