"""Start the frozen Runrail engine without Python site initialization."""

from __future__ import annotations

import json
import os
from pathlib import Path
import sys


def _engine_source() -> Path:
    configured = os.environ.get("RUNRAIL_ENGINE_ROOT", "").strip()
    if not configured:
        raise RuntimeError("runrail-engine-root-missing")
    engine_root = Path(configured)
    if not engine_root.is_absolute():
        raise RuntimeError("runrail-engine-root-not-absolute")
    source = (engine_root / "src").resolve(strict=True)
    cli_module = source / "ra_cpu" / "cli.py"
    if not cli_module.is_file():
        raise RuntimeError("runrail-engine-cli-missing")
    return source


def main() -> int:
    source = _engine_source()
    sys.path.insert(0, str(source))
    if sys.argv[1:] == ["--bootstrap-probe"]:
        import ra_cpu

        module_path = Path(ra_cpu.__file__).resolve(strict=True)
        if source not in module_path.parents:
            raise RuntimeError("runrail-engine-import-escaped")
        print(
            json.dumps(
                {
                    "ok": True,
                    "mode": "isolated-no-site",
                    "engineSource": str(source),
                    "modulePath": str(module_path),
                    "siteImported": "site" in sys.modules,
                },
                sort_keys=True,
            )
        )
        return 0

    from ra_cpu.cli import main as engine_main

    return engine_main(sys.argv[1:])


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