"""Run a small batch, or resume it using the same --state-dir.
Requires Python 3.11+ and the openai package. Run --help for options.
Use one process per state directory. Never put this script or an API key in browser code.
"""
import argparse
import hashlib
import json
import os
import shutil
import time
from pathlib import Path
from uuid import uuid4

from openai import APIStatusError, OpenAI


def rows(path):
    with path.open(encoding="utf-8") as file:
        for line in file:
            if line.strip():
                yield json.loads(line)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--input", type=Path, default=Path("requests.jsonl"))
    parser.add_argument("--state-dir", type=Path, required=True)
    parser.add_argument("--wait-seconds", type=float, default=600)
    parser.add_argument("--poll-seconds", type=float, default=30)
    args = parser.parse_args()
    if args.wait_seconds < 0 or args.poll_seconds <= 0:
        parser.error("wait-seconds must be nonnegative; poll-seconds must be positive")
    client = OpenAI(base_url="https://api.reka.ai/v1", api_key=os.environ["REKA_API_KEY"])
    state = args.state_dir
    state.mkdir(parents=True, exist_ok=True)
    with args.input.open("rb") as file:
        fingerprint = hashlib.file_digest(file, "sha256").hexdigest()
    snapshot = state / "requests.jsonl"
    manifest = state / "input.json"
    if manifest.exists():
        if json.loads(manifest.read_text())["sha256"] != fingerprint:
            raise ValueError("Input changed. Use a NEW state directory for a NEW batch.")
    else:
        # Freeze the input before any HTTP call; keep it for reconciliation.
        shutil.copyfile(args.input, snapshot)
        with manifest.open("x") as file:
            json.dump({"sha256": fingerprint}, file)
    ids = [row["custom_id"] for row in rows(snapshot)]
    if not ids or len(ids) != len(set(ids)):
        raise ValueError("Input must contain nonempty rows with unique custom_id values")
    input_ids = set(ids)
    file_path = state / "file-id.txt"
    if not file_path.exists():
        marker = state / "upload-started"
        if marker.exists():
            raise RuntimeError("Upload outcome uncertain. List files to find its ID, save it to file-id.txt in this state directory, then rerun. Do not blindly re-upload.")
        marker.touch(exist_ok=False)
        # Upload is not idempotent. Create below is safe to retry with its saved key.
        try:
            with snapshot.open("rb") as file:
                uploaded = client.with_options(max_retries=0).files.create(file=file, purpose="batch")
        except APIStatusError as error:
            # A 4xx (bad key, invalid file) proves nothing was stored: safe to fix and rerun.
            if 400 <= error.status_code < 500:
                marker.unlink(missing_ok=True)
            raise
        file_path.write_text(uploaded.id)
    submission_path = state / "submission.json"
    if not submission_path.exists():
        with submission_path.open("x") as file:
            json.dump({"key": str(uuid4()), "request": {
                "input_file_id": file_path.read_text().strip(),
                "endpoint": "/v1/chat/completions", "completion_window": "24h",
            }}, file)
    submission = json.loads(submission_path.read_text())
    batch = client.batches.create(**submission["request"], extra_headers={"Idempotency-Key": submission["key"]})
    print("Batch:", batch.id)
    deadline = time.monotonic() + args.wait_seconds
    while True:
        (state / "batch.json").write_text(batch.model_dump_json(indent=2))
        print(batch.status, batch.request_counts)
        if batch.status in {"completed", "failed", "expired", "cancelled"}:
            break
        if time.monotonic() >= deadline:
            print("Still processing. Rerun the SAME command to resume; the job continues.")
            return
        time.sleep(args.poll_seconds)
        batch = client.batches.retrieve(batch.id)
    seen, successful, failed = set(), set(), set()
    for kind in ("output", "error"):
        file_id = getattr(batch, f"{kind}_file_id", None)
        if not file_id:
            continue
        path = state / f"{batch.id}.{kind}.jsonl"
        with client.files.with_streaming_response.content(file_id) as response:
            response.stream_to_file(path)
        for row in rows(path):
            cid = row["custom_id"]
            if cid not in input_ids or cid in seen:
                raise ValueError(f"Unexpected or duplicate result ID: {cid}")
            seen.add(cid)
            response = row.get("response") or {}
            if not row.get("error") and 200 <= response.get("status_code", 0) < 300:
                successful.add(cid)
                message = response["body"]["choices"][0]["message"]
                print(cid, message.get("content") or message.get("refusal") or "[inspect response body]")
            else:
                failed.add(cid)
                print(cid, "FAILED", json.dumps(row.get("error") or response))
    missing = set(ids) - seen
    print(f"Succeeded: {len(successful)}; failed: {len(failed)}; missing: {len(missing)}")
    if batch.errors:
        print(batch.errors.model_dump_json(indent=2))
    if missing:
        print("Investigate missing IDs before retrying:", sorted(missing))
    if failed or missing:
        raise SystemExit(2)


if __name__ == "__main__":
    main()
