#!/usr/bin/env bash
# generate-skill-index.sh — Auto-generate SKILL-INDEX.md from skills-lock.json + SKILL.md frontmatter
# This file is called by sync-skills.sh. Output is SKILL-INDEX.md at repo root.
# DO NOT edit SKILL-INDEX.md manually — it is auto-generated.
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
LOCKFILE="$REPO_ROOT/skills-lock.json"
INDEX_FILE="$REPO_ROOT/SKILL-INDEX.md"

if [[ ! -f "$LOCKFILE" ]]; then
  echo "generate-skill-index: ERROR — skills-lock.json not found. Run regenerate-lockfile.sh first." >&2
  exit 1
fi

# Phase categorization — maps each skill to a lifecycle phase
declare -A PHASE_MAP
PHASE_MAP=(
  # Discover
  [survey-context]="Discover"
  [research-first]="Discover"
  [search-skills]="Discover"
  [using-bigpowers]="Discover"
  [map-codebase]="Discover"
  [elaborate-spec]="Discover"
  # Elaborate / Design
  [model-domain]="Design"
  [define-language]="Design"
  [grill-me]="Design"
  [grill-with-docs]="Design"
  [deepen-architecture]="Design"
  [design-interface]="Design"
  [define-success]="Design"
  # Plan
  [scope-work]="Plan"
  [slice-tasks]="Plan"
  [plan-work]="Plan"
  [plan-release]="Plan"
  [plan-refactor]="Plan"
  [assess-impact]="Plan"
  [change-request]="Plan"
  [run-planning]="Plan"
  [seed-conventions]="Plan"
  # Build
  [develop-tdd]="Build"
  [kickoff-branch]="Build"
  [execute-plan]="Build"
  [build-epic]="Build"
  [spike-prototype]="Build"
  [craft-skill]="Build"
  [quick-fix]="Build"
  [setup-environment]="Build"
  [wire-observability]="Build"
  [wire-ci]="Build"
  [publish-package]="Build"
  [align-grid]="Build"
  [orchestrate-project]="Build"
  [guard-git]="Build"
  [hook-commits]="Build"
  [deploy]="Build"
  [smoke-test]="Build"
  [validate-contracts]="Build"
  # Verify
  [verify-work]="Verify"
  [validate-fix]="Verify"
  [audit-code]="Verify"
  [enforce-first]="Verify"
  [run-evals]="Verify"
  [investigate-bug]="Verify"
  [diagnose-root]="Verify"
  [fix-bug]="Verify"
  [inspect-quality]="Verify"
  [request-review]="Verify"
  [respond-review]="Verify"
  [trace-requirement]="Verify"
  # Release
  [release-branch]="Release"
  [commit-message]="Release"
  # Sustain
  [session-state]="Sustain"
  [edit-document]="Sustain"
  [write-document]="Sustain"
  [organize-workspace]="Sustain"
  [reset-baseline]="Sustain"
  [stocktake-skills]="Sustain"
  [evolve-skill]="Sustain"
  [terse-mode]="Sustain"
  [delegate-task]="Sustain"
  [dispatch-agents]="Sustain"
  [simulate-agents]="Sustain"
  [compose-workflow]="Sustain"
  [migrate-spec]="Sustain"
)

# Phase order for display
PHASE_ORDER=("Discover" "Design" "Plan" "Build" "Verify" "Release" "Sustain")

# Column widths
SKILL_COL_WIDTH=28
DESC_COL_WIDTH=56

