//! Skill command handlers.

use crate::cli::args::{GlobalArgs, SkillCommand, SkillInstallArgs};
use crate::cli::output::OutputWriter;
use crate::error::{ExitStatus, Result};
use crate::skill::{install_skill, uninstall_skill, update_skill};
use crate::skill::installer::get_skill_status;

/// Handle skill commands
pub async fn handle_skill(cmd: SkillCommand, global: &GlobalArgs) -> Result<ExitStatus> {
    match cmd {
        SkillCommand::Install(args) => handle_install(args, global).await,
        SkillCommand::Uninstall => handle_uninstall(global).await,
        SkillCommand::Update => handle_update(global).await,
        SkillCommand::Status => handle_status(global).await,
    }
}

async fn handle_install(args: SkillInstallArgs, global: &GlobalArgs) -> Result<ExitStatus> {
    let status = install_skill(args.project, args.force)?;

    let writer = OutputWriter::new(global);
    writer.write_value(&status)?;

    if !global.quiet {
        eprintln!(
            "GDELT skill installed at: {}",
            status.location.as_deref().unwrap_or("unknown")
        );
        if status.is_project_local {
            eprintln!("Note: Installed as project-local skill.");
        }
    }

    Ok(ExitStatus::Success)
}

async fn handle_uninstall(global: &GlobalArgs) -> Result<ExitStatus> {
    let status = uninstall_skill()?;

    let writer = OutputWriter::new(global);
    writer.write_value(&status)?;

    if !global.quiet {
        eprintln!(
            "GDELT skill uninstalled from: {}",
            status.location.as_deref().unwrap_or("unknown")
        );
    }

    Ok(ExitStatus::Success)
}

async fn handle_update(global: &GlobalArgs) -> Result<ExitStatus> {
    let status = update_skill()?;

    let writer = OutputWriter::new(global);
    writer.write_value(&status)?;

    if !global.quiet {
        eprintln!(
            "GDELT skill updated to version {}",
            status.version.as_deref().unwrap_or("unknown")
        );
    }

    Ok(ExitStatus::Success)
}

async fn handle_status(global: &GlobalArgs) -> Result<ExitStatus> {
    let status = get_skill_status()?;

    let writer = OutputWriter::new(global);
    writer.write_value(&status)?;

    if !global.quiet {
        if status.installed {
            eprintln!("GDELT skill is installed");
            eprintln!("  Location: {}", status.location.as_deref().unwrap_or("unknown"));
            eprintln!("  Version: {}", status.version.as_deref().unwrap_or("unknown"));
            if status.is_project_local {
                eprintln!("  Type: Project-local");
            } else {
                eprintln!("  Type: Global");
            }
        } else {
            eprintln!("GDELT skill is not installed");
            eprintln!("Run 'gdelt skill install' to install it.");
        }
    }

    Ok(ExitStatus::Success)
}
