#!/usr/bin/env bash
# ============================================================================
# Athena Pre-Commit Hook — Mechanical Enforcement of DISCIPLINE.md
# ============================================================================
# Purpose: Makes DISCIPLINE.md rules binding, not aspirational.
#
# Install:
#   cp scripts/hooks/pre-commit .git/hooks/pre-commit
#   chmod +x .git/hooks/pre-commit
#
# Gates:
#   1. VERSION LINT — blocks commit if version strings diverge
#   2. PROTOCOL CAP — blocks if protocol count exceeds cap without RETIRES:
#   3. WORKFLOW CAP — warns if workflow count exceeds target
#   4. AUTO-GEN INDEXES — regenerates indexes when source files change
#
# Override: Include DISCIPLINE_OVERRIDE in commit message to bypass all gates.
#           Overrides are logged to decisionLog.md.
# ============================================================================

set -euo pipefail

RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
BOLD='\033[1m'
NC='\033[0m'

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

log_error() { echo -e "${RED}✗ BLOCKED${NC} $1"; ((ERRORS++)) || true; }
log_warn()  { echo -e "${YELLOW}⚠ WARNING${NC} $1"; ((WARNINGS++)) || true; }
log_ok()    { echo -e "${GREEN}✓${NC} $1"; }

# ── Gate 0: Override ────────────────────────────────────────────────────────
COMMIT_MSG_FILE="${REPO_ROOT}/.git/COMMIT_EDITMSG"
if [[ -f "$COMMIT_MSG_FILE" ]] && grep -q "DISCIPLINE_OVERRIDE" "$COMMIT_MSG_FILE" 2>/dev/null; then
    echo -e "${YELLOW}⚠ DISCIPLINE_OVERRIDE detected — all gates bypassed${NC}"
    echo "$(date -u +%Y-%m-%dT%H:%M:%SZ) | OVERRIDE | pre-commit gates bypassed" \
        >> "${REPO_ROOT}/decisionLog.md" 2>/dev/null || true
    exit 0
fi

# ── Gate 1: Version Lint ────────────────────────────────────────────────────
echo -e "\n${BOLD}── Gate 1: Version Lint ──${NC}"

CANONICAL_VERSION=""
if [[ -f "${REPO_ROOT}/pyproject.toml" ]]; then
    CANONICAL_VERSION=$(grep -m1 '^version' "${REPO_ROOT}/pyproject.toml" | sed 's/version *= *"\(.*\)"/\1/')
fi

if [[ -z "$CANONICAL_VERSION" ]]; then
    log_warn "Could not read version from pyproject.toml — skipping"
else
    for vfile in README.md AGENTS.md; do
        filepath="${REPO_ROOT}/${vfile}"
        [[ -f "$filepath" ]] || continue
        git diff --cached --name-only | grep -q "^${vfile}$" || continue

        staged_content=$(git show ":${vfile}" 2>/dev/null || cat "$filepath")
        old_versions=$(echo "$staged_content" | grep -oE 'v[0-9]+\.[0-9]+\.[0-9]+' | sort -u | grep -v "v${CANONICAL_VERSION}" | grep -v 'v8\.2' || true)

        if [[ -n "$old_versions" ]]; then
            log_error "${vfile} has version(s) [${old_versions//$'\n'/, }] — canonical is v${CANONICAL_VERSION}"
        fi
    done

    [[ $ERRORS -eq 0 ]] && log_ok "All staged files reference v${CANONICAL_VERSION}"
fi

# ── Gate 2: Protocol Cap ────────────────────────────────────────────────────
echo -e "\n${BOLD}── Gate 2: Protocol Cap ──${NC}"

PROTOCOL_CAP=500  # Customize per DISCIPLINE.md Rule 3
PROTOCOL_DIRS=("${REPO_ROOT}/.agent/skills/protocols" "${REPO_ROOT}/examples/protocols")

PROTOCOL_COUNT=0
for pdir in "${PROTOCOL_DIRS[@]}"; do
    if [[ -d "$pdir" ]]; then
        count=$(find "$pdir" -name "*.md" -type f | wc -l | tr -d ' ')
        PROTOCOL_COUNT=$((PROTOCOL_COUNT + count))
    fi
done

