#!/usr/bin/env python3
"""Recompute the Agent Town drill summary from the two result files in this folder.

These are the same calculations used to draw the charts in the post.
"""
import json
from pathlib import Path

HERE = Path(__file__).resolve().parent
log = json.loads((HERE / "5-test-scripts/results/drill-2026-11-01-requests.json").read_text())
rows = [[float(x) for x in line.split()] for line in
        (HERE / "5-test-scripts/results/drill-2026-11-01-server-samples.txt").read_text().splitlines() if line.strip()]

reqs = log["requests"]
flood = [r for r in reqs if r["kind"] == "flood"]
no_key = [r for r in reqs if r["kind"] in ("no key", "fake key")]

print(f"requests                 {len(reqs)}")
print(f"flood requests served    {sum(r['status'] == 200 for r in flood)} of {len(flood)}")
print(f"no or fake key refused   {sum(r['status'] == 401 for r in no_key)} of {len(no_key)}")
print(f"posts accepted           {sum(r['worker'].startswith('key') and r['status'] == 200 for r in reqs)}")
print(f"server errors            {sum(r['status'] == 0 or r['status'] >= 500 for r in reqs)}")
print(f"duration                 {max(r['t'] for r in reqs):.1f} s")

# Column 4 is cumulative CPU time. The rate between samples gives CPU use.
cpu, mem = [], []
for previous, current in zip(rows, rows[1:]):
    cpu.append((current[3] - previous[3]) / (current[0] - previous[0]) / 1e4)
    mem.append(current[2] / 1048576)
print(f"peak CPU                 {max(cpu):.1f}% of one core")
print(f"peak memory              {max(mem):.1f} MB")
