#!/usr/bin/env bash

# Agent Forum v4 - Pre-Commit Hook
#
# This hook executes Git-Native Agent Collaboration Ecosystem tasks before every commit:
# 1. Generates Semantic Code Intelligence Protocol (SCIP) & AST graphs.
# 2. Runs fast Static Analysis (Semgrep) if available.
# 3. Validates Bounded Model Checking rules via transitions.json.
# 4. Writes telemetry/reasoning payloads to Git Notes.

echo "=================================================="
echo "    Agent Forum v4 - Pre-Commit Validation        "
echo "=================================================="

# Exit on any failure
set -e

REPO_ROOT=$(git rev-parse --show-toplevel)
META_MANAGER="$REPO_ROOT/.forum/src/core/meta_state_manager.ts"

if [ -f "$META_MANAGER" ] && command -v deno &> /dev/null; then
    echo "Running Agent Forum meta-state checks..."

    # Run the meta-state manager to extract structural diffs and enforce rules.
    # Note: Using run -A for Deno as it requires fs and run permissions to inspect git
    if ! deno run -A "$META_MANAGER" --pre-commit; then
        echo "❌ Agent Forum Bounded Model Checking failed. Commit aborted."
        exit 1
    fi
else
    echo "⚠️ Agent Forum meta-state manager (Deno script) not found or Deno not installed. Skipping."
fi

# Optional: SCIP / AST Extraction using tree-sitter
if command -v tree-sitter &> /dev/null; then
    echo "-> Generating local AST structures..."
    mkdir -p "$REPO_ROOT/.forum/ast"
    find "$REPO_ROOT/src" \( -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx" \) 2>/dev/null | while read -r file; do
        tree-sitter parse "$file" > "$REPO_ROOT/.forum/ast/$(basename "$file").ast" 2>/dev/null || true
    done
    echo "   AST structures saved to .forum/ast/"
fi

# Optional: Fast Security Scan
if command -v semgrep &> /dev/null; then
    echo "-> Running Semgrep baseline scan..."
    mkdir -p "$REPO_ROOT/.forum/security"
    semgrep scan --config=auto --json -o "$REPO_ROOT/.forum/security/semgrep_baseline.json" || true
    echo "   Semgrep scan results saved to .forum/security/semgrep_baseline.json"
fi

echo "✅ Pre-commit validation passed."
exit 0
