#!/usr/bin/python3
"""
Orchestrator Verification - Combined Runner

Runs all verification checks for orchestrator tracking:
1. Thread continuity
2. Emotional beats
3. Pattern variety

Usage: python3 orchestrator_verify.py <project_path>
Example: python3 orchestrator_verify.py ./leviathan

Returns:
- Exit code 0: All checks pass
- Exit code 1: One or more checks have errors
- Exit code 2: Warnings only (no errors)
"""

import json
import subprocess
import sys
from pathlib import Path

_SCRIPT_DIR = Path(__file__).parent.resolve()
sys.path.insert(0, str(_SCRIPT_DIR.parent.parent))  # CLAUDE_PROJECTS, for recoil.*
from recoil.core.paths import ProjectPaths


def run_check(script_name: str, project_path: Path, extra_args: list = None) -> tuple:
    """
    Run a verification script and capture results.
    Returns (passed, has_errors, has_warnings, output).
    """
    script_path = _SCRIPT_DIR / script_name

    if not script_path.exists():
        return False, True, False, f"Script not found: {script_path}"

    cmd = [sys.executable, str(script_path), str(project_path)]
    if extra_args:
        cmd.extend(extra_args)

    result = subprocess.run(cmd, capture_output=True, text=True)

    output = result.stdout + result.stderr
    has_errors = result.returncode == 1
    passed = result.returncode == 0

    return passed, has_errors, not passed and not has_errors, output


def load_orchestrator_state(project_path: Path) -> dict | None:
    """Load orchestrator state if exists."""
    state_file = ProjectPaths.from_root(project_path).state_dir / "orchestrator_state.json"
    if not state_file.exists():
        return None

    try:
        with open(state_file, 'r') as f:
            return json.load(f)
    except json.JSONDecodeError as e:
        print(f"Error: Invalid JSON in orchestrator_state.json: {e}")
        return None


def main():
    if len(sys.argv) < 2:
        print("Usage: python3 orchestrator_verify.py <project_path>")
        print("Example: python3 orchestrator_verify.py ./leviathan")
        sys.exit(1)

    project_path = Path(sys.argv[1]).resolve()

    if not project_path.exists():
        print(f"Error: Project path does not exist: {project_path}")
        sys.exit(1)

    state = load_orchestrator_state(project_path)
    if not state:
        print(f"Error: No orchestrator_state.json found.")
        print(f"Run: python3 /tools/init_orchestrator_state.py {project_path}")
        sys.exit(1)

    position = state.get("position", {})
    current_ep = position.get("last_completed_episode", 0)
    current_batch = position.get("last_completed_batch", 0)

    print(f"\n{'#'*60}")
    print(f"# ORCHESTRATOR VERIFICATION")
    print(f"{'#'*60}")
    print(f"\nProject: {project_path.name}")
    print(f"Position: Batch {current_batch} / Episode {current_ep}")

    # Each check: (script_name, check_name, extra_args or None)
    checks = [
        ("verify_thread_continuity.py", "Thread Continuity", None),
        ("verify_emotional_beats.py", "Emotional Beats", None),
        ("verify_pattern_variety.py", "Pattern Variety", None)
    ]

    # Voice contamination check only at batches 3, 6, 9, 12
    if current_batch in [3, 6, 9, 12]:
        checks.append((
            "../../.claude/hooks/baseline_comparison.py",
            "Voice Contamination",
            [str(current_batch)]  # baseline_comparison.py requires batch number
        ))

    results = []
    any_errors = False
    any_warnings = False

    for script_name, check_name, extra_args in checks:
        print(f"\n{'─'*60}")
        print(f"Running: {check_name}")
        print(f"{'─'*60}")

        passed, has_errors, has_warnings, output = run_check(script_name, project_path, extra_args)

        if has_errors:
            any_errors = True
            status = "FAIL"
        elif has_warnings:
            any_warnings = True
            status = "WARN"
        else:
            status = "PASS"

        results.append((check_name, status, output))

        # Print condensed output
        if output:
            # Extract just the issues section if present
            lines = output.split('\n')
            in_issues = False
            for line in lines:
                if 'ISSUES FOUND' in line or '✗' in line or '⚠' in line:
                    in_issues = True
                if in_issues or '✓' in line:
                    print(f"  {line.strip()}")

    # Summary
    print(f"\n{'#'*60}")
    print(f"# VERIFICATION SUMMARY")
    print(f"{'#'*60}\n")

    for check_name, status, _ in results:
        icon = "✓" if status == "PASS" else "⚠" if status == "WARN" else "✗"
        print(f"  {icon} {check_name}: {status}")

    # Overall status
    print(f"\n{'─'*60}")
    if any_errors:
        print(f"OVERALL: FAILED — Critical issues require attention")
        print(f"{'#'*60}\n")
        sys.exit(1)
    elif any_warnings:
        print(f"OVERALL: PASSED with warnings")
        print(f"{'#'*60}\n")
        sys.exit(2)
    else:
        print(f"OVERALL: PASSED — All checks healthy")
        print(f"{'#'*60}\n")
        sys.exit(0)


if __name__ == "__main__":
    main()
