"""Measure an existing mcp-server-time installation over stdio. No installs or network.

python installed_time_probe.py --python PATH/TO/VENV/python --out NEW-COHORT.json
The probe itself requires psutil. The target interpreter requires mcp-server-time.
"""

from __future__ import annotations

import argparse
import asyncio
import hashlib
import json
import os
import platform
import statistics
import subprocess
import tempfile
import time
from datetime import datetime, timezone
from pathlib import Path

import psutil

PROTOCOL = "2024-11-05"
METRICS = ("ready_ms", "list_ms", "call_ms", "rss_after_list_mib", "rss_after_call_mib")
METADATA_CODE = """
import hashlib, importlib.metadata as m, json, platform, sys
d=m.distribution('mcp-server-time'); h=hashlib.sha256()
items=sorted(f for f in d.files if str(f).replace(chr(92),'/').startswith('mcp_server_time/') and str(f).endswith('.py'))
assert items, 'installed source files missing'
for f in items:
 h.update(str(f).replace(chr(92),'/').encode()+b'\\0'); h.update(hashlib.sha256(f.locate().read_bytes()).digest())
print(json.dumps({'python':platform.python_version(),'package':'mcp-server-time','package_version':d.version,'sdk_version':m.version('mcp'),'package_source_sha256':h.hexdigest(),'machine':platform.machine()}))
"""


def allowed_environment(scratch):
    keep = {
        key: value
        for key, value in os.environ.items()
        if key.upper()
        in {
            "SYSTEMROOT",
            "WINDIR",
            "PATH",
            "PATHEXT",
            "COMSPEC",
            "LD_LIBRARY_PATH",
            "SYSTEMDRIVE",
            "LANG",
            "LC_ALL",
        }
    }
    keep.update(
        TMPDIR=scratch, TEMP=scratch, TMP=scratch, HOME=scratch, USERPROFILE=scratch
    )
    return keep


def rss_mib(pid):
    process = psutil.Process(pid)
    return round(
        sum(p.memory_info().rss for p in [process, *process.children(recursive=True)])
        / 1048576,
        3,
    )


async def rpc(proc, request_id, method, params=None):
    message = {"jsonrpc": "2.0", "id": request_id, "method": method}
    if params is not None:
        message["params"] = params
    proc.stdin.write((json.dumps(message) + "\n").encode())
    await proc.stdin.drain()
    async with asyncio.timeout(20):
        while raw := await proc.stdout.readline():
            reply = json.loads(raw)
            if reply.get("id") == request_id:
                if "error" in reply or "result" not in reply:
                    raise RuntimeError(f"{method} did not return a successful result")
                return reply["result"]
    raise RuntimeError(f"server closed before {method} returned")


async def run_once(exe, scratch, env):
    start = time.perf_counter_ns()
    proc = await asyncio.create_subprocess_exec(
        str(exe),
        "-I",
        "-B",
        "-m",
        "mcp_server_time",
        "--local-timezone",
        "UTC",
        stdin=asyncio.subprocess.PIPE,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.DEVNULL,
        cwd=scratch,
        env=env,
        limit=1024 * 1024,
    )
    try:
        init = await rpc(
            proc,
            1,
            "initialize",
            {
                "protocolVersion": PROTOCOL,
                "capabilities": {},
                "clientInfo": {
                    "name": "techfuelhq-installed-time-probe",
                    "version": "1",
                },
            },
        )
        ready = (time.perf_counter_ns() - start) / 1e6
        proc.stdin.write(b'{"jsonrpc":"2.0","method":"notifications/initialized"}\n')
        await proc.stdin.drain()
        start = time.perf_counter_ns()
        listing = await rpc(proc, 2, "tools/list")
        list_ms = (time.perf_counter_ns() - start) / 1e6
        tools = sorted(t["name"] for t in listing["tools"])
        if "convert_time" not in tools:
            raise RuntimeError("installed server did not list convert_time")
        after_list = rss_mib(proc.pid)
        start = time.perf_counter_ns()
        result = await rpc(
            proc,
            3,
            "tools/call",
            {
                "name": "convert_time",
                "arguments": {
                    "source_timezone": "UTC",
                    "time": "12:34",
                    "target_timezone": "UTC",
                },
            },
        )
        call_ms = (time.perf_counter_ns() - start) / 1e6
        if result.get("isError") or len(result.get("content", [])) != 1:
            raise RuntimeError("time conversion failed")
        conversion = json.loads(result["content"][0]["text"])
        for side in ("source", "target"):
            value = datetime.fromisoformat(conversion[side]["datetime"])
            if (
                conversion[side]["timezone"] != "UTC"
                or (value.hour, value.minute) != (12, 34)
                or value.utcoffset().total_seconds() != 0
            ):
                raise RuntimeError("unexpected conversion result")
        return {
            "ready_ms": round(ready, 3),
            "list_ms": round(list_ms, 3),
            "call_ms": round(call_ms, 3),
            "rss_after_list_mib": after_list,
            "rss_after_call_mib": rss_mib(proc.pid),
            "protocol": init["protocolVersion"],
            "tools": tools,
            "conversion_checked": True,
        }
    finally:
        proc.stdin.close()
        try:
            await asyncio.wait_for(proc.wait(), 4)
        except TimeoutError:
            proc.kill()
            await proc.wait()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--python", type=Path, required=True)
    parser.add_argument("--out", type=Path, required=True)
    args = parser.parse_args()
    if args.out.exists():
        parser.error("choose a new cohort file; existing measurements are immutable")
    exe = args.python.resolve(strict=True)
    started = datetime.now(timezone.utc).isoformat()
    with tempfile.TemporaryDirectory() as scratch:
        env = allowed_environment(scratch)
        metadata = json.loads(
            subprocess.check_output(
                [str(exe), "-I", "-B", "-c", METADATA_CODE],
                cwd=scratch,
                env=env,
                timeout=20,
                text=True,
            )
        )

        async def capture():
            await run_once(
                exe, scratch, env
            )  # warm caches; omit this spawn from results
            return [await run_once(exe, scratch, env) for _ in range(5)]

        samples = asyncio.run(capture())
    if len({(s["protocol"], tuple(s["tools"])) for s in samples}) != 1:
        raise RuntimeError("server identity changed across iterations")
    output = {
        "method": "installed-mcp-time-stdio-v1",
        "date_started_utc": started,
        "date_finished_utc": datetime.now(timezone.utc).isoformat(),
        "platform": platform.system(),
        "os_version": platform.version(),
        "target": metadata,
        "requested_protocol": PROTOCOL,
        "probe_sha256_canonical_lf": hashlib.sha256(
            Path(__file__).read_bytes().replace(b"\r\n", b"\n")
        ).hexdigest(),
        "conditions": "One discarded warmup and five serial fresh processes. Direct installed interpreter, warm filesystem cache, no npx/uvx wrapper. No tool concurrency. RSS sums process tree immediately after each validated operation (MiB), not peak, CPU or wall energy.",
        "workload": "initialize; tools/list; convert_time UTC 12:34 to UTC, verifying both timestamps",
        "samples": samples,
        "medians": {key: statistics.median(s[key] for s in samples) for key in METRICS},
    }
    with args.out.open("x", encoding="utf-8", newline="\n") as file:
        file.write(json.dumps(output, indent=2) + "\n")
    print(json.dumps(output["medians"]))


if __name__ == "__main__":
    main()
