"""Orchestrator for the Lock Pipeline.

Runs all four stages in the required order using a single command:

    python run_pipeline.py

Deterministic output (all four stages share the same pinned timestamp):

    $env:LOCK_PIPELINE_GENERATED_AT = "1970-01-01 00:00:00"
    python run_pipeline.py

Or use the epoch shorthand:

    $env:LOCK_PIPELINE_DETERMINISTIC = "1"
    python run_pipeline.py
"""
from __future__ import annotations

import os
import sys
from pathlib import Path

# Guarantee imports resolve from the pipeline root regardless of working directory.
_ROOT = Path(__file__).resolve().parent
if str(_ROOT) not in sys.path:
    sys.path.insert(0, str(_ROOT))

import verse_locks
import sura_locks
import global_lock
import locks_summary
import hash_registry


def main() -> None:
    root = _ROOT

    print("[preflight] signed registry integrity check ...", end=" ", flush=True)
    verify_code = hash_registry.cmd_verify_signed()
    if verify_code != 0:
        print("failed.")
        raise SystemExit(
            "Aborting: signed integrity verification failed. "
            "Run 'python hash_registry.py --verify-signed' for details."
        )
    print("ok.")

    txt = root / "summary" / "txt"
    json_dir = root / "summary" / "json"
    txt.mkdir(parents=True, exist_ok=True)
    json_dir.mkdir(parents=True, exist_ok=True)

    # Pin a single timestamp for the entire run so all four output files share
    # the same Generated: line.  Honour any caller-supplied override first.
    if not os.getenv("LOCK_PIPELINE_GENERATED_AT") and not os.getenv("LOCK_PIPELINE_DETERMINISTIC"):
        from datetime import datetime
        os.environ["LOCK_PIPELINE_GENERATED_AT"] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    print("=== LOCK PIPELINE ===")

    print("[1/4] verse_locks  ...", end=" ", flush=True)
    verse_locks.build_summary(root, txt / "grand_verse_lock_summary.txt")
    print("done.")

    print("[2/4] sura_locks   ...", end=" ", flush=True)
    sura_locks.build_summary(root, txt / "grand_sura_lock_summary.txt")
    print("done.")

    print("[3/4] global_lock  ...", end=" ", flush=True)
    global_lock.build_summary(root, txt / "global_lock_summary.txt")
    print("done.")

    print("[4/4] locks_summary...", end=" ", flush=True)
    locks_summary.build_locks_summary(root, txt / "LOCKS.txt")
    print("done.")

    print("=== Pipeline complete. ===")


if __name__ == "__main__":
    main()
