#!/usr/bin/env python3
"""PATH shim: logs every `botmap` invocation, then runs the real CLI.

Placed first on PATH as `botmap`. Runs the real CLI via
`<python> -m botmap` (module form, so it never re-invokes this shim),
captures argv / exit code / stdout / stderr to the JSON-lines file named by
$OVERTURE_EVAL_LOG, then reproduces stdout/stderr and the exit code
unchanged. Fails open: if logging breaks, the real CLI still runs and the
agent sees normal output.

Env:
  OVERTURE_EVAL_PYTHON  python interpreter that has `botmap` installed
                        (defaults to this script's interpreter)
  OVERTURE_EVAL_LOG     append-target for the JSON-lines call log (optional)
"""

from __future__ import annotations

import json
import os
import subprocess
import sys
import time


def main() -> int:
    argv = sys.argv[1:]
    python = os.environ.get("OVERTURE_EVAL_PYTHON") or sys.executable

    start = time.monotonic()
    proc = subprocess.run(
        [python, "-m", "botmap", *argv],
        capture_output=True,
        text=True,
    )
    duration = time.monotonic() - start

    log_path = os.environ.get("OVERTURE_EVAL_LOG")
    if log_path:
        try:
            with open(log_path, "a", encoding="utf-8") as fh:
                fh.write(
                    json.dumps(
                        {
                            "argv": argv,
                            "exit_code": proc.returncode,
                            "stdout": proc.stdout,
                            "stderr": proc.stderr,
                            "duration": duration,
                        }
                    )
                    + "\n"
                )
        except OSError:
            pass  # fail open — logging must never break the agent's run

    sys.stdout.write(proc.stdout)
    sys.stderr.write(proc.stderr)
    return proc.returncode


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