from __future__ import annotations

import json
import os
import pathlib
import runpy
import sys
import time


def main() -> int:
    arguments = list(sys.argv[1:])
    if "--bootstrapped-path" not in arguments or "--target" not in arguments:
        raise SystemExit("--bootstrapped-path and --target are required")
    boot_index = arguments.index("--bootstrapped-path")
    target_index = arguments.index("--target")
    boot = pathlib.Path(arguments[boot_index + 1])
    target = pathlib.Path(arguments[target_index + 1]).resolve()
    remainder = arguments[target_index + 2:]
    if remainder[:1] == ["--"]:
        remainder = remainder[1:]
    boot.parent.mkdir(parents=True, exist_ok=True)
    injected_delay = float(os.environ.get("WRLAB_R9_INJECTED_STARTUP_DELAY_SECONDS", "0"))
    if injected_delay > 0:
        time.sleep(injected_delay)
    temporary = boot.with_suffix(boot.suffix + f".{os.getpid()}.tmp")
    temporary.write_text(json.dumps({"status": "BOOTSTRAPPED", "bootstrapped": True, "pid": os.getpid(), "event_epoch": time.time_ns() / 1_000_000_000, "phase": "minimal_launcher_before_target_import"}, sort_keys=True), encoding="utf-8")
    os.replace(temporary, boot)
    sys.argv = [str(target), *remainder]
    runpy.run_path(str(target), run_name="__main__")
    return 0


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