"""Reconcile downloaded chat-completion JSONL records by custom_id."""
import argparse
import json
from pathlib import Path

def read_index(path):
    records = {}
    for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
        if not line.strip():
            continue
        row = json.loads(line)
        key = row.get("custom_id")
        if not isinstance(key, str) or not key or key in records:
            raise ValueError(f"{path}:{number}: invalid or duplicate custom_id")
        records[key] = row
    return records

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("requests", type=Path)
parser.add_argument("results", type=Path)
args = parser.parse_args()
expected = read_index(args.requests)
actual = read_index(args.results)
unknown = actual.keys() - expected.keys()
if unknown:
    raise SystemExit("Unknown IDs: " + ", ".join(sorted(unknown)))
issues = 0
for key in expected:
    row = actual.get(key)
    if row is None:
        print(f"{key}: missing")
        issues += 1
        continue
    response = row.get("response") or {}
    code = response.get("status_code")
    if row.get("error") or type(code) is not int or not 200 <= code < 300:
        print(f"{key}: failed (HTTP {code})")
        issues += 1
        continue
    try:
        answer = response["body"]["choices"][0]["message"]["content"]
    except (KeyError, IndexError, TypeError):
        answer = None
    if not isinstance(answer, str) or not answer.strip():
        print(f"{key}: missing text")
        issues += 1
        continue
    print(f"{key}: {json.dumps(answer, ensure_ascii=False)}")
raise SystemExit(1 if issues else 0)
