"""Observe SSE content chunks. Chunk timings are NOT per-token ITL/TPOT."""

import argparse
import json
import time
import urllib.error
import urllib.request
from pathlib import Path


def sse_data(lines):
    """SSE records may contain multiple data lines; ignore comments/other fields."""
    parts = []
    for line in lines:
        line = line.decode("utf-8").rstrip("\r\n")
        if not line:
            if parts:
                yield "\n".join(parts)
                parts = []
        elif line.startswith("data:"):
            value = line[5:]
            parts.append(value[1:] if value.startswith(" ") else value)
    if parts:
        yield "\n".join(parts)


def observe(records, started, clock=time.perf_counter, abort_after_chunks=None):
    chunks, stamps, usage, finish, done = [], [], None, None, False
    request_id, cancelled = None, False
    for data in records:
        if data == "[DONE]":
            done = True
            break
        event = json.loads(data)
        request_id = request_id or event.get("id")
        if event.get("error"):
            raise ValueError(f"server SSE error: {event['error']}")
        if event.get("usage"):
            usage = event["usage"]
        for choice in event.get("choices", []):
            if choice.get("index", 0) != 0:
                continue
            content = choice.get("delta", {}).get("content")
            if isinstance(content, str) and content:
                chunks.append(content)
                stamps.append(clock() - started)
            if choice.get("finish_reason"):
                finish = choice["finish_reason"]
        if abort_after_chunks is not None and len(chunks) >= abort_after_chunks:
            cancelled = True
            break
    ended = clock() - started
    return {"protocol_complete": done, "finish_reason": finish, "usage": usage,
            "request_id": request_id, "client_cancelled": cancelled,
            "text": "".join(chunks), "content_chunks": len(chunks),
            "ttfc_seconds": stamps[0] if stamps else None,
            "chunk_gap_seconds": [b-a for a, b in zip(stamps, stamps[1:])],
            "content_times_seconds": stamps, "stream_end_seconds": ended,
            "measurement": "client content chunks, not token ITL/TPOT; end includes protocol tail"}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--url", default="http://127.0.0.1:8000/v1/chat/completions")
    parser.add_argument("--model", default="course-text")
    parser.add_argument("--prompt", default="用三句话解释什么是 KV cache。")
    parser.add_argument("--request", type=Path, help="optional JSON body, e.g. VLM request")
    parser.add_argument("--max-tokens", type=int, default=64)
    parser.add_argument("--timeout", type=float, default=120)
    parser.add_argument("--sse-file", type=Path, help="parse an offline teaching SSE; no timing claims")
    parser.add_argument("--abort-after-chunks", type=int, help="close after N content chunks; does not prove server abort")
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    if args.abort_after_chunks is not None and args.abort_after_chunks < 1:
        parser.error("--abort-after-chunks must be positive")
    body = json.loads(args.request.read_text()) if args.request else {
        "model": args.model, "messages": [{"role": "user", "content": args.prompt}],
        "temperature": 0, "max_tokens": args.max_tokens}
    body.update(stream=True, stream_options={"include_usage": True}, n=1)
    req = urllib.request.Request(args.url, json.dumps(body).encode(),
                                 {"Content-Type": "application/json"})
    started = time.perf_counter()
    exit_code = 0
    try:
        if args.sse_file:
            with args.sse_file.open("rb") as response:
                result = observe(sse_data(response), 0, lambda: 0, args.abort_after_chunks)
            result.update(ttfc_seconds=None, chunk_gap_seconds=[], content_times_seconds=[],
                          stream_end_seconds=None, measurement="offline fixture; no latency measured")
        else:
            with urllib.request.urlopen(req, timeout=args.timeout) as response:
                if "text/event-stream" not in response.headers.get("Content-Type", ""):
                    raise ValueError("expected text/event-stream")
                result = observe(sse_data(response), started, abort_after_chunks=args.abort_after_chunks)
        if result["client_cancelled"]:
            result["server_abort_verified"] = False
            result["note"] = "client intentionally closed; verify server logs and resource metrics separately"
        elif not result["protocol_complete"] or result["finish_reason"] is None:
            result["error"] = "incomplete protocol or missing finish_reason"
            exit_code = 1
    except (OSError, ValueError, urllib.error.URLError) as exc:
        result = {"protocol_complete": False, "error": str(exc),
                  "elapsed_seconds": time.perf_counter() - started}
        exit_code = 1
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
    print(args.output)
    raise SystemExit(exit_code)


if __name__ == "__main__":
    main()
