#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Phase 2B one-command pipeline runner.

Run from the workspace root:

    python run_pipeline.py

Optional clean rebuild:

    python run_pipeline.py --clean

Pipeline stages:
1. Run 14_initial_engine.py.
2. Generate workspace registry, hash manifest, and validation report.
"""

from __future__ import annotations

import argparse
import shutil
import subprocess
import sys
from pathlib import Path


OUTPUT_DIRS = ["14_initial_engine_outputs"]

STEPS = [
    {
        "label": "[1/2] 14 Initial Engine",
        "script": "14_initial_engine.py",
        "args": [],
    },
    {
        "label": "[2/2] Workspace Registry / Hash Audit",
        "script": "workspace_registry_hash_audit.py",
        "args": ["--root", ".", "--output-dir", "14_initial_engine_outputs/audit"],
    },
]


def clean_outputs(root: Path) -> None:
    for name in OUTPUT_DIRS:
        path = root / name
        if path.exists():
            shutil.rmtree(path)
            print(f"[CLEAN] Removed {name}/")


def require_script(root: Path, script_name: str) -> Path:
    path = root / script_name
    if not path.exists():
        raise FileNotFoundError(f"Required script not found: {script_name}")
    return path


def run_step(root: Path, step: dict) -> None:
    script_path = require_script(root, step["script"])
    cmd = [sys.executable, str(script_path), *step["args"]]

    print()
    print("=" * 72)
    print(step["label"])
    print("=" * 72)
    print(" ".join(cmd))

    completed = subprocess.run(cmd, cwd=root)
    if completed.returncode != 0:
        raise SystemExit(f"\n[FAIL] {step['label']} exited with code {completed.returncode}")

    print(f"[OK] {step['label']} completed")


def main() -> None:
    parser = argparse.ArgumentParser(description="Run the full Phase 2B initial engine pipeline.")
    parser.add_argument("--clean", action="store_true", help="Delete generated output folders before running.")
    parser.add_argument("--skip-audit", action="store_true", help="Skip workspace registry/hash audit.")
    args = parser.parse_args()

    root = Path(__file__).resolve().parent

    print("Phase 2B Pipeline")
    print(f"Workspace root: {root}")

    if args.clean:
        clean_outputs(root)

    for step in STEPS:
        if args.skip_audit and step["script"] == "workspace_registry_hash_audit.py":
            print("[SKIP] Workspace Registry / Hash Audit")
            continue
        run_step(root, step)

    print()
    print("=" * 72)
    print("Pipeline completed successfully.")
    print("=" * 72)
    print("Generated folders:")
    for folder in OUTPUT_DIRS:
        path = root / folder
        status = "present" if path.exists() else "not present"
        print(f"- {folder}/ [{status}]")


if __name__ == "__main__":
    main()
