#!/bin/bash
#
# DevForgeAI Pre-Commit Validation Hook
#
# Validates story files before commit to prevent:
# - Autonomous deferrals (DoD [x] but Impl [ ] without user approval)
# - Missing Implementation Notes
# - Invalid deferral justifications
#
# INCIDENT STORIES: Stories with `generated_by: ci-incident-resolver` or
#   `source_issue:` in YAML frontmatter are auto-skipped — the incident
#   (GitHub Issue) IS the specification, no Implementation Notes needed.
#
# To bypass (NOT RECOMMENDED): git commit --no-verify
#

echo ""
echo "🔍 DevForgeAI Validators Running..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

VALIDATION_FAILED=0

# ============================================================================
# Story-Scoped Validation (STORY-121)
# Set DEVFORGEAI_STORY=STORY-NNN to validate only that story
# ============================================================================

if [ -n "$DEVFORGEAI_STORY" ]; then
    # Validate format: STORY-NNN (3+ digits, uppercase only)
    if ! echo "$DEVFORGEAI_STORY" | grep -qE '^STORY-[0-9]{3,}$'; then
        echo "  WARNING: Invalid DEVFORGEAI_STORY format: $DEVFORGEAI_STORY"
        echo "  Expected: STORY-NNN (e.g., STORY-120)"
        echo "  Falling back to unscoped validation..."
        DEVFORGEAI_STORY=""
    fi
fi

if [ -n "$DEVFORGEAI_STORY" ]; then
    # Scoped validation - only validate specific story
    STORY_FILES=$(git diff --cached --name-only --diff-filter=d | grep "${DEVFORGEAI_STORY}" | grep -v '^tests/' | grep -v 'fixtures/' | grep -v '\.archive/' | grep -v '/backup/' || true)
    echo "  Scoped to: $DEVFORGEAI_STORY"
else
    # Default behavior - validate all staged story files
    # Exclude: tests/, fixtures/ (test data), .archive/ (deprecated skills), backup/ (pre-migration snapshots)
    STORY_FILES=$(git diff --cached --name-only --diff-filter=d | grep '\.story\.md$' | grep -v '^tests/' | grep -v 'fixtures/' | grep -v '\.archive/' | grep -v '/backup/' || true)
fi

if [ -z "$STORY_FILES" ]; then
    echo "  No story files to validate"
    echo "✅ Pre-commit validation passed"
    echo ""
    exit 0
fi

# Validate each story file
VALIDATION_FAILED=0

for file in $STORY_FILES; do
    # Skip if file doesn't exist (shouldn't happen with --diff-filter=d, but safety check)
    if [ ! -f "$file" ]; then
        echo "  ⚠️  Skipping (file not found): $file"
        continue
    fi

    echo "  📋 Validating: $file"

    # Run DoD validator with PYTHONPATH set (fixes relative import issue)
    # This allows the validator to import from parent package without pip install
    if PYTHONPATH=".claude/scripts:$PYTHONPATH" python3 -m devforgeai_cli.validators.dod_validator "$file" --project-root .; then
        echo "     ✅ Passed"
    else
        echo "     ❌ Failed"
        VALIDATION_FAILED=1
    fi
done

echo ""

if [ $VALIDATION_FAILED -eq 1 ]; then
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "❌ COMMIT BLOCKED - Fix violations"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    echo "RECOVERY: Read the fix guide, then fix the story file:"
    echo "  Read('.claude/skills/spec-driven-dev/references/dod-update-workflow.md')"
    echo ""
    echo "MOST COMMON FIX: Move DoD items to be directly under '## Implementation Notes'"
    echo "  (NOT under ### subsections - the parser stops at the first ### header)"
    echo ""
    echo "INCIDENT STORIES: If this work was implemented from a GitHub Issue"
    echo "  (not a formal spec-driven story), add these YAML frontmatter fields:"
    echo "    generated_by: ci-incident-resolver"
    echo "    source_issue: https://github.com/<org>/<repo>/issues/<N>"
    echo "  Incident stories are auto-exempt from DoD validation."
    echo ""
    echo "VALIDATE before retrying:"
    echo "  devforgeai-validate validate-dod <story-file>"
    echo ""
    echo "To bypass validation (NOT RECOMMENDED):"
    echo "  git commit --no-verify"
    echo ""
    exit 1
fi

echo "✅ All validators passed - commit allowed"
echo ""
exit 0
