#!/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.

export FORUM_DEFER_NOTES=1

# Clear any stale pending notes from aborted commits
PENDING_FILE=$(git rev-parse --git-path forum_pending_notes.jsonl 2>/dev/null || echo ".git/forum_pending_notes.jsonl")
rm -f "$PENDING_FILE"


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

# Exit on any failure
set -e

REPO_ROOT=$(git rev-parse --show-toplevel)
CLI="$REPO_ROOT/.forum/src/cli.ts"

if [ -f "$CLI" ] && 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 "$CLI" sync --pre-commit; then
        echo "❌ Agent Forum Bounded Model Checking failed. Commit aborted."
        exit 1
    fi

# Optional: AST Extraction using tree-sitter
if command -v tree-sitter &> /dev/null; then
    echo "-> Generating local AST structures..."
    START_TS=$(deno eval 'console.log(Date.now())' 2>/dev/null || date +%s%3N)
    find "$REPO_ROOT/src" \( -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx" \) 2>/dev/null | while read -r file; do
        rel_path="${file#"$REPO_ROOT/"}"
        mkdir -p "$REPO_ROOT/.forum/ast/$(dirname "$rel_path")"
        tree-sitter parse "$file" > "$REPO_ROOT/.forum/ast/$rel_path.ast" 2>/dev/null || true
    done
    END_TS=$(deno eval 'console.log(Date.now())' 2>/dev/null || date +%s%3N)
    DURATION=$((END_TS - START_TS))
    TRACE_FILE=$(git rev-parse --git-path forum_trace.jsonl)
    echo "{\"cmd\":\"tree-sitter (batch ast extraction)\",\"duration_ms\":$DURATION,\"timestamp\":$START_TS,\"exit_code\":0}" >> "$TRACE_FILE"
    echo "   AST structures saved to .forum/ast/"
fi

if command -v deno &> /dev/null; then
    echo "-> Generating Deno dependency graph..."
    START_TS=$(deno eval 'console.log(Date.now())' 2>/dev/null || date +%s%3N)
    mkdir -p "$REPO_ROOT/.forum/ast"
    deno info --json src/run.ts > "$REPO_ROOT/.forum/ast/deno_graph.json" 2>/dev/null || true
    END_TS=$(deno eval 'console.log(Date.now())' 2>/dev/null || date +%s%3N)
    DURATION=$((END_TS - START_TS))
    TRACE_FILE=$(git rev-parse --git-path forum_trace.jsonl)
    echo "{\"cmd\":\"deno info --json src/run.ts\",\"duration_ms\":$DURATION,\"timestamp\":$START_TS,\"exit_code\":0}" >> "$TRACE_FILE"
    echo "   Deno dependency graph saved to .forum/ast/deno_graph.json"
fi

# Optional: Fast Security Scan
if command -v semgrep &> /dev/null; then
    echo "-> Running Semgrep baseline scan..."
    START_TS=$(deno eval 'console.log(Date.now())' 2>/dev/null || date +%s%3N)
    mkdir -p "$REPO_ROOT/.forum/security"
    semgrep scan --config=auto --json -o "$REPO_ROOT/.forum/security/semgrep_baseline.json" || true
    END_TS=$(deno eval 'console.log(Date.now())' 2>/dev/null || date +%s%3N)
    DURATION=$((END_TS - START_TS))
    TRACE_FILE=$(git rev-parse --git-path forum_trace.jsonl)
    echo "{\"cmd\":\"semgrep\",\"duration_ms\":$DURATION,\"timestamp\":$START_TS,\"exit_code\":0}" >> "$TRACE_FILE"
    echo "   Semgrep scan results saved to .forum/security/semgrep_baseline.json"
fi

    echo "-> Agent Forum: Evaluating BMC rules & certifying commit..."
    deno run -A "$CLI" run || { echo "❌ Agent Forum BMC pipeline rejected the commit."; exit 1; }
else
    echo "⚠️ Agent Forum meta-state manager (Deno script) not found or Deno not installed. Skipping."
fi

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