#!/bin/bash
# =====================================================
# Git Hook: pre-commit (workflow plugin)
# =====================================================
#
# Performs workflow validation before allowing commits:
#   1. Validates active ticket in .git/WORKFLOW_STATE
#   2. Scans for secrets using gitleaks
#
# Called by: git commit (before commit-msg hook)
#
# Exit codes:
#   0  Valid (all checks pass)
#   1  Invalid (validation failed, blocks commit)
#
# To bypass (NOT RECOMMENDED):
#   git commit --no-verify
#
# =====================================================

set -e

# =====================================================
# Find Plugin Directory
# =====================================================

REPO_ROOT="$(git rev-parse --show-toplevel)"

# Derive plugin dir from this hook's own location (hooks/ -> parent plugin dir)
HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_DIR="$(cd "$HOOK_DIR/.." && pwd)"

if [ ! -d "$PLUGIN_DIR/scripts" ]; then
    echo "⚠️  WARNING: workflow plugin scripts not found at $PLUGIN_DIR" >&2
    echo "   Skipping workflow validation" >&2
    exit 0
fi

# =====================================================
# 1. Check for Active Ticket
# =====================================================

GET_TICKET_SCRIPT="$PLUGIN_DIR/scripts/get-active-ticket.sh"

if [ ! -f "$GET_TICKET_SCRIPT" ]; then
    echo "⚠️  WARNING: get-active-ticket.sh not found: $GET_TICKET_SCRIPT" >&2
    echo "   Skipping active ticket validation" >&2
else
    # Make sure script is executable
    chmod +x "$GET_TICKET_SCRIPT" 2>/dev/null || true

    # Check if active ticket exists
    if ! "$GET_TICKET_SCRIPT" --format=id &>/dev/null; then
        echo "❌ ERROR: No active ticket claimed for this worktree" >&2
        echo "" >&2
        echo "Before committing, claim a ticket:" >&2
        echo "  cd $PLUGIN_DIR" >&2
        echo "  ./scripts/claim-ticket.sh <TICKET-ID>" >&2
        echo "" >&2
        echo "Example:" >&2
        echo "  ./scripts/claim-ticket.sh CUR-262" >&2
        echo "" >&2
        echo "Or to bypass this check (NOT RECOMMENDED):" >&2
        echo "  git commit --no-verify" >&2
        echo "" >&2
        exit 1
    fi

    # Active ticket found
    TICKET_ID=$("$GET_TICKET_SCRIPT" --format=id)
    echo "✅ Active ticket: $TICKET_ID"
fi

# =====================================================
# 2. Scan for Secrets (gitleaks)
# =====================================================

if ! command -v gitleaks &> /dev/null; then
    echo "⚠️  WARNING: gitleaks not installed - skipping secret scan" >&2
    echo "   Install gitleaks for secret detection: https://github.com/gitleaks/gitleaks" >&2
    echo "   Or rebuild dev container with updated base image" >&2
    echo "" >&2
else
    echo "🔍 Scanning staged files for secrets..." >&2

    # Use gitleaks protect to scan only staged changes
    # --staged: Only scan staged files
    # --verbose: Show what's being scanned
    # --no-banner: Suppress ASCII art banner
    # --redact: Hide actual secret values in output (for security)

    if gitleaks protect --staged --verbose --no-banner --redact 2>&1; then
        echo "✅ No secrets detected in staged files" >&2
    else
        GITLEAKS_EXIT_CODE=$?

        echo "" >&2
        echo "❌ SECRETS DETECTED IN STAGED FILES!" >&2
        echo "" >&2
        echo "Gitleaks found potential secrets in your staged changes." >&2
        echo "" >&2
        echo "To fix this:" >&2
        echo "  1. Remove the secrets from the staged files" >&2
        echo "  2. Use environment variables or Doppler for secrets" >&2
        echo "  3. Unstage files: git restore --staged <file>" >&2
        echo "  4. Try committing again" >&2
        echo "" >&2
        echo "If this is a false positive:" >&2
        echo "  1. Add the pattern to .gitleaks.toml [allowlist]" >&2
        echo "  2. Document why it's a false positive" >&2
        echo "" >&2
        echo "To bypass this check (NOT RECOMMENDED):" >&2
        echo "  git commit --no-verify" >&2
        echo "" >&2

        exit $GITLEAKS_EXIT_CODE
    fi
fi

# =====================================================
# All Validations Passed
# =====================================================

exit 0