if [[ $PROTOCOL_COUNT -gt $PROTOCOL_CAP ]]; then
    if [[ -f "$COMMIT_MSG_FILE" ]] && grep -q "RETIRES:" "$COMMIT_MSG_FILE" 2>/dev/null; then
        log_ok "Protocol count ${PROTOCOL_COUNT}/${PROTOCOL_CAP} — RETIRES: found"
    else
        log_error "Protocol count ${PROTOCOL_COUNT} exceeds cap of ${PROTOCOL_CAP}. Add 'RETIRES: <name>' to commit message."
    fi
else
    log_ok "Protocol count ${PROTOCOL_COUNT}/${PROTOCOL_CAP}"
fi

# ── Gate 3: Workflow Cap ────────────────────────────────────────────────────
echo -e "\n${BOLD}── Gate 3: Workflow Cap ──${NC}"

WORKFLOW_TARGET=24   # DISCIPLINE.md Rule 2
WORKFLOW_DIR="${REPO_ROOT}/.agent/workflows"

if [[ -d "$WORKFLOW_DIR" ]]; then
    WORKFLOW_COUNT=$(find "$WORKFLOW_DIR" -maxdepth 1 -name "*.md" -not -name "_shared.md" -type f | wc -l | tr -d ' ')

    if [[ $WORKFLOW_COUNT -gt $WORKFLOW_TARGET ]]; then
        log_warn "Workflow count ${WORKFLOW_COUNT}/${WORKFLOW_TARGET}. Archive unused workflows."
    else
        log_ok "Workflow count ${WORKFLOW_COUNT}/${WORKFLOW_TARGET}"
    fi
fi

# ── Gate 4: Auto-Generate Indexes ───────────────────────────────────────────
echo -e "\n${BOLD}── Gate 4: Auto-Generate Indexes ──${NC}"

STAGED_FILES=$(git diff --cached --name-only 2>/dev/null || true)

# Regenerate protocol summaries if any protocol files changed
if echo "$STAGED_FILES" | grep -qE '(protocols/|skills/protocols/).*\.md$'; then
    if [[ -x "${REPO_ROOT}/scripts/generate_protocol_summaries.py" ]] || command -v python3 &>/dev/null; then
        python3 "${REPO_ROOT}/scripts/generate_protocol_summaries.py" 2>/dev/null && \
            git add "${REPO_ROOT}/.context/PROTOCOL_SUMMARIES.md" 2>/dev/null && \
            log_ok "Regenerated PROTOCOL_SUMMARIES.md" || \
            log_warn "Protocol summary generation failed (non-blocking)"
    fi
fi

# Regenerate skill index if any skill files changed
if echo "$STAGED_FILES" | grep -qE 'skills/.*SKILL\.md$'; then
    if [[ -x "${REPO_ROOT}/scripts/generate_skill_index.py" ]] || command -v python3 &>/dev/null; then
        python3 "${REPO_ROOT}/scripts/generate_skill_index.py" 2>/dev/null && \
            log_ok "Regenerated SKILL_INDEX.md" || \
            log_warn "Skill index generation failed (non-blocking)"
    fi
fi

# Regenerate workflow index if any workflow files changed
if echo "$STAGED_FILES" | grep -qE 'workflows/.*\.md$'; then
    if [[ -x "${REPO_ROOT}/scripts/regenerate_workflow_index.py" ]] || command -v python3 &>/dev/null; then
        python3 "${REPO_ROOT}/scripts/regenerate_workflow_index.py" 2>/dev/null && \
            log_ok "Regenerated workflow index" || \
            log_warn "Workflow index generation failed (non-blocking)"
    fi
fi

[[ $ERRORS -eq 0 ]] && log_ok "Index generation complete"

# ── Summary ─────────────────────────────────────────────────────────────────
echo ""
if [[ $ERRORS -gt 0 ]]; then
    echo -e "${RED}${BOLD}COMMIT BLOCKED${NC} — ${ERRORS} error(s), ${WARNINGS} warning(s)"
    echo -e "Fix issues above, or add ${BOLD}DISCIPLINE_OVERRIDE${NC} to commit message (logged)."
    exit 1
elif [[ $WARNINGS -gt 0 ]]; then
    echo -e "${YELLOW}${BOLD}COMMIT ALLOWED${NC} — ${WARNINGS} warning(s)"
    exit 0
else
    echo -e "${GREEN}${BOLD}ALL GATES PASSED${NC}"
    exit 0
fi
