#!/bin/bash
# Regenerate the phosphor-specialist agent definition from the current codebase.
# Run this after significant features or before a version bump.
# Usage: ./scripts/update-agent.sh

set -e
cd "$(dirname "$0")/.."

AGENT_FILE=".claude/agents/phosphor-specialist.md"
CONTROLS="controls.json"
VERSION=$(grep '^version = ' Cargo.toml | head -1 | sed 's/version = "\(.*\)"/\1/')
PPQ=$(grep 'pub const PPQ.*=' crates/phosphor-core/src/transport.rs | head -1 | grep -o '[0-9]*' | tail -1)
THEME_COUNT=$(grep 'pub const THEME_COUNT' crates/phosphor-tui/src/theme.rs | grep -o '[0-9]*')
THEME_NAMES=$(grep -A"$THEME_COUNT" 'THEME_NAMES' crates/phosphor-tui/src/theme.rs | grep '"' | sed 's/.*"\(.*\)".*/\1/' | tr '\n' ', ' | sed 's/,$//')
TEST_COUNT=$(cargo test --workspace 2>&1 | grep 'test result' | awk '{sum += $4} END {print sum}')

# Extract instrument types from the ALL constant (single line)
INSTRUMENTS=$(grep 'ALL.*InstrumentType.*Self' crates/phosphor-app/src/state/menu.rs | grep -o 'Self::[A-Za-z0-9]*' | sed 's/Self:://' | tr '\n' ', ' | sed 's/,$//')

# Extract SpaceAction variants
SPACE_ACTIONS=$(python3 -c "
import re
with open('crates/phosphor-app/src/state/menu.rs') as f:
    text = f.read()
m = re.search(r'enum SpaceAction \{(.*?)\}', text, re.DOTALL)
if m:
    variants = re.findall(r'(\w+)', m.group(1))
    print(', '.join(variants))
")

# Extract UndoAction variants
UNDO_ACTIONS=$(python3 -c "
import re
with open('crates/phosphor-app/src/state/undo.rs') as f:
    text = f.read()
m = re.search(r'pub enum UndoAction \{(.*?)\n\}', text, re.DOTALL)
if m:
    variants = re.findall(r'^\s+(\w+)\s*\{', m.group(1), re.MULTILINE)
    print(', '.join(variants))
")

# Extract GridResolution labels
GRID_VARIANTS=$(python3 -c "
import re
with open('crates/phosphor-app/src/state/clip_view.rs') as f:
    text = f.read()
m = re.search(r'impl GridResolution.*?pub fn label.*?\{(.*?)\}', text, re.DOTALL)
if m:
    labels = re.findall(r'\"(.*?)\"', m.group(1))
    print(', '.join(labels))
")

# Count files
APP_FILES=$(find crates/phosphor-tui/src/app -name '*.rs' | wc -l | tr -d ' ')
STATE_FILES=$(find crates/phosphor-tui/src/state -name '*.rs' | wc -l | tr -d ' ')
UI_FILES=$(find crates/phosphor-tui/src/ui -name '*.rs' | wc -l | tr -d ' ')
DSP_FILES=$(find crates/phosphor-dsp/src -name '*.rs' | wc -l | tr -d ' ')

# Extract MixerCommand variants
MIXER_CMDS=$(python3 -c "
import re
with open('crates/phosphor-core/src/mixer.rs') as f:
    text = f.read()
m = re.search(r'pub enum MixerCommand \{(.*?)\n\}', text, re.DOTALL)
if m:
    variants = re.findall(r'^\s+(\w+)\s*\{', m.group(1), re.MULTILINE)
    print(', '.join(variants))
")

echo "Phosphor v${VERSION}"
echo "PPQ: ${PPQ}"
echo "Themes: ${THEME_NAMES}"
echo "Tests: ${TEST_COUNT}"
echo "Instruments: ${INSTRUMENTS}"
echo "Space actions: ${SPACE_ACTIONS}"
echo "Undo actions: ${UNDO_ACTIONS}"
echo "Grid: ${GRID_VARIANTS}"
echo "Mixer commands: ${MIXER_CMDS}"
echo "Files: app=${APP_FILES} state=${STATE_FILES} ui=${UI_FILES} dsp=${DSP_FILES}"
echo ""
echo "Updating ${AGENT_FILE}..."

# Update version in agent file
sed -i '' "s/Version: [0-9.]*/Version: ${VERSION}/" "$AGENT_FILE" 2>/dev/null || true

# Write a generated metadata section at the end of the agent file
# First, remove any existing auto-generated section
sed -i '' '/^## Auto-Generated Metadata/,$d' "$AGENT_FILE" 2>/dev/null || true

cat >> "$AGENT_FILE" << METADATA

## Auto-Generated Metadata
<!-- Regenerated by scripts/update-agent.sh — do not edit below this line -->

- **Version**: ${VERSION}
- **PPQ**: ${PPQ} ticks per quarter note
- **Themes** (${THEME_COUNT}): ${THEME_NAMES}
- **Tests**: ${TEST_COUNT} across workspace
- **Instruments**: ${INSTRUMENTS}
- **SpaceAction variants**: ${SPACE_ACTIONS}
- **UndoAction variants**: ${UNDO_ACTIONS}
- **MixerCommand variants**: ${MIXER_CMDS}
- **Grid resolutions**: ${GRID_VARIANTS}
- **Source files**: app=${APP_FILES}, state=${STATE_FILES}, ui=${UI_FILES}, dsp=${DSP_FILES}
- **Controls reference**: See controls.json for complete key mapping
- **Last updated**: $(date '+%Y-%m-%d %H:%M')
METADATA

echo "Done. Agent updated with v${VERSION} metadata."
