#!/bin/bash

# Validate a skill follows the Agent Skills specification

set -e

echo "Validating skill at: $1"

# Check if SKILL.md exists
if [ ! -f "$1/SKILL.md" ]; then
    echo "ERROR: SKILL.md file is required"
    exit 1
fi

# Check if name field exists and matches directory name (convert underscores to hyphens)
SKILL_NAME=$(grep -E "^name:" "$1/SKILL.md" | cut -d " " -f 2 | tr -d ' ')
DIRECTORY_NAME=$(basename "$1" | tr '_' '-')

if [ "$SKILL_NAME" != "$DIRECTORY_NAME" ]; then
    echo "ERROR: Skill name '$SKILL_NAME' doesn't match directory name '$DIRECTORY_NAME' (underscores converted to hyphens)"
    exit 1
fi

# Check if description field exists
if ! grep -q "^description:" "$1/SKILL.md"; then
    echo "ERROR: description field is required"
    exit 1
fi

# Check name format (lowercase alphanumeric and hyphens only)
if ! echo "$SKILL_NAME" | grep -q "^[a-z0-9-]*$"; then
    echo "ERROR: Skill name can only contain lowercase alphanumeric characters and hyphens"
    exit 1
fi

# Check name doesn't start or end with hyphen
if [[ "$SKILL_NAME" == -* ]] || [[ "$SKILL_NAME" == *- ]]; then
    echo "ERROR: Skill name cannot start or end with hyphen"
    exit 1
fi

# Check name doesn't contain consecutive hyphens
if echo "$SKILL_NAME" | grep -q -e "--"; then
    echo "ERROR: Skill name cannot contain consecutive hyphens"
    exit 1
fi

# Check description length (1-1024 characters)
DESCRIPTION=$(grep "^description:" "$1/SKILL.md" | cut -d " " -f 2-)
DESCRIPTION_LENGTH=${#DESCRIPTION}

if [ "$DESCRIPTION_LENGTH" -lt 1 ] || [ "$DESCRIPTION_LENGTH" -gt 1024 ]; then
    echo "ERROR: Description must be 1-1024 characters"
    exit 1
fi

echo "✓ Skill validation passed: $SKILL_NAME"
echo "✓ Name format: $SKILL_NAME"
echo "✓ Description length: $DESCRIPTION_LENGTH characters"
echo "✓ Directory structure: Valid"

# Check for optional directories
if [ -d "$1/scripts" ]; then
    echo "✓ Optional scripts/ directory found"
fi

if [ -d "$1/references" ]; then
    echo "✓ Optional references/ directory found"
fi

if [ -d "$1/assets" ]; then
    echo "✓ Optional assets/ directory found"
fi