"""TechFuelHQ: replay the August 26, 2026 RTX 5080 timings, without running a model.

Put observations.json beside this file, then run: python replay.py
To compare against the separately downloadable August 26 CSV:
    python replay.py --csv llm-server-compare-2026-08-26-lmstudio.csv
To also compare the extract against the original logs and public CSV:
    python replay.py --repo PATH_TO_TECHFUELHQ
"""
import argparse
import csv
import hashlib
import json
import sys
from pathlib import Path
from statistics import median


DATA = Path(__file__).with_name("observations.json")
CAPTURE_DIR = Path("ops/audit/evidence/2026-08-26/lmstudio-vs-ollama")
PUBLIC_CSV = Path("static/data/llm-server-compare-2026-08-26-lmstudio.csv")
MODEL_KEYS = {
    "Llama 3.2 3B": ("llama3.2:3b", "llama-3.2-3b-q4km", "llama-3.2-3b-instruct-q4km", "071529"),
    "Qwen 2.5 14B": ("qwen2.5:14b", "qwen2.5-14b-q4km", "qwen2.5-14b-instruct-q4km", "071723"),
}
LOAD_KEY = {"ollama": "load_s", "lms": "load_wall_s"}


def require(condition, message):
    if not condition:
        raise ValueError(message)


def digest(path):
    # Git checkouts may use LF or CRLF. These hashes identify the LF text.
    return hashlib.sha256(path.read_bytes().replace(b"\r\n", b"\n")).hexdigest()


def extract(repo):
    """Build the public subset from readings; drop unrelated models and machine details."""
    source = repo / CAPTURE_DIR
    csv_rows = list(csv.DictReader((repo / PUBLIC_CSV).read_text(encoding="utf-8").splitlines()))
    checksums = (source / "model-sha256s.txt").read_text(encoding="utf-8").splitlines()
    records = []
    for model, (ollama_id, lms_id, gguf_id, lms_stamp) in MODEL_KEYS.items():
        [model_hash] = [line.split()[0] for line in checksums
                        if line.endswith(f"*{gguf_id}-ollama-blob.gguf")]
        for app, model_id, stamp in [("ollama", ollama_id, "072102"), ("lms", lms_id, lms_stamp)]:
            path = source / f"{app}-normalized-2026-08-26T{stamp}.json"
            capture = json.loads(path.read_text(encoding="utf-8"))
            [row] = [r for r in capture["results"] if r["model"] == model_id]
            [pub] = [r for r in csv_rows if (r["app"], r["model"], r["condition"]) ==
                     (app, model_id, "normalized")]
            fields = ["n_pred", "decode_tps"] + (["ttft_s"] if app == "lms" else [])
            record = {
                "model": model, "model_id": model_id, "gguf_sha256": model_hash,
                "app": app, "app_version": pub["app_version"], "engine": pub["engine"],
                "condition": capture["condition"], "context": int(pub["context"]),
                "gpu": capture["environment"]["gpu"], "driver": capture["environment"]["driver"],
                "file": path.name, "capture_at_utc": capture["captured_at"], "file_sha256_lf": digest(path),
                LOAD_KEY[app]: row[LOAD_KEY[app]], "cold_first_request_s": row["cold_first_request_s"],
                "resident_runs": [{k: run[k] for k in fields} for run in row["runs"]],
            }
            records.append(record)
    return {
        "credit": "TechFuelHQ, August 26, 2026; data: CC BY 4.0",
        "source_dataset": "https://techfuelhq.com/data/llm-server-compare/",
        "source_csv_sha256_lf": digest(repo / PUBLIC_CSV),
        "capture_script_sha256_lf": digest(repo / "ops/bench/lmscmp/lmstudio_vs_ollama.py"),
        "first_reply": "Servers already running; model unloaded; warm filesystem cache. One nonstreaming request per row, capped at 8 output tokens. On Ollama load_s is INSIDE the request; LM Studio load_wall_s is a separately timed CLI load BEFORE the request.",
        "resident": "Five short-prompt, 256-output-token requests per row. Decode seconds = median(n_pred / decode_tps). TTFT, when present, is server-reported, not client streaming latency.",
        "observations": records,
    }


def summarize(record):
    app = record["app"]
    runs = record["resident_runs"]
    require(app in LOAD_KEY and set(LOAD_KEY.values()) & record.keys() == {LOAD_KEY[app]},
            "missing or conflicting load timer")
    require(len(runs) == 5 and all(r["n_pred"] == 256 and r["decode_tps"] > 0 for r in runs),
            "a recorded resident run or its 256 output tokens are missing")
    require(all(("ttft_s" in r) == (app == "lms") for r in runs), "unsupported TTFT coverage")
    request, load = record["cold_first_request_s"], record[LOAD_KEY[app]]
    require(request > 0 and load > 0 and (app != "ollama" or request >= load),
            "invalid request or load timing")
    first = request if app == "ollama" else load + request
    decode = median(r["n_pred"] / r["decode_tps"] for r in runs)
    ttft = f'{median(r["ttft_s"] for r in runs) * 1000:.1f}' if app == "lms" else ""
    return record["model"], record["app_version"], f"{first:.2f}", f"{decode:.2f}", ttft


def verify_csv(data, path):
    require(digest(path) == data["source_csv_sha256_lf"], "wrong public CSV or file changed")
    published = list(csv.DictReader(path.read_text(encoding="utf-8").splitlines()))
    for r in data["observations"]:
        [p] = [p for p in published if (p["app"], p["model"], p["condition"]) ==
               (r["app"], r["model_id"], r["condition"])]
        require(r["context"] == int(p["context"]) and r["app_version"] == p["app_version"]
                and r[LOAD_KEY[r["app"]]] == float(p["load_s"])
                and r["cold_first_request_s"] == float(p["cold_first_request_s"])
                and [run["decode_tps"] for run in r["resident_runs"]] ==
                    [float(v) for v in p["decode_tps_all"].split("|")]
                and summarize(r)[-1] == p["ttft_ms_median"],
                f"{r['model_id']}: readings disagree with the published CSV")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--repo", type=Path, help="also verify against the original repository")
    parser.add_argument("--csv", type=Path, help="also verify against the original public CSV")
    args = parser.parse_args()
    data = json.loads(DATA.read_text(encoding="utf-8"))
    if args.repo:
        require(data == extract(args.repo), "public extract differs from the source files")
        verify_csv(data, args.repo / PUBLIC_CSV)
    if args.csv:
        verify_csv(data, args.csv)
    rows = data["observations"]
    require([(r["model"], r["app"]) for r in rows] ==
            [(model, app) for model in MODEL_KEYS for app in LOAD_KEY], "unexpected cohort")
    for model, ids in MODEL_KEYS.items():
        pair = [r for r in rows if r["model"] == model]
        require([r["model_id"] for r in pair] == list(ids[:2])
                and len({r["gguf_sha256"] for r in pair}) == 1
                and all(r["condition"] == "normalized" and r["context"] == 4096 for r in pair),
                f"{model}: cannot compare mismatched weights, settings, or model IDs")
    output = [summarize(r) for r in rows]
    writer = csv.writer(sys.stdout, lineterminator="\n")
    writer.writerow(("model", "app", "unloaded_to_short_reply_approx_s",
                     "resident_256_token_decode_median_approx_s", "resident_server_ttft_median_ms"))
    writer.writerows(output)


if __name__ == "__main__":
    try:
        main()
    except (KeyError, OSError, TypeError, ValueError) as exc:
        raise SystemExit(f"Cannot replay: {exc}")
