#!/usr/bin/env python3
"""Run the local native wire capture proxy for a browser compare pane."""
import json
import os
import shutil
import signal
import socket
import subprocess
import sys
import time
from pathlib import Path


def main():
    harness, destination = sys.argv[1:]
    if harness not in ("claude", "codex"):
        raise ValueError("Unsupported capture harness")
    addon = Path(__file__).with_name("wire-capture-addon.py")
    ca = Path.home() / ".mitmproxy" / "mitmproxy-ca-cert.pem"
    candidates = [
        shutil.which("mitmdump"),
        str(Path.home() / "Library" / "Python" / "3.9" / "bin" / "mitmdump"),
    ]
    mitmdump = next((path for path in candidates if path and Path(path).is_file() and os.access(path, os.X_OK)), None)
    if not mitmdump or not addon.is_file() or not ca.is_file():
        raise RuntimeError("--wire needs mitmdump and a trusted ~/.mitmproxy CA; see docs/NATIVE_CODEX_WIRE_CAPTURE.md")
    directory = Path(destination)
    directory.mkdir(parents=True, exist_ok=True)
    with socket.socket() as sock:
        sock.bind(("127.0.0.1", 0))
        port = sock.getsockname()[1]
    hosts = "chatgpt.com,api.openai.com" if harness == "codex" else "api.anthropic.com"
    log = (directory / "mitmdump.log").open("wb")
    child = subprocess.Popen([
        mitmdump, "--listen-host", "127.0.0.1", "--listen-port", str(port),
        "--set", "block_global=false", "-s", str(addon),
        "--set", f"pr_capture_hosts={hosts}", "--set", f"pr_capture_dir={directory}",
    ], stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)
    try:
        deadline = time.monotonic() + 15
        while time.monotonic() < deadline:
            if child.poll() is not None:
                raise RuntimeError(f"mitmdump exited; see {directory / 'mitmdump.log'}")
            with socket.socket() as probe:
                probe.settimeout(.3)
                if probe.connect_ex(("127.0.0.1", port)) == 0:
                    break
            time.sleep(.2)
        else:
            raise RuntimeError(f"mitmdump did not listen; see {directory / 'mitmdump.log'}")
        proxy = f"http://127.0.0.1:{port}"
        print(json.dumps({
            "HTTPS_PROXY": proxy, "HTTP_PROXY": proxy, "https_proxy": proxy, "http_proxy": proxy,
            "NO_PROXY": "localhost,127.0.0.1", "no_proxy": "localhost,127.0.0.1",
            "NODE_EXTRA_CA_CERTS": str(ca), "SSL_CERT_FILE": str(ca), "REQUESTS_CA_BUNDLE": str(ca),
        }), flush=True)
        sys.stdin.read()
    finally:
        if child.poll() is None:
            child.send_signal(signal.SIGTERM)
            try:
                child.wait(timeout=10)
            except subprocess.TimeoutExpired:
                child.kill()
        log.close()


if __name__ == "__main__":
    try:
        main()
    except Exception as error:
        print(str(error), file=sys.stderr)
        raise SystemExit(1)
