use std::path::Path;

use super::embedded::{EMBEDDED_SKILLS, EmbeddedSkill};

pub fn install_builtin_skills(target_dir: &Path) {
    for skill in EMBEDDED_SKILLS {
        let skill_dir = target_dir.join(skill.name);

        if skill_dir.exists() {
            continue;
        }

        match install_one(skill, &skill_dir) {
            Ok(()) => {
                tracing::info!(name = skill.name, dir = %skill_dir.display(), "Installed built-in skill");
            }
            Err(e) => {
                tracing::warn!(name = skill.name, error = %e, "Failed to install built-in skill");
            }
        }
    }
}

fn install_one(skill: &EmbeddedSkill, target_dir: &Path) -> Result<(), String> {
    let decompressed = zstd::decode_all(skill.data).map_err(|e| format!("zstd decode: {}", e))?;

    let mut archive = tar::Archive::new(decompressed.as_slice());
    archive
        .unpack(target_dir.parent().unwrap_or_else(|| Path::new(".")))
        .map_err(|e| format!("tar unpack: {}", e))?;

    Ok(())
}
