"""Measure local stdio reads using an isolated synthetic file, and export tool schemas.
Usage: python3 scripts/benchmark-mcp.py /absolute/path/to/tinytasks
No user task data is read or modified.
"""
import hashlib,json,math,os,pathlib,platform,statistics,subprocess,sys,tempfile,time
root=pathlib.Path(__file__).resolve().parents[1]
binary=pathlib.Path(sys.argv[1]).resolve()
samples=100
with tempfile.TemporaryDirectory(prefix="tinytasks-site-benchmark-") as tmp:
    task_file=pathlib.Path(tmp)/"tasks.md"
    task_file.write_text("## Benchmark\n"+"".join(f"- [ ] Synthetic task {i} @id({i})\n" for i in range(1,101)))
    env=dict(os.environ,TINYTASKS_FILE=str(task_file),TINYTASKS_DATA_DIR=tmp,TINYTASKS_NO_LAUNCH="1")
    start=time.perf_counter_ns()
    proc=subprocess.Popen([str(binary),"mcp"],stdin=subprocess.PIPE,stdout=subprocess.PIPE,text=True,env=env)
    seq=0
    def req(method,params):
        global seq
        seq+=1
        proc.stdin.write(json.dumps({"jsonrpc":"2.0","id":seq,"method":method,"params":params})+"\n");proc.stdin.flush()
        response=json.loads(proc.stdout.readline())
        assert "error" not in response,response
        result=response["result"]
        assert not result.get("isError"),result
        return result
    try:
        req("initialize",{"protocolVersion":"2025-06-18","clientInfo":{"name":"tinytasks-site-benchmark","version":"1"}})
        startup=(time.perf_counter_ns()-start)/1e6
        proc.stdin.write(json.dumps({"jsonrpc":"2.0","method":"notifications/initialized"})+"\n");proc.stdin.flush()
        tools=req("tools/list",{})
        (root/"public/mcp-tools.json").write_text(json.dumps({"app_version":"0.4.1","source_commit":"4a63bdef9c12dbe23467a3d91ddf50d571be7dcc",**tools},indent=2)+"\n")
        results=[]
        for name,args in [("list_lists",{}),("list_tasks_page",{"status":"all","limit":100})]:
            params={"name":name,"arguments":args}
            for _ in range(10):req("tools/call",params)
            times=[]
            for _ in range(samples):
                t=time.perf_counter_ns();req("tools/call",params);times.append((time.perf_counter_ns()-t)/1e6)
            results.append({"tool":name,"arguments":args,"median_ms":round(statistics.median(times),3),"p95_ms":round(sorted(times)[math.ceil(.95*len(times))-1],3),"samples":samples})
        result={"app_version":"0.4.1","date":"2026-11-20","platform":platform.system(),"architecture":platform.machine(),"os_version":platform.mac_ver()[0],"task_count":100,"warmups_per_tool":10,"samples_per_tool":samples,"startup_plus_initialize_ms":round(startup,3),"binary_sha256":hashlib.sha256(binary.read_bytes()).hexdigest(),"results":results,"scope":"Single local run; one warm server process, synthetic local file. Includes JSON serialization, stdio round trip and response parsing. Excludes model time, network and cloud sync. Not a cross-product comparison."}
        (root/"public/benchmark.json").write_text(json.dumps(result,indent=2)+"\n")
        print(json.dumps(result,indent=2))
    finally:
        proc.stdin.close()
        try:proc.wait(timeout=5)
        except subprocess.TimeoutExpired:proc.terminate();proc.wait()
