#!/bin/bash
# =============================================================================
# PRE-COMMIT HOOK — docs up-to-date check
# =============================================================================
# If src/pinky_streamlit/ files are staged:
#   1. Regenerate pdoc and stage the output automatically.
#   2. Require README.md to also be staged.
#   3. Require AGENT.md to also be staged.
# =============================================================================

SRC_STAGED=$(git diff --cached --name-only -- src/pinky_streamlit/ | grep -v '__pycache__' | wc -l | tr -d ' ')

if [ "$SRC_STAGED" -eq 0 ]; then
    exit 0
fi

# 1. Regenerate pdoc
if command -v pdoc > /dev/null 2>&1; then
    PDOC_ALLOW_EXEC=1 pdoc pinky_streamlit -o docs/reference/generated/api/ --no-show-source --template-dir docs/templates/ 2>/dev/null
    # Strip trailing whitespace and ensure final newline (pdoc output has trailing spaces)
    find docs/reference/generated/api/ -type f \( -name "*.html" -o -name "*.js" \) -exec sed -i '' 's/[[:space:]]*$//' {} \;
    find docs/reference/generated/api/ -type f \( -name "*.html" -o -name "*.js" \) | while read -r f; do
        [ -n "$(tail -c1 "$f")" ] && echo >> "$f"
    done
    git add docs/reference/generated/api/ 2>/dev/null
else
    echo "⚠️  pdoc not found — skipping API doc regeneration."
    echo "   Install with: pip install pdoc"
fi

# 2. Require README.md to be staged
README_STAGED=$(git diff --cached --name-only -- README.md | wc -l | tr -d ' ')

if [ "$README_STAGED" -eq 0 ]; then
    echo "❌ README.md not staged."
    echo ""
    echo "   src/pinky_streamlit/ was modified — README.md must be updated"
    echo "   and staged before committing."
    exit 1
fi

# 3. Require AGENT.md to be staged
AGENT_STAGED=$(git diff --cached --name-only -- AGENT.md | wc -l | tr -d ' ')

if [ "$AGENT_STAGED" -eq 0 ]; then
    echo "❌ AGENT.md not staged."
    echo ""
    echo "   src/pinky_streamlit/ was modified — AGENT.md must be reviewed"
    echo "   (scopes, structure, key decisions) and staged before committing."
    exit 1
fi

exit 0
