use colored::Colorize;

use crate::errors::KamError;
use crate::template::TemplateCacheManager;
use crate::utils::Utils;

use super::args::{TmplArgs, TmplCommands};
use super::{export, import, pull};

// 模板命令的入口，就是处理各种模板相关的操作
/// AUTO-GENERATED BY Kam/scripts/add_missing_docs.py: placeholder documentation for public function 'run'. Replace with real documentation. (2025-12-30T22:23:21Z)
///
/// # Errors
/// Returns `KamError` if template operations fail (I/O errors, template not found, import/export failures).
pub fn run(args: TmplArgs) -> Result<(), KamError> {
    match args.command {
        TmplCommands::List => list_templates(),
        TmplCommands::Import { path, name, force } => import::import_template(&path, name, force),
        TmplCommands::Pull { url, global, quiet } => pull::run_pull(url.as_deref(), global, quiet),
        TmplCommands::Update { global, quiet } => pull::run_update(global, quiet),
        TmplCommands::Export {
            templates,
            output,
            force,
        } => export::export_template(&templates, &output, force),
        TmplCommands::Remove { name } => remove_template(&name),
        TmplCommands::Path => show_cache_path(),
    }
}

fn list_templates() -> Result<(), KamError> {
    let templates = TemplateCacheManager::list_local_templates()?;

    if templates.is_empty() {
        Utils::warn(crate::i18n::tr("tmpl.no_templates_in_cache"));
        println!();
        Utils::info(&trf!("tmpl.use_import_command", "kam tmpl import".bold()));
    } else {
        Utils::section("Templates in Cache");
        for template in &templates {
            Utils::info(template);
        }
        println!();
        Utils::success(format!("{} template(s) available", templates.len()));
    }

    Ok(())
}

fn remove_template(name: &str) -> Result<(), KamError> {
    TemplateCacheManager::remove_template(name)?;
    Utils::success(format!("Template '{name}' removed successfully"));
    Ok(())
}

fn show_cache_path() -> Result<(), KamError> {
    let cache_dir = TemplateCacheManager::get_cache_dir()?;
    println!("{}", cache_dir.display());
    Ok(())
}
