"""s3c census load (runs INSIDE the engine container, loopback): served sampling, thinking on,
no max_tokens, phases written to $S3C_OUT/phase so the instrument keys every launch by phase.

usage: s3c_drive.py SERVED_NAME VISION(0|1) OUTDIR
phases: c1 (2 sequential), c4 (4 concurrent), prefill_short (2 conc), prefill_long (~6k + ~20k tokens,
2 conc), vision (2 images, then 2 conc) when VISION=1. flag_truth saved after each phase.
"""
import base64
import io
import json
import os
import random
import sys
import threading
import time
import urllib.request
import zlib
import struct

BASE = "http://127.0.0.1:8000"
name, vision, out = sys.argv[1], sys.argv[2] == "1", sys.argv[3]
S3C = os.environ.get("S3C_OUT", "/cache/s3c")
os.makedirs(out, exist_ok=True)


def phase(p):
    with open(os.path.join(S3C, "phase.tmp"), "w") as f:
        f.write(p)
    os.replace(os.path.join(S3C, "phase.tmp"), os.path.join(S3C, "phase"))
    time.sleep(1.5)  # the instrument polls every 0.5 s
    print(f"{time.strftime('%T')} phase {p}", flush=True)


def flag_truth(tag):
    try:
        d = urllib.request.urlopen(BASE + "/v1/admin/flag_truth", timeout=120).read()
        open(os.path.join(out, f"flag_truth.{tag}.json"), "wb").write(d)
    except Exception as e:  # noqa: BLE001
        print("flag_truth failed", tag, e, flush=True)


def chat(content, tag):
    body = {"model": name, "messages": [{"role": "user", "content": content}], "stream": False}
    req = urllib.request.Request(BASE + "/v1/chat/completions", data=json.dumps(body).encode(),
                                 headers={"Content-Type": "application/json"})
    t0 = time.time()
    try:
        r = json.load(urllib.request.urlopen(req, timeout=10800))
        print(f"  {tag} {time.time() - t0:.0f}s usage={r.get('usage')}", flush=True)
    except Exception as e:  # noqa: BLE001
        print(f"  {tag} FAILED {e!r}"[:400], flush=True)


def conc(items):
    ts = [threading.Thread(target=chat, args=(c, f"{t}")) for c, t in items]
    [t.start() for t in ts]
    [t.join() for t in ts]


rng = random.Random(11)
QS = ["Explain why the sky is blue, briefly.",
      "Write a short Python function that checks whether a number is prime, and explain it.",
      "What are three differences between TCP and UDP?",
      "Give me a two-sentence summary of the causes of the French Revolution.",
      "How many prime numbers are there between 1 and 50? List them.",
      "Describe how a hash map handles collisions."]


def long_doc(n_par):
    return " ".join(
        f"Paragraph {i}: the committee reviewed item {rng.randint(1, 999)} for project {rng.choice('ABCDEFGH')} "
        f"and recorded outcome {rng.randint(1, 99)} with note '{rng.choice(['approved', 'deferred', 'rejected', 'escalated'])}'."
        for i in range(n_par))


def png(w, h):
    rows = []
    for y in range(h):
        r = bytearray([0])
        for x in range(w):
            r += bytes(((x * 255) // w, (y * 255) // h, ((x // 32 + y // 32) % 2) * 255))
        rows.append(bytes(r))
    raw = zlib.compress(b"".join(rows), 6)

    def chunk(t, d):
        return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)

    return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))
            + chunk(b"IDAT", raw) + chunk(b"IEND", b""))


flag_truth("ready")
phase("c1")
for i in range(2):
    chat(QS[i], f"c1.{i}")
flag_truth("c1")
phase("c4")
conc([(QS[2 + i], f"c4.{i}") for i in range(4)])
flag_truth("c4")
phase("prefill_short")
conc([("Reply with one word: what colour is grass?", "ps.0"), ("Name one planet.", "ps.1")])
phase("prefill_long")
conc([(long_doc(260) + "\nWhich items were escalated? Answer briefly.", "pl.6k"),
      (long_doc(900) + "\nSummarise the outcomes for project C in three bullets.", "pl.20k")])
flag_truth("prefill")
if vision:
    phase("vision")
    for i, (w, h) in enumerate(((640, 480), (1280, 960))):
        b64 = base64.b64encode(png(w, h)).decode()
        content = [{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}},
                   {"type": "text", "text": "Describe this image in two sentences."}]
        chat(content, f"vis.{w}x{h}")
    b64 = base64.b64encode(png(800, 600)).decode()
    conc([([{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}},
            {"type": "text", "text": f"What colours dominate this image? ({k})"}], f"vis.c2.{k}") for k in range(2)])
    flag_truth("vision")
phase("done")
time.sleep(12)  # one more instrument dump
print("DRIVE DONE", flush=True)
