#!/bin/bash
# check-togen-skill.sh — freshness self-check for the Togen skill (DVI-980).
# Greps every "file:line" / "file.py:NNN" anchor referenced in the skill and
# flags any anchor whose file is missing. Line numbers drift as app.py grows,
# so a present-but-moved anchor is a prompt to re-verify with grep, not an error.
#
# Usage:  scripts/check-togen-skill.sh
# Exit:   0 = all referenced files exist; 1 = one or more missing.

set -uo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SKILL_DIR="$REPO_ROOT/.claude/skills/togen"

if [ ! -d "$SKILL_DIR" ]; then
    echo "ERROR: skill dir not found: $SKILL_DIR" >&2
    exit 1
fi

echo "Checking Togen skill anchors under $SKILL_DIR"
echo

# Match anchors like:  togen/app.py:193  clickup_client.py:20  assistant.py:31
# Capture the file path (allowing subdirs) preceding :NNN.
missing=0
checked=0

# Collect unique "path:line" tokens from all skill markdown.
mapfile -t anchors < <(grep -rhoE '[A-Za-z0-9_./-]+\.(py|sh|json|service|html):[0-9]+' "$SKILL_DIR" 2>/dev/null | sort -u)

for anchor in "${anchors[@]}"; do
    file="${anchor%%:*}"
    line="${anchor##*:}"
    checked=$((checked+1))
    # Resolve relative to repo root; also try togen/ prefix for bare module names.
    if [ -f "$REPO_ROOT/$file" ]; then
        path="$REPO_ROOT/$file"
    elif [ -f "$REPO_ROOT/togen/$file" ]; then
        path="$REPO_ROOT/togen/$file"
    else
        echo "MISSING FILE: $anchor  (referenced file not found)"
        missing=$((missing+1))
        continue
    fi
    total_lines="$(wc -l < "$path")"
    if [ "$line" -gt "$total_lines" ]; then
        echo "STALE LINE?:  $anchor  (file has $total_lines lines — re-verify with grep)"
    fi
done

echo
echo "Checked $checked anchor(s); $missing missing file(s)."
[ "$missing" -eq 0 ]
