#!/usr/bin/env python3
"""Compare standalone rpi Mini with a batched client using local Host."""
import argparse
import asyncio
import ctypes
import hashlib
import importlib.util
import json
import math
from pathlib import Path
import platform
import resource
import subprocess
import sys
import tempfile
import time
from datetime import datetime, timezone


MODES = ("standalone", "host_socket")
SYSTEM_PROMPT = "Reply with a short line."


def prompt_for(index):
    marker = f"probe-agent:{index}\n"
    return marker + "a" * (1024 - len(marker))


async def exchange(socket, workspace, index):
    # Version 1 is the local wire sent by run_mini_client, not a public API.
    reader, writer = await asyncio.open_unix_connection(socket)
    try:
        payload = {"version": 1, "workspace": str(workspace), "mini": {
            "input": {"prompts": [prompt_for(index)], "images": []},
            "provider": "bench", "model": "probe", "thinking": "off",
            "timeout": {"secs": 300, "nanos": 0},
            "no_tools": True, "no_builtin_tools": False, "no_skills": True,
            "no_prompt_templates": True, "no_context_files": True,
            "system_prompt": SYSTEM_PROMPT, "append_system_prompt": [],
            "debug_system_prompt": False,
        }}
        writer.write(json.dumps(payload).encode() + b"\n")
        await writer.drain()
        result = json.loads(await reader.readline())
        expected = {"type": "mini_finished", "exit_code": 0, "text": f"completed {index}",
                    "diagnostics": []}
        if result != expected:
            raise RuntimeError(f"Agent {index}: {result}")
        return result["text"]
    finally:
        writer.close()
        await writer.wait_closed()


async def submit_batch(workspace, agents, sockets):
    tasks = []
    for index in range(agents):
        socket = sockets[index % len(sockets)]
        tasks.append(asyncio.create_task(exchange(socket, workspace, index)))
        if (index + 1) % 12 == 0:
            await asyncio.sleep(0.025)
            for task in tasks[-12:]:
                if task.done():
                    task.result()
    for result in await asyncio.gather(*tasks):
        print(result)


class RusageV0(ctypes.Structure):
    _fields_ = [("uuid", ctypes.c_uint8 * 16), ("user_ns", ctypes.c_uint64),
                ("system_ns", ctypes.c_uint64), ("wakeups", ctypes.c_uint64 * 2),
                ("pageins", ctypes.c_uint64), ("wired_bytes", ctypes.c_uint64),
                ("resident_bytes", ctypes.c_uint64), ("footprint_bytes", ctypes.c_uint64),
                ("start_abstime", ctypes.c_uint64), ("exit_abstime", ctypes.c_uint64)]


class TaskInfo(ctypes.Structure):
    _fields_ = [("times", ctypes.c_uint64 * 6), ("counters", ctypes.c_int32 * 12)]


class ProcCounters:
    def __init__(self):
        lib = ctypes.CDLL("/usr/lib/libproc.dylib", use_errno=True)
        self.rusage = lib.proc_pid_rusage
        self.rusage.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_void_p]
        self.info = lib.proc_pidinfo
        self.info.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_uint64,
                              ctypes.c_void_p, ctypes.c_int]

    def read(self, pid):
        usage = RusageV0()
        if self.rusage(pid, 0, ctypes.byref(usage)) != 0:
            raise OSError(ctypes.get_errno(), f"proc_pid_rusage failed for {pid}")
        task = TaskInfo()
        if self.info(pid, 4, 0, ctypes.byref(task), ctypes.sizeof(task)) != ctypes.sizeof(task):
            raise OSError(ctypes.get_errno(), f"PROC_PIDTASKINFO failed for {pid}")
        fd_size = 8  # sizeof(struct proc_fdinfo)
        size = self.info(pid, 1, 0, None, 0)
        for _ in range(4):
            if size <= 0:
                break
            buffer = ctypes.create_string_buffer(size + 32 * fd_size)
            count = self.info(pid, 1, 0, buffer, len(buffer))
            if 0 < count < len(buffer):
                return {"footprint_bytes": usage.footprint_bytes,
                        "rss_bytes": usage.resident_bytes,
                        "threads": task.counters[9], "fds": count // fd_size}
            size = len(buffer) * 2
        raise OSError(ctypes.get_errno(), f"PROC_PIDLISTFDS failed for {pid}")

    def aggregate(self, children):
        totals = dict(processes=len(children), footprint_bytes=0, rss_bytes=0,
                      threads=0, fds=0)
        for child in children:
            for key, value in self.read(child.pid).items():
                totals[key] += value
        return totals


def load_fixture(repo):
    spec = importlib.util.spec_from_file_location(
        "rpi_bench_fixture", repo / "scripts/bench-shared-host.py")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)

    class Fixture(module.FixtureServer):
        def __init__(self, count):
            super().__init__(count, "model", 16384)
            self.body_hashes = {}

        def validate_request(self, body):
            index, has_tool_result = super().validate_request(body)
            if body.get("tools") or has_tool_result:
                raise ValueError("unexpected tools in Mini request")
            digest = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
            self.body_hashes[index] = digest
            return index, has_tool_result

        def body_digest(self):
            ordered = [self.body_hashes[index] for index in sorted(self.body_hashes)]
            return hashlib.sha256("".join(ordered).encode()).hexdigest()

    return Fixture


