#!/usr/bin/env bash
set -euo pipefail

# Configuration
REPO_URL="https://git.tswf.io/ai-agents/ai-agent-skills.git"
TARGET_DIR=".agents/skills"

# Get script directory for relative paths
if [ -n "${BASH_SOURCE[0]+x}" ]; then
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    cd "$SCRIPT_DIR"
fi

# Create target directory if it doesn't exist
mkdir -p "$TARGET_DIR"

# Create temporary directory
TEMP_DIR=$(mktemp -d)
echo "Created temporary directory: $TEMP_DIR"

# Ensure cleanup on exit
cleanup() {
    if [ -d "$TEMP_DIR" ]; then
        rm -rf "$TEMP_DIR"
        echo "Cleaned up temporary directory"
    fi
}
trap cleanup EXIT

# Clone repository
echo "Cloning repository $REPO_URL..."
git clone --depth 1 "$REPO_URL" "$TEMP_DIR/repo"

# Check if clone was successful
if [ ! -d "$TEMP_DIR/repo" ]; then
    echo "Error: Failed to clone repository"
    exit 1
fi

# Find and process skills (subdirectories in the cloned repo)
SKILLS_FOUND=0
for skill_path in "$TEMP_DIR/repo/skills"/*/; do
    # Skip if no directories found (glob returns literal pattern if no match)
    [ -d "$skill_path" ] || continue
    
    skill_name=$(basename "$skill_path")
    target_skill_path="$TARGET_DIR/$skill_name"
    
    # Remove existing skill if present
    if [ -e "$target_skill_path" ]; then
        echo "Removing existing skill: $skill_name"
        rm -rf "$target_skill_path"
    fi
    
    # Copy new skill
    echo "Installing skill: $skill_name"
    cp -r "$skill_path" "$target_skill_path"
    
    SKILLS_FOUND=$((SKILLS_FOUND + 1))
done

if [ "$SKILLS_FOUND" -eq 0 ]; then
    echo "Warning: No skills found in repository"
else
    echo "Successfully synchronized $SKILLS_FOUND skill(s) to $TARGET_DIR"
fi
