#!/usr/bin/env bash
# Lint SKILL.md files: validates frontmatter and length.
# Exit 0 = all good. Exit 1 = at least one error.

set -u

errors=0
warnings=0

shopt -s nullglob

for skill_file in skills/*/SKILL.md; do
    skill_dir=$(dirname "$skill_file")
    skill_name=$(basename "$skill_dir")

    # Frontmatter must start on line 1 with ---
    first_line=$(head -n 1 "$skill_file")
    if [[ "$first_line" != "---" ]]; then
        echo "ERROR: $skill_file does not start with frontmatter ('---' on line 1)"
        errors=$((errors + 1))
        continue
    fi

    # Frontmatter must contain 'name:' and 'description:' before the closing ---
    frontmatter=$(awk '/^---$/{c++; if (c==2) exit} c==1' "$skill_file")
    if ! grep -q '^name:' <<<"$frontmatter"; then
        echo "ERROR: $skill_file frontmatter missing 'name:' field"
        errors=$((errors + 1))
    fi
    if ! grep -q '^description:' <<<"$frontmatter"; then
        echo "ERROR: $skill_file frontmatter missing 'description:' field"
        errors=$((errors + 1))
    fi

    # Frontmatter 'name' should match directory name
    name_value=$(grep '^name:' <<<"$frontmatter" | head -n 1 | sed 's/^name:[[:space:]]*//')
    if [[ -n "$name_value" && "$name_value" != "$skill_name" ]]; then
        echo "ERROR: $skill_file name '$name_value' does not match directory '$skill_name'"
        errors=$((errors + 1))
    fi

    # Length warning at 400 lines
    line_count=$(wc -l <"$skill_file")
    if (( line_count > 400 )); then
        echo "WARN: $skill_file is $line_count lines (target <400)"
        warnings=$((warnings + 1))
    fi
done

# Summary
echo
echo "Skill lint complete: $errors error(s), $warnings warning(s)"

if (( errors > 0 )); then
    exit 1
fi
exit 0
