#!/usr/bin/env bash
# init.sh — verification gate for the crm-automator master.
# The agent MUST run this before claiming any feature is done.
# THE ANTI-THEATER GATE: runs verify_crm_automation.py against every sample in
# samples/good/* (must PASS, exit 0) and samples/bad/* (must FAIL, nonzero).
# If the gate passes a bad sample or fails a good one, this script exits
# nonzero — proving the linter actually catches bullshit, not just prints green.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT"

echo "== crm-automation harness :: verifying gate =="

# --- toolchain check -------------------------------------------------------
if ! command -v python3 >/dev/null 2>&1; then
  echo "FAIL: python3 not found on PATH" >&2
  exit 1
fi

LINTER="verify_crm_automation.py"
if [ ! -f "$LINTER" ]; then
  echo "FAIL: $LINTER not found at repo root" >&2
  exit 1
fi

GOOD_DIR="samples/good"
BAD_DIR="samples/bad"

if [ ! -d "$GOOD_DIR" ] || [ -z "$(ls -A "$GOOD_DIR" 2>/dev/null)" ]; then
  echo "FAIL: $GOOD_DIR is missing or empty — need at least one known-excellent sample" >&2
  exit 1
fi
if [ ! -d "$BAD_DIR" ] || [ -z "$(ls -A "$BAD_DIR" 2>/dev/null)" ]; then
  echo "FAIL: $BAD_DIR is missing or empty — need at least one deliberately-broken sample" >&2
  exit 1
fi

GATE_OK=1

echo
echo "-- good samples: every file MUST pass (exit 0) --"
for f in "$GOOD_DIR"/*; do
  [ -f "$f" ] || continue
  if python3 "$LINTER" "$f"; then
    echo "  OK   : $f passed as expected"
  else
    echo "  FAIL : $f was rejected but is supposed to be EXCELLENT — the gate is too strict or the sample regressed" >&2
    GATE_OK=0
  fi
  echo
done

echo "-- bad samples: every file MUST fail (nonzero exit) --"
for f in "$BAD_DIR"/*; do
  [ -f "$f" ] || continue
  if python3 "$LINTER" "$f"; then
    echo "  FAIL : $f PASSED but is supposed to be BROKEN — the gate does not catch bullshit" >&2
    GATE_OK=0
  else
    echo "  OK   : $f was rejected as expected"
  fi
  echo
done

if [ "$GATE_OK" -ne 1 ]; then
  echo "FAIL: anti-theater gate failed — the linter does not reliably separate good from bad. Fix the linter or the samples before trusting any 'done' claim." >&2
  exit 1
fi

echo "PASS: anti-theater gate holds — every good sample passed, every bad sample failed."
echo
echo "== crm-automation harness :: gate green =="
exit 0
