#!/usr/bin/env python3
"""Run Spatial Bench from its extracted macOS package."""

import argparse
import os
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory


COMMANDS = {
    "doctor": ("spatial_onboarding.py", "check package integrity, Python, native physics and Metal"),
    "quickstart": ("spatial_onboarding.py", "run, inspect and verify your first task"),
    "sample": ("spatial_suite.py", "run the included reference policies"),
    "suite": ("spatial_suite.py", "run or verify a suite with executable or native policies"),
    "model": ("spatial_model_bench.py", "run or verify a vision model archive"),
    "task-model": ("spatial_task_model.py", "run a local or hosted vision model on a saved World task or verify its archive"),
    "compare-task-models": ("spatial_compare_task_models.py", "compare two vision recordings of the same World task"),
    "instruction-pair": ("spatial_instruction_pair.py", "compare two instructions against the same World and vision endpoint"),
    "instruction-suite": ("spatial_instruction_suite.py", "evaluate vision models on matched Worlds, camera angles and seeds"),
    "visual-memory": ("spatial_visual_memory.py", "compare current-frame and two-frame decisions on matched Worlds"),
    "custom-task": ("spatial_custom_task.py", "run or replay project-authored tasks with custom actions and rewards"),
    "probe-custom-model": ("spatial_probe_custom_model.py", "check model connections and one action on the first task observation"),
    "custom-task-counterfactual": ("spatial_custom_task_counterfactual.py", "test an alternate action at a recorded decision"),
    "presentation-frames": ("spatial_presentation.py", "render verified replay frames for a custom task"),
    "author-custom-task": ("spatial_author_custom_task.py", "create and validate a standalone custom task from World"),
    "author-lighting-suite": ("spatial_author_lighting_suite.py", "generate a matched lighting suite from a saved World task"),
    "custom-task-suite": ("spatial_custom_task_suite.py", "evaluate or verify a partition of project-authored tasks"),
    "delivery-report": ("spatial_delivery_report.py", "verify paired delivery orders and report changes in docking choices"),
    "compare-custom-task-runs": ("spatial_compare_custom_task_suites.py", "compare standalone task runs on shared seeds"),
    "compare-lighting-runs": ("spatial_compare_lighting.py", "compare an original World run against its lighting variants"),
    "compare-custom-task-suites": ("spatial_compare_custom_task_suites.py", "compare matched suite runs and identify regressions"),
    "custom-task-dataset": ("spatial_custom_task_dataset.py", "export or verify training trajectories from a custom development suite"),
    "compare": ("spatial_compare_models.py", "compare two model archives and export their differing frames"),
    "evidence": ("spatial_evidence.py", "export or independently verify a comparison evidence folder"),
    "dataset": ("spatial_export_dataset.py", "export verified development trajectories and RGB frames"),
    "learn": ("spatial_learn.py", "fit a demonstration policy and verify its held-out trials"),
    "replay": ("spatial_visual_replay.py", "verify and capture a recorded episode"),
    "regression": ("spatial_regression.py", "compare two builds on the same World and recorded actions"),
    "regression-suite": ("spatial_regression_suite.py", "compare two builds across recorded scenarios and seeds"),
    "author": ("spatial_author_suite.py", "export a paired benchmark from a saved Crescent scene"),
}

def has_option(options, name):
    return any(option == name or option.startswith(name + "=") for option in options)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    subcommands = parser.add_subparsers(dest="command", required=True)
    for name, (_, description) in COMMANDS.items():
        subcommands.add_parser(name, help=description, add_help=False)
    args, options = parser.parse_known_args()
    root = Path(__file__).resolve().parent
    script = root / "tools/SpatialBench" / COMMANDS[args.command][0]
    if not script.is_file():
        parser.error("Run the spatial-bench launcher from an extracted package")

    if args.command in {"doctor", "quickstart"}:
        os.execv(sys.executable, [sys.executable, "-B", str(script), args.command, *options])

    defaults = [] if args.command in {"regression", "regression-suite"} else [
        "--library", str(root / "lib/libCrescentSpatial.dylib"),
        "--renderer", str(root / "lib/libCrescentRuntime.dylib"),
        "--metallib", str(root / "shaders/default.metallib"),
    ]
    if args.command == "sample":
        policies = root / "Benchmarks/Spatial"
        defaults += ["--partition", "development"]
        if not has_option(options, "--verify"):
            defaults += ["--policy", f"direct={policies / 'pixel_direct.py'}",
                         "--policy", f"detour={policies / 'pixel_policy.py'}"]
    if args.command == "compare-custom-task-runs":
        defaults.append("--single-task")

    command = [sys.executable, "-B", str(script), *defaults]
    env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1")
    if args.command in {"custom-task", "custom-task-suite"}:
        os.execve(sys.executable, [*command, *options], env)
    uses_suite = args.command in {"suite", "sample", "model", "compare", "dataset", "learn"}
    uses_suite = uses_suite or (args.command == "evidence" and not has_option(options, "--verify"))
    if not uses_suite or has_option(options, "--suite"):
        return subprocess.call([*command, *options], env=env)

    # The renderer can create project directories, even for a headless capture.
    with TemporaryDirectory(prefix="crescent-bench-fixture-") as temporary:
        fixture = Path(temporary) / "closing-route"
        shutil.copytree(root / "fixtures/closing-route", fixture)
        return subprocess.call([*command, "--suite", str(fixture / "suite.json"), *options], env=env)


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