def write_json(path, value):
    path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")


def start(command, workspace, env, log):
    with log.open("wb") as output:
        return subprocess.Popen(command, cwd=workspace, env=env, stdin=subprocess.DEVNULL,
                                stdout=output, stderr=subprocess.STDOUT)


async def wait_for(predicate, deadline, check):
    while not predicate():
        check()
        if time.monotonic() > deadline:
            raise TimeoutError("phase deadline exceeded")
        await asyncio.sleep(0.05)


def reap(daemons, clients):
    children = clients + daemons
    for child in children:
        if child.poll() is None:
            child.terminate()
    deadline = time.monotonic() + 5
    for child in children:
        try:
            child.wait(max(0, deadline - time.monotonic()))
        except subprocess.TimeoutExpired:
            child.kill()
            child.wait()


async def measure(args, fixture_type, mode, number):
    count = args.agents
    shared = mode == "host_socket"
    areas = [f"area{i}" for i in range(math.ceil(count / 250))] if shared else []
    server = fixture_type(count)
    daemons, clients, samples = [], [], []
    before_cpu = resource.getrusage(resource.RUSAGE_CHILDREN)
    with tempfile.TemporaryDirectory(prefix="rh-ab-", dir="/tmp") as temp:
        root = Path(temp).resolve()
        home, workspace = root / "a", root / "w"
        home.mkdir()
        workspace.mkdir()
        env = {"HOME": str(root), "RPI_CODING_AGENT_DIR": str(home),
               "XDG_CONFIG_HOME": str(root / "config"), "PATH": "/usr/bin:/bin",
               "RPI_OFFLINE": "1", "NO_PROXY": "127.0.0.1", "TOKIO_WORKER_THREADS": "1",
               "LANG": "en_US.UTF-8"}
        url = await server.start()
        write_json(home / "models.json", {"providers": {"bench": {
            "api": "openai-completions", "baseUrl": url, "apiKey": "local-fixture-only",
            "models": [{"id": "probe", "contextWindow": 32768, "maxTokens": 256}],
        }}})
        write_json(home / "settings.json", {"defaultProvider": "bench", "defaultModel": "probe"})
        write_json(home / "host.json", {"areas": {area: {"maxAgents": 250} for area in areas}})
        sockets = [home / "local-host-v1" / f"area-{area}" / "rpc.sock" for area in areas]
        counters = ProcCounters()

        def gate_check():
            for index, daemon in enumerate(daemons):
                if daemon.poll() is not None:
                    raise RuntimeError(f"{areas[index]} exited: {(root / areas[index]).read_text()}")
            for index, client in enumerate(clients):
                if client.poll() is not None:
                    raise RuntimeError(f"client {index} exited during load: "
                                       f"{(root / str(index)).read_text()[:600]}")

        try:
            daemon_start = time.monotonic()
            for area in areas:
                daemons.append(start([args.binary, "__rpi_local_host", area], workspace,
                                     env, root / area))
            await wait_for(lambda: all(socket.is_socket() for socket in sockets),
                           daemon_start + 15, gate_check)
            daemon_ready_s = time.monotonic() - daemon_start if shared else None
            command = [args.binary, "--mini", "--provider", "bench", "--model", "probe",
                       "--thinking", "off", "--timeout", "300", "--no-tools", "--no-extensions",
                       "--no-skills", "--no-context-files", "--no-prompt-templates",
                       "--system-prompt", SYSTEM_PROMPT]
            launch = time.monotonic()
            if shared:
                batch = [sys.executable, "-B", Path(__file__).resolve(), "--submit-batch",
                         workspace, str(count), *sockets]
                clients.append(start(batch, workspace, env, root / "0"))
            else:
                for index in range(count):
                    clients.append(start(command + [prompt_for(index)], workspace,
                                         env, root / str(index)))
                    if (index + 1) % 12 == 0:
                        await asyncio.sleep(0.025)
                        for client in clients[-12:]:
                            if client.poll() is not None:
                                gate_check()
            await wait_for(server.ready.is_set, launch + args.timeout, gate_check)
            barrier_s = time.monotonic() - launch
            print(f"round {number} {mode}: {server.active}/{count} at request barrier "
                  f"after {barrier_s:.2f}s", flush=True)
            for sample_index in range(3):
                if sample_index:
                    await asyncio.sleep(0.75)
                gate_check()
                if server.active != count or server.errors:
                    raise RuntimeError(f"invalid request barrier: {server.summary()}")
                begin = time.monotonic()
                daemon_usage = counters.aggregate(daemons)
                client_usage = counters.aggregate(clients)
                end = time.monotonic()
                combined = {key: daemon_usage[key] + client_usage[key] for key in client_usage}
                samples.append({"elapsed_s": (begin + end) / 2 - launch,
                                "scan_s": end - begin, "daemons": daemon_usage,
                                "clients": client_usage, "total": combined})
            server.release.set()
            released = time.monotonic()
            await wait_for(lambda: all(cli.poll() is not None for cli in clients),
                           released + args.timeout, lambda: None)
            completion_s = time.monotonic() - released
            failures = []
            if shared:
                output = (root / "0").read_text().splitlines()
                if clients[0].returncode != 0 or output != [f"completed {i}" for i in range(count)]:
                    failures.append({"code": clients[0].returncode, "lines": len(output),
                                     "output_tail": output[-5:]})
            else:
                for index, client in enumerate(clients):
                    output = (root / str(index)).read_text()
                    if client.returncode != 0 or output.strip() != f"completed {index}":
                        failures.append({"agent": index, "code": client.returncode,
                                         "output": output[:300]})
            if (failures or server.requests != count or len(server.final) != count
                    or server.peak != count or server.errors):
                raise RuntimeError(f"failed results: {failures[:8]}; {server.summary()}")
            result = {"round": number, "mode": mode, "completed": count, "areas": len(areas),
                      "barrier_s": barrier_s, "daemon_ready_s": daemon_ready_s,
                      "post_release_completion_s": completion_s,
                      "fixture": server.summary(), "body_sha256": server.body_digest(),
                      "samples": samples}
        except Exception as error:
            raise RuntimeError(f"{mode} round {number}, started {len(clients)} clients, "
                               f"fixture {server.summary()}: {error}") from error
        finally:
            reap(daemons, clients)
            await server.close()
    after_cpu = resource.getrusage(resource.RUSAGE_CHILDREN)
    result["cpu_user_s"] = after_cpu.ru_utime - before_cpu.ru_utime
    result["cpu_system_s"] = after_cpu.ru_stime - before_cpu.ru_stime
    return result


