#!/usr/bin/env python3
"""
CI-style self-check for the RU↔host universality engine bundle.

Pipeline:
1) Regenerate + validate all built-in examples
2) Validate all robust certificates
3) Build artifact index (json + md)
4) Build the reproducible global report (Fibonacci alpha chambers)

Exit code is nonzero on any failure.

Usage:
  python tools/ci_selfcheck.py
"""

from __future__ import annotations
import os
import subprocess
import sys

def run(cmd: list[str], label: str) -> int:
    print("\n=== " + label + " ===")
    p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    print(p.stdout)
    return p.returncode

def main() -> int:
    root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
    py = sys.executable

    steps = [
        ([py, os.path.join(root, "tools", "generate_certificate_from_instance.py"), "--root", root, "--host_instance", "sources/host_instances/fibonacci_contraction_instance.json", "--name", "demo_fibonacci_contraction", "--Lmax", "8"], "Generate candidate certificate from standardized host instance"),
        ([py, os.path.join(root, "tools", "extract_string_theory_index.py"), "--root", root], "Extract string theory context map"),
        ([py, os.path.join(root, "tools", "check_theorem_bundle_present.py")], "Check theorem bundle present"),
        ([py, os.path.join(root, "tools", "audit_sanity_checks.py"), "--root", root], "Audit sanity checks"),
        ([py, os.path.join(root, "tools", "run_all_examples.py"), "--root", root], "Regenerate + validate built-in examples"),
        ([py, os.path.join(root, "tools", "validate_certificates.py"), "--root", root], "Validate all robust certificates"),
        ([py, os.path.join(root, "tools", "build_artifact_index.py"), "--root", root], "Build artifact index"),
        ([py, os.path.join(root, "tools", "build_fibonacci_alpha_chambers_report.py"), "--root", root], "Build Fibonacci alpha chamberwise global report"),
    ]

    for cmd, label in steps:
        rc = run(cmd, label)
        if rc != 0:
            print("\nFAILED:", label, "exit code", rc)
            return rc

    print("\nALL CHECKS PASSED")
    return 0

if __name__ == "__main__":
    raise SystemExit(main())
