"""Bootstrapper for running commands under instrumentation."""

from __future__ import annotations

import os
import runpy
import sys
from typing import List

from autodebug_probe.runtime import initialize
from autodebug_probe.recorder import get_recorder


def _extract_command(argv: List[str]) -> List[str]:
    if "--" not in argv:
        return []
    idx = argv.index("--")
    return argv[idx + 1 :]


def _run_as_module(module: str, argv: List[str]) -> int:
    sys.argv = [module] + argv
    try:
        runpy.run_module(module, run_name="__main__")
    except SystemExit as exc:
        return int(exc.code or 0)
    return 0


def _run_as_path(path: str, argv: List[str]) -> int:
    sys.argv = [path] + argv
    try:
        runpy.run_path(path, run_name="__main__")
    except SystemExit as exc:
        return int(exc.code or 0)
    return 0


def _finalize(code: int) -> int:
    """Record RUN_END and close the recorder to flush all streams."""
    recorder = get_recorder()
    recorder.record_event({"type": "RUN_END", "exit_code": code})
    recorder.close()
    return code


def main() -> int:
    cmd = _extract_command(sys.argv)
    if not cmd:
        print("Missing command after --", file=sys.stderr)
        return 2

    initialize()

    if cmd[0] in {"python", sys.executable}:
        if len(cmd) >= 3 and cmd[1] == "-m":
            code = _run_as_module(cmd[2], cmd[3:])
            return _finalize(code)
        if len(cmd) >= 2:
            code = _run_as_path(cmd[1], cmd[2:])
            return _finalize(code)
        print("Missing python target", file=sys.stderr)
        return 2

    if cmd[0].endswith(".py"):
        code = _run_as_path(cmd[0], cmd[1:])
        return _finalize(code)

    code = _run_as_module(cmd[0], cmd[1:])
    return _finalize(code)


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