#!/usr/bin/env python3
"""Pre-harness SSOT gate — called by the harness before any phase runs.

Checks three things in order:
1. No Dropbox conflict files in recoil/architecture/
2. Manifest AST validator passes
3. No BUILD_SPEC.violation.json in cwd

Accepts --bypass-ssot-gate-with-explanation to skip checks 2+3 (check 1 always runs).

Usage:
    python3 recoil/architecture/tools/pre_harness_gate.py
    python3 recoil/architecture/tools/pre_harness_gate.py \\
        --bypass-ssot-gate-with-explanation "Tartarus EP001 crunch — critical hotfix"

Exit codes:
    0 = all checks passed (or bypassed with explanation logged)
    1 = gate failed
"""
from __future__ import annotations

import argparse
import json
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path

AUDIT_LOG = Path("recoil/architecture/auditor_log.jsonl")
VIOLATION_FILE = Path("BUILD_SPEC.violation.json")
MANIFEST_PATH = Path("recoil/architecture/ssot_manifest.yaml")
VALIDATOR_SCRIPT = Path("recoil/architecture/tools/validate_manifest_ast.py")


def _now_iso() -> str:
    return datetime.now(timezone.utc).isoformat()


def _check_dropbox_conflicts() -> list[str]:
    arch_dir = Path("recoil/architecture")
    if not arch_dir.exists():
        return []
    conflicts = []
    for p in arch_dir.rglob("*"):
        if "conflicted copy" in p.name:
            conflicts.append(str(p))
    return conflicts


def _log_bypass(reason: str) -> None:
    import uuid
    entry = {
        "id": str(uuid.uuid4()),
        "timestamp": _now_iso(),
        "spec_path": "(harness gate bypass)",
        "manifest_path": str(MANIFEST_PATH),
        "verdict": "BYPASS",
        "reason": f"Harness gate bypass: {reason}",
        "build_id": "",
        "bypassed": True,
        "bypass_explanation": reason,
    }
    AUDIT_LOG.parent.mkdir(parents=True, exist_ok=True)
    with open(AUDIT_LOG, "a") as f:
        f.write(json.dumps(entry) + "\n")


def main() -> int:
    p = argparse.ArgumentParser(description="Pre-harness SSOT gate")
    p.add_argument("--bypass-ssot-gate-with-explanation", metavar="REASON",
                   help="Skip manifest + violation checks; log the explanation")
    p.add_argument("--manifest", default=str(MANIFEST_PATH))
    args = p.parse_args()

    # Check 1: Dropbox conflict files (ALWAYS runs, not bypassable)
    conflicts = _check_dropbox_conflicts()
    if conflicts:
        print("GATE FAIL: Dropbox conflict file(s) in recoil/architecture/:", file=sys.stderr)
        for c in conflicts:
            print(f"  {c}", file=sys.stderr)
        print("\nResolve the conflict files before running any harness build.", file=sys.stderr)
        return 1

    # Bypass mode (checks 2+3)
    if args.bypass_ssot_gate_with_explanation:
        reason = args.bypass_ssot_gate_with_explanation
        _log_bypass(reason)
        print(f"GATE BYPASS (logged): {reason}")
        print("Pre-harness gate: BYPASSED")
        return 0

    # Check 2: Manifest AST validator
    if VALIDATOR_SCRIPT.exists() and MANIFEST_PATH.exists():
        result = subprocess.run(
            [sys.executable, str(VALIDATOR_SCRIPT), "--manifest", str(args.manifest)],
            capture_output=True, text=True,
        )
        if result.returncode != 0:
            print(f"GATE FAIL: Manifest AST validation failed:", file=sys.stderr)
            print(result.stderr, file=sys.stderr)
            return 1
        print(f"Manifest: {result.stdout.strip()}")
    else:
        print("NOTE: Manifest or validator not found — skipping manifest check")

    # Check 3: Violation file
    if VIOLATION_FILE.exists():
        try:
            violation_data = json.loads(VIOLATION_FILE.read_text())
            print(f"GATE FAIL: BUILD_SPEC.violation.json exists:", file=sys.stderr)
            for v in violation_data.get("violations", []):
                print(f"  Phase {v.get('phase', '?')}: {v.get('reason', '')}", file=sys.stderr)
            print(
                f"\nRun /spec-review and address the architectural violation before dispatching.",
                file=sys.stderr,
            )
        except Exception:
            print(f"GATE FAIL: BUILD_SPEC.violation.json exists and is malformed", file=sys.stderr)
        return 1

    print("Pre-harness gate: PASS")
    return 0


if __name__ == "__main__":
    sys.exit(main())
