#!/usr/bin/env bash
# story: e13s02
# 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

source "$(dirname "${BASH_SOURCE[0]}")/lib/skill-common.sh"
resolve_repo_root

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
# Primary: reads phase: from SKILL.md frontmatter (self-maintaining)
# Fallback: hardcoded case statement for bash 3.2 compatibility
phase_of() {
  local skill_name="$1"
  local skill_file="$REPO_ROOT/skills/$skill_name/SKILL.md"

  # Try frontmatter first (self-maintaining path)
  if [[ -f "$skill_file" ]]; then
    local phase
    phase=$(awk '/^---$/{n++; next} n==1 && /^phase:/{gsub(/^phase:[[:space:]]*/, ""); gsub(/[[:space:]]*$/, ""); print; exit}' "$skill_file" 2>/dev/null | awk '{print toupper(substr($0,1,1)) tolower(substr($0,2))}')
    if [[ -n "$phase" ]]; then
      echo "$phase"
      return
    fi
  fi

  # Fallback: hardcoded case statement
  case "$skill_name" in
    # Discover
    survey-context|research-first|search-skills|using-bigpowers|map-codebase|elaborate-spec|audit-plan) echo "Discover" ;;
    # Design
    model-domain|define-language|grill-me|grill-with-docs|deepen-architecture|design-interface|define-success) echo "Design" ;;
    # Plan
    scope-work|slice-tasks|plan-work|plan-release|plan-refactor|assess-impact|change-request|run-planning|seed-conventions) echo "Plan" ;;
    # Build
    develop-tdd|kickoff-branch|execute-plan|build-epic|spike-prototype|craft-skill|quick-fix|setup-environment|wire-observability|wire-ci|publish-package|align-grid|orchestrate-project|guard-git|hook-commits|deploy|smoke-test|validate-contracts|extract-design) echo "Build" ;;
    # Verify
    verify-work|validate-fix|audit-code|enforce-first|run-evals|investigate-bug|diagnose-root|fix-bug|inspect-quality|request-review|respond-review|trace-requirement|security-review|context7-mcp|diagnose-stall|gate-trace|generate-allure-report|plan-tests) echo "Verify" ;;
    # Release
    release-branch|commit-message) echo "Release" ;;
    # Sustain
    session-state|edit-document|write-document|organize-workspace|reset-baseline|stocktake-skills|evolve-skill|run-benchmark|terse-mode|delegate-task|dispatch-agents|simulate-agents|compose-workflow|migrate-spec|visual-dashboard|harden-vps|maintain-wiki) echo "Sustain" ;;
  esac
}

# 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 ""
  # No generation timestamp: output must be byte-identical for the same sources
  # (CI drift gate runs git diff --exit-code). Git history records when this
  # file changed; a wall-clock or commit-date stamp makes every run dirty.
  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_of "$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_of "$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 → validate-contracts → smoke-test → 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 . skills -maxdepth 2 -name \"SKILL.md\" 2>/dev/null | grep -v \".git\\|.cursor\\|.gemini\\|.pi\" | sort -u | wc -l\`"
  echo ""

} > "$INDEX_FILE"

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