"""Decode A/B drive through the admin console's own measurement path (runs INSIDE the engine
container, loopback). canonical_prompt (fixed seed, token-bisected), _run_rung (TTFT + steady TPOT
per token, derived aggregate), served sampling (thinking on), EOS respected (16384 only a bound).
usage: fc_ab_drive.py OUT.json  -- rungs c1 and c4, total prefill 2048 tokens, REPS rungs each."""
import asyncio
import json
import sys

from arbi_serve.admin_console import targets as T
from arbi_serve.admin_console.ab_probe import canonical_prompt, cell_prompt_tokens

TARGET = "http://127.0.0.1:8000"
TOKEN = next(  # tokens file: "<token> admin=true" under comment lines
    ln.split()[0] for ln in open("/cache/arbi-serve/auth/operator-token") if ln.strip() and not ln.startswith("#")
)
REPS, PREFILL, BOUND = 3, 2048, 16384


async def main(out):
    model = await T._resident_model_id(TARGET, TOKEN)

    async def count(text):
        return await T._count_prompt_tokens(TARGET, TOKEN, model, text)

    oai = T._openai_client(TARGET, TOKEN, timeout=10800)
    rows = []
    for conc in (1, 4):
        per = cell_prompt_tokens(PREFILL, conc)
        prompts = [await canonical_prompt(count, i, target_tokens=per) for i in range(conc)]
        await T._run_rung(oai, TARGET, model, prompts, max_tokens=BOUND, cache=False)  # warm rung
        for rep in range(REPS):
            r = await T._run_rung(oai, TARGET, model, prompts, max_tokens=BOUND, cache=False)
            r["rep"] = rep
            rows.append(r)
            keys = ("concurrency", "n_ok", "tpot_ms", "ttft_ms", "tokens", "tps_agg_derived")
            print(json.dumps({k: r.get(k) for k in keys}), flush=True)
    json.dump(rows, open(out, "w"), indent=1, default=str)


asyncio.run(main(sys.argv[1]))
