#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$SCRIPT_DIR"

TSV="$PROJECT_ROOT/draft-compliance-report-2026-10-31.tsv"
REPORT="$PROJECT_ROOT/draft-verification-report-2026-11-01.md"

if [[ ! -f "$TSV" ]]; then
  echo "Missing TSV: $TSV"
  exit 1
fi
if [[ ! -f "$REPORT" ]]; then
  echo "Missing report: $REPORT"
  exit 1
fi

# Generate fresh TSV using Python
FRESH=$(mktemp)
python3 - "$FRESH" <<'PY'
import sys
from pathlib import Path

wizard_work = Path("/root/troupe-standup/wizard-work/quill")
exclude = {"draft-compliance-report-2026-10-31.md", "draft-verification-report-2026-11-01.md"}
verification_report = "draft-verification-report-2026-11-01.md"
rows = []
for p in sorted(wizard_work.glob("*.md")):
    if p.name in exclude:
        continue
    rel = p.name
    lines = p.read_text(errors="replace").splitlines()
    line_count = len(lines)
    has_verdict = any(l.strip().startswith("VERDICT:") for l in lines)
    has_check = any(l.strip().startswith("CHECK:") for l in lines)
    bare_cmd = ""
    for l in lines:
        s = l.strip()
        if s.startswith("CHECK:"):
            bare_cmd = s[len("CHECK:"):].strip()
            break
    rows.append((rel, line_count, has_verdict, has_check, bool(bare_cmd), bare_cmd))

# Include verification report
report_path = Path("/root/.hermes/wizard-outputs/quill/draft-verification-report-2026-11-01.md")
if report_path.exists():
    lines = report_path.read_text(errors="replace").splitlines()
    line_count = len(lines)
    has_verdict = any(l.strip().startswith("VERDICT:") for l in lines)
    has_check = any(l.strip().startswith("CHECK:") for l in lines)
    bare_cmd = ""
    for l in lines:
        s = l.strip()
        if s.startswith("CHECK:"):
            bare_cmd = s[len("CHECK:"):].strip()
            break
    rows.append((verification_report, line_count, has_verdict, has_check, bool(bare_cmd), bare_cmd))

rows.sort(key=lambda r: r[0])
with open(sys.argv[1], "w") as f:
    f.write(f"# measured {len(rows)} markdown files\n")
    for rel, lc, hv, hc, hbc, cmd in rows:
        f.write(f"{rel}\t{lc}\t{hv}\t{hc}\t{hbc}\t{cmd}\n")
PY

if ! diff -u "$TSV" "$FRESH" > /dev/null; then
  echo "TSV mismatch"
  diff -u "$TSV" "$FRESH" | head -20
  rm -f "$FRESH"
  exit 1
fi

# Verify report summary numbers match TSV
pop=$(grep -oP 'Total `\.md` drafts scanned\s*\|\s*\K\d+' "$REPORT" || true)
verdict=$(grep -oP 'Drafts with `VERDICT:`\s*\|\s*\K\d+' "$REPORT" || true)
check=$(grep -oP 'Drafts with `CHECK:`\s*\|\s*\K\d+' "$REPORT" || true)
bare=$(grep -oP 'Drafts with a bare `CHECK:` command\s*\|\s*\K\d+' "$REPORT" || true)
failing=$(grep -oP 'Drafts failing at least one column\s*\|\s*\K\d+' "$REPORT" || true)

tsv_pop=$(tail -n +2 "$TSV" | wc -l)
tsv_verdict=$(awk -F'\t' '$3 == "True" {count++} END {print count+0}' "$TSV")
tsv_check=$(awk -F'\t' '$4 == "True" {count++} END {print count+0}' "$TSV")
tsv_bare=$(awk -F'\t' '$5 == "True" {count++} END {print count+0}' "$TSV")
tsv_failing=$(awk -F'\t' 'NR>1 && ($3 != "True" || $5 != "True") {count++} END {print count+0}' "$TSV")

if [[ "$pop" != "$tsv_pop" ]]; then
  echo "Population mismatch: report=$pop, tsv=$tsv_pop"
  exit 1
fi
if [[ "$verdict" != "$tsv_verdict" ]]; then
  echo "Verdict count mismatch: report=$verdict, tsv=$tsv_verdict"
  exit 1
fi
if [[ "$check" != "$tsv_check" ]]; then
  echo "Check count mismatch: report=$check, tsv=$tsv_check"
  exit 1
fi
if [[ "$bare" != "$tsv_bare" ]]; then
  echo "Bare check mismatch: report=$bare, tsv=$tsv_bare"
  exit 1
fi
if [[ "$failing" != "$tsv_failing" ]]; then
  echo "Failing mismatch: report=$failing, tsv=$tsv_failing"
  exit 1
fi

# Verify report has VERDICT and CHECK lines
if ! grep -q '^VERDICT:' "$REPORT"; then
  echo "Report missing VERDICT line"
  exit 1
fi
if ! grep -q '^CHECK:' "$REPORT"; then
  echo "Report missing CHECK line"
  exit 1
fi

rm -f "$FRESH"
echo "All checks passed"
exit 0
