"""Reference expander for Batchrouter sectioned JSONL (format "batchrouter.sectioned.v1").

Turns a sectioned file into standard OpenAI Batch input JSONL, one request per line, for any
OpenAI-compatible batch runner (for example `vllm run-batch`). Works for provider and customer files.

    python expand_sectioned.py input.sectioned.jsonl > input.jsonl

The format:
  line 1    {"type":"header","format":"batchrouter.sectioned.v1","section_count"?,"request_count"?}
  section   {"type":"section","id","model","url","cache_key"?,"prefix":[messages],"body":{shared}}
  request   {"type":"request","section","custom_id","body":{"messages":[...]}}

  - A section line comes before its requests, and its requests follow it directly.
  - Expanded line = {"custom_id", "method":"POST", "url": section.url,
      "body": {"model": section.model,
               "messages": section.prefix + request.body.messages,   (when either is present)
               **section.body, **request.body without messages}}       (request wins, shallow)
  - Bodies never contain "model", "stream" or "stream_options".
  - Everything in one section shares model, endpoint, tools and prefix: compute the prefix once.
    `cache_key` is stable for one customer's identical prefix; it can be used as a vLLM cache_salt.
"""
import json
import sys

FORMAT = "batchrouter.sectioned.v1"
ENDPOINTS = {"/v1/chat/completions"}
FORBIDDEN = {"model", "stream", "stream_options"}


class FormatError(ValueError):
    pass


def expand_request(section, request):
    own = dict(request.get("body") or {})
    messages = own.pop("messages", None)
    prefix = section.get("prefix") or []
    body = {"model": section["model"]}
    if prefix or messages is not None:
        body["messages"] = prefix + (messages or [])
    body.update(section.get("body") or {})
    body.update(own)
    return {"custom_id": request["custom_id"], "method": "POST", "url": section["url"], "body": body}


def expand(lines):
    """Yield standard batch input lines (dicts) from an iterable of sectioned JSONL text lines."""
    header = None
    current = None
    count_in_section = 0
    sections = set()
    custom_ids = set()
    requests = 0
    for number, raw in enumerate(lines, start=1):
        if not raw.strip():
            continue
        record = json.loads(raw)
        kind = record.get("type")
        if header is None:
            if kind != "header" or record.get("format") != FORMAT:
                raise FormatError(f"line {number}: the first line must be a {FORMAT} header")
            header = record
        elif kind == "section":
            if current is not None and count_in_section == 0:
                raise FormatError(f"line {number}: section {current['id']} has no requests")
            if record.get("id") in sections:
                raise FormatError(f"line {number}: section {record.get('id')} is declared twice")
            if record.get("url") not in ENDPOINTS or not record.get("model"):
                raise FormatError(f"line {number}: section needs a model and a supported url")
            if FORBIDDEN & set(record.get("body") or {}) or "messages" in (record.get("body") or {}):
                raise FormatError(f"line {number}: section body may not set model, stream or messages")
            sections.add(record["id"])
            current, count_in_section = record, 0
        elif kind == "request":
            if current is None or record.get("section") != current["id"]:
                raise FormatError(f"line {number}: request is not directly after its section")
            custom_id = record.get("custom_id")
            if not custom_id or len(custom_id) > 128 or custom_id in custom_ids:
                raise FormatError(f"line {number}: custom_id missing, too long or repeated")
            if FORBIDDEN & set(record.get("body") or {}):
                raise FormatError(f"line {number}: request body may not set model or stream")
            custom_ids.add(custom_id)
            count_in_section += 1
            requests += 1
            yield expand_request(current, record)
        else:
            raise FormatError(f"line {number}: unknown record type {kind!r}")
    if header is None:
        raise FormatError("empty file")
    if current is not None and count_in_section == 0:
        raise FormatError(f"section {current['id']} has no requests")
    for field, actual in (("section_count", len(sections)), ("request_count", requests)):
        if field in header and header[field] != actual:
            raise FormatError(f"header {field} is {header[field]}, file has {actual}")


if __name__ == "__main__":
    sys.stdout.reconfigure(encoding="utf-8", newline="\n")
    with open(sys.argv[1], encoding="utf-8") as fh:
        for line in expand(fh):
            sys.stdout.write(json.dumps(line, ensure_ascii=False, separators=(",", ":")) + "\n")