def sysctl(name):
    return subprocess.check_output(["/usr/sbin/sysctl", "-n", name], text=True).strip()


async def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--repo", required=True, type=Path)
    parser.add_argument("--binary", required=True, type=Path)
    parser.add_argument("--output", required=True, type=Path)
    parser.add_argument("--agents", type=int, default=1000)
    parser.add_argument("--rounds", type=int, default=3)
    parser.add_argument("--timeout", type=int, default=120)
    args = parser.parse_args()
    if not (platform.system() == "Darwin" and 1 <= args.agents <= 1000
            and args.rounds >= 1 and 1 <= args.timeout < 300):
        parser.error("requires macOS, 1–1000 agents, at least one round, and timeout 1–299s")
    if args.output.exists():
        parser.error("output file already exists")
    args.binary = args.binary.resolve(strict=True)
    args.repo = args.repo.resolve(strict=True)
    fixture = load_fixture(args.repo)
    report = {"success": False, "timestamp_utc": datetime.now(timezone.utc).isoformat(),
              "os": platform.mac_ver()[0], "arch": platform.machine(),
              "hardware_model": sysctl("hw.model"), "cpu_brand": sysctl("machdep.cpu.brand_string"),
              "logical_cpus": int(sysctl("hw.ncpu")), "ram_bytes": int(sysctl("hw.memsize")),
              "process_limit": list(resource.getrlimit(resource.RLIMIT_NPROC)),
              "fd_limit": list(resource.getrlimit(resource.RLIMIT_NOFILE)),
              "repo_revision": subprocess.check_output(
                  ["/usr/bin/git", "rev-parse", "HEAD"], cwd=args.repo, text=True).strip(),
              "binary_sha256": hashlib.sha256(args.binary.read_bytes()).hexdigest(),
              "binary_version": subprocess.check_output([args.binary, "--version"], text=True).strip(),
              "run_config": {"agents": args.agents, "rounds": args.rounds, "area_capacity": 250,
                             "modes": MODES,
                             "tokio_worker_threads_per_process": 1,
                             "prompt_bytes": 1024, "tools": False, "extensions": False,
                             "saved_session": False, "timeout_seconds": args.timeout},
              "runs": []}
    try:
        for number in range(1, args.rounds + 1):
            offset = (number - 1) % len(MODES)
            group = [await measure(args, fixture, mode, number)
                     for mode in MODES[offset:] + MODES[:offset]]
            if len({run["body_sha256"] for run in group + report["runs"]}) != 1:
                raise RuntimeError("bench modes sent different model request bodies")
            report["runs"].extend(group)
            write_json(args.output, report)
        report["success"] = True
    except Exception as error:
        report["error"] = str(error)
        raise
    finally:
        write_json(args.output, report)


if __name__ == "__main__":
    if sys.argv[1:2] == ["--submit-batch"]:
        workspace, count, *sockets = sys.argv[2:]
        asyncio.run(submit_batch(Path(workspace), int(count), sockets))
    else:
        asyncio.run(main())
