#!/bin/bash
# Post-commit hook: Auto-implement design changes via Claude Code
# Copy to .git/hooks/post-commit and make executable

set -e

# Check if ui-design.pen was modified in this commit
if ! git diff --name-only HEAD~1 HEAD | grep -q "ui-design.pen"; then
    exit 0
fi

echo ""
echo "🎨 Design file changed - analyzing..."

# Run analyzer
ANALYZER_OUTPUT=$(node scripts/design-diff-analyzer.js --json 2>&1)

if [ $? -eq 0 ]; then
    echo "✅ No implementation tasks needed (content-only changes)"
    exit 0
fi

# Extract tasks from JSON
TASKS_JSON=$(echo "$ANALYZER_OUTPUT" | sed -n '/---JSON---/,$ p' | tail -n +2)

if [ -z "$TASKS_JSON" ]; then
    echo "✅ No significant design changes"
    exit 0
fi

echo "$ANALYZER_OUTPUT" | sed '/---JSON---/,$ d'

# Generate Claude Code prompt
PROMPT=$(cat <<EOF
The design file ui-design.pen was just updated. Analyze the changes and implement them.

Design changes detected:
$ANALYZER_OUTPUT

Tasks:
1. Review the git diff of ui-design.pen (HEAD vs HEAD~1)
2. Identify what changed (colors, typography, spacing, layout)
3. Update the corresponding code:
   - Colors/Typography/Spacing → update src/theme.json
   - Layout changes → update React components
   - New elements → create new components
4. Test visually in Chrome (pnpm dev, open localhost:5173)
5. Run tests: pnpm test
6. Commit changes with descriptive message referencing the design update

When completely finished, run:
openclaw system event --text "✅ Design changes implemented and tested" --mode now
EOF
)

echo ""
echo "🚀 Spawning Claude Code to implement changes..."
echo ""

# Spawn Claude Code via OpenClaw
openclaw sessions spawn \
    --task "$PROMPT" \
    --label "design-auto-implement" \
    --cleanup delete \
    --timeout-seconds 600 \
    --agent-id main

echo ""
echo "✅ Claude Code spawned - you'll be notified when implementation is complete"
echo ""

exit 0