# Build the index file
{
  echo "# Skill Index — Single Source of Truth"
  echo ""
  echo "> **DO NOT EDIT** — This file is auto-generated by \`scripts/generate-skill-index.sh\`."
  echo "> Edit \`SKILL.md\` source files or \`skills-lock.json\` instead. Run \`bash scripts/sync-skills.sh\` to regenerate."
  echo ""
  echo "**Generated:** $(date -u +%Y-%m-%dT%H:%M:%SZ)"
  echo "**Skills:** $(jq '.skills | length' "$LOCKFILE")"
  echo ""

  # Summary by phase
  echo "---"
  echo ""
  echo "## Quick Navigation by Phase"
  echo ""
  echo "| Phase | Count | Skills |"
  echo "|---|---|---|"
  total=0
  for phase in "${PHASE_ORDER[@]}"; do
    phase_skills=()
    for name in $(jq -r '.skills | keys[]' "$LOCKFILE" | sort); do
      [[ "${PHASE_MAP[$name]:-}" == "$phase" ]] && phase_skills+=("$name")
    done
    count=${#phase_skills[@]}
    total=$((total + count))
    skill_list=$(IFS=,; echo "${phase_skills[*]}" | sed 's/,/, /g')
    echo "| $phase | $count | \`$skill_list\` |"
  done
  echo "| **TOTAL** | **$total** | |"
  echo ""

  # Full reference table
  echo "---"
  echo ""
  echo "## Full Reference Table"
  echo ""
  echo "| # | Phase | Skill | Description | Status |"
  echo "|---|---|---|---|---|"

  row=0
  for phase in "${PHASE_ORDER[@]}"; do
    for name in $(jq -r '.skills | keys[]' "$LOCKFILE" | sort); do
      [[ "${PHASE_MAP[$name]:-}" != "$phase" ]] && continue
      row=$((row + 1))
      desc=$(jq -r --arg n "$name" '.skills[$n].description // ""' "$LOCKFILE" | head -c 80)
      echo "| $row | $phase | \`$name\` | $desc | ✅ Active |"
    done
  done

  echo ""
  echo "**Total: $total active skills.**"
  echo ""

  # Lifecycle arc
  echo "---"
  echo ""
  echo "## Lifecycle Arc"
  echo ""
  echo '```'
  echo '[First time]'
  echo 'using-bigpowers → orchestrate-project'
  echo '                         ↓'
  echo 'survey-context → research-first → elaborate-spec → map-codebase'
  echo '                         ↓'
  echo '  model-domain / define-language / grill-me / grill-with-docs'
  echo '  design-interface / deepen-architecture / define-success'
  echo '                         ↓'
  echo '  scope-work → assess-impact → change-request → slice-tasks'
  echo '  → plan-work / plan-refactor / plan-release / seed-conventions'
  echo '                         ↓'
  echo '    kickoff-branch → guard-git / hook-commits / setup-environment'
  echo '                         ↓'
  echo '       [Unknown domain?] spike-prototype → (learnings)'
  echo '                         ↓'
  echo '  develop-tdd (+ enforce-first) ←→ delegate-task / dispatch-agents'
  echo '  execute-plan / build-epic / craft-skill / align-grid'
  echo '                         ↓'
  echo '              ★ VERIFY ★  verify-work → run-evals → audit-code'
  echo '                         ↓'
  echo '    fix-bug → investigate-bug → diagnose-root → validate-fix'
  echo '                         ↓'
  echo '      request-review → respond-review → trace-requirement'
  echo '                         ↓'
  echo '      commit-message → release-branch'
  echo '                         ↓'
  echo '   inspect-quality → organize-workspace → stocktake-skills'
  echo '   → evolve-skill → edit-document / write-document / migrate-spec'
  echo ''
  echo 'Transversal utilities (any phase):'
  echo '  terse-mode, session-state, visual-dashboard, reset-baseline,'
  echo '  search-skills, compose-workflow, simulate-agents, wire-observability'
  echo '```'
  echo ""
  echo "---"
  echo ""
  echo "## Status Legend"
  echo ""
  echo "| Icon | Meaning |"
  echo "|---|---|"
  echo "| ✅ Active | SKILL.md exists and is usable |"
  echo "| 📋 Planned | Designed but not yet implemented |"
  echo "| 🔄 Refactoring | Active but under revision |"
  echo "| ⚠️ Deprecated | Will be removed in a future release |"
  echo ""
  echo "## Naming Convention Notes"
  echo ""
  echo "All skills follow \`verb-noun\` kebab-case (ADR-0001). Documented exceptions:"
  echo "- \`terse-mode\` — adjective-noun; retained for clarity"
  echo "- \`visual-dashboard\` — adjective-noun; retained for clarity"
  echo ""
  echo "## How to Update"
  echo ""
  echo "1. Run \`bash scripts/sync-skills.sh\` to regenerate this file and all artifacts."
  echo "2. Or run \`bash scripts/generate-skill-index.sh\` to only regenerate this index."
  echo ""
  echo "→ verify: \`find . -maxdepth 2 -name \"SKILL.md\" | grep -v \".git\\|.cursor\\|.gemini\" | wc -l\`"
  echo ""

} > "$INDEX_FILE"

count=$(jq '.skills | length' "$LOCKFILE")
echo "generate-skill-index: wrote SKILL-INDEX.md ($count skills)"
