"""Run the fixed Strata SSD warm batch against a local test server."""

import argparse
import http.client
import json
import signal
import time

from measure import compare, snapshot


PROMPTS = (
    ("copy", "Reply with only the words blue notebook."),
    ("arithmetic", "What is 17 plus 25? Reply with the integer only."),
    ("json", "Return only a JSON object with keys color and count, using blue and 2."),
    ("explain", "In two sentences, explain why a wet towel dries faster in moving air."),
)
MAX_RESPONSE_BYTES = 64 * 1024
DEADLINE_SECONDS = 90


def _deadline(_signum, _frame):
    raise TimeoutError("whole-request deadline")


def request(port, model, prompt):
    payload = json.dumps({
        "model": model,
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0,
        "max_tokens": 64,
        "stream": False,
        "reasoning_effort": "none",
        "chat_template_kwargs": {"enable_thinking": False},
    }).encode()
    connection = http.client.HTTPConnection("127.0.0.1", port, timeout=DEADLINE_SECONDS)
    previous = signal.signal(signal.SIGALRM, _deadline)
    signal.setitimer(signal.ITIMER_REAL, DEADLINE_SECONDS)
    try:
        connection.request("POST", "/v1/chat/completions", body=payload,
                           headers={"Content-Type": "application/json"})
        with connection.getresponse() as response:
            if response.status != 200:
                return {"state": "http_error", "http_status": response.status}
            raw = response.read(MAX_RESPONSE_BYTES + 1)
        if len(raw) > MAX_RESPONSE_BYTES:
            return {"state": "invalid_response"}
        body = json.loads(raw)
        choice, = body["choices"]
        content = choice["message"]["content"]
        finish = choice["finish_reason"]
        tokens = (body.get("usage") or {}).get("completion_tokens")
        if not isinstance(content, str) or not content.strip() or finish not in {"stop", "length"}:
            return {"state": "invalid_response"}
        if tokens is not None and (type(tokens) is not int or not 1 <= tokens <= 64):
            return {"state": "invalid_response"}
        return {"state": "completed" if finish == "stop" else "truncated",
                "completion_tokens": tokens}
    except TimeoutError:
        return {"state": "timeout"}
    except (OSError, http.client.HTTPException, ValueError, KeyError, TypeError, AttributeError):
        return {"state": "invalid_response"}
    finally:
        signal.setitimer(signal.ITIMER_REAL, 0)
        signal.signal(signal.SIGALRM, previous)
        connection.close()


def run_batch(namespace, port, model, *, read_snapshot=snapshot):
    before = read_snapshot(namespace)
    rows = []
    stopped = False
    for case, prompt in PROMPTS:
        if stopped:
            row = {"state": "not_submitted"}
        else:
            started = time.monotonic()
            row = request(port, model, prompt)
            row["elapsed_ms"] = round((time.monotonic() - started) * 1000, 3)
        rows.append({"case": case, **row})
        stopped = row["state"] not in {"completed", "truncated"}
    after = read_snapshot(namespace)
    return {"before": before, "after": after, "interval": compare(before, after), "requests": rows}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("namespace")
    parser.add_argument("port", type=int)
    parser.add_argument("model")
    args = parser.parse_args()
    if not 1 <= args.port <= 65535 or not args.model.strip():
        parser.error("enter the port and model ID of the local test server")
    try:
        result = run_batch(args.namespace, args.port, args.model)
    except (OSError, ValueError, KeyError) as exc:
        parser.exit(1, f"counter read failed: {exc}\n")
    print(json.dumps(result, indent=2))
    return int(any(row["state"] not in {"completed", "truncated"} for row in result["requests"]))


if __name__ == "__main__":
    raise SystemExit(main())
