"""Capacity arithmetic plus optional REAL local Ollama inference. No auto downloads."""
import argparse
import concurrent.futures
import json
import time
import urllib.error
import urllib.request


def get_json(path):
    with urllib.request.urlopen("http://127.0.0.1:11434" + path, timeout=10) as r:
        return json.load(r)


def infer(model, prompt):
    payload = json.dumps({"model": model, "prompt": prompt, "stream": True,
                          "options": {"temperature": 0, "num_predict": 24, "num_ctx": 512}}).encode()
    req = urllib.request.Request("http://127.0.0.1:11434/api/generate", data=payload,
                                 headers={"Content-Type": "application/json"})
    start = time.perf_counter()
    first = None
    text = []
    final = None
    with urllib.request.urlopen(req, timeout=120) as r:
        for line in r:
            item = json.loads(line)
            if "error" in item:
                raise RuntimeError(item["error"])
            if item.get("response"):
                if first is None:
                    first = time.perf_counter() - start
                text.append(item["response"])
            if item.get("done"):
                final = item
    if final is None:
        raise RuntimeError("No completed inference response")
    duration = final.get("eval_duration", 0) / 1e9
    return {"model": model, "answer": "".join(text), "wall_s": time.perf_counter()-start,
            "first_visible_token_s": first, "decode_tokens": final.get("eval_count", 0),
            "decode_tokens_per_s": final.get("eval_count", 0)/duration if duration else None,
            "prompt_tokens": final.get("prompt_eval_count"), "prompt_duration_ns": final.get("prompt_eval_duration")}


def lesson1(a):
    ideal = 500_000_000 * 4 / 8
    assert ideal == 250_000_000
    print(json.dumps({"ideal_4bit_weight_bytes": ideal, "not_peak_memory": True}))
    if a.real:
        print(json.dumps({"runtime": get_json("/api/version"), "installed": get_json("/api/tags")}))
        req = urllib.request.Request("http://127.0.0.1:11434/api/show", data=json.dumps({"model": a.model}).encode(),
                                     headers={"Content-Type": "application/json"})
        with urllib.request.urlopen(req, timeout=10) as r:
            info = json.load(r)
        print(json.dumps({"model": a.model, "details": info.get("details"), "template": info.get("template"),
                          "model_info": info.get("model_info"), "license": info.get("license")}))
        print(json.dumps(infer(a.model, "Return one word: hello")))
        print(json.dumps({"resident_runtime_report": get_json("/api/ps"),
                          "peak_memory": "Not measured automatically; record OS process peak working set and accelerator monitor peak separately."}))
    else:
        print("CAPACITY ONLY. Actual model-fit and inference competency pending: rerun --real after setup.")


def lesson2(a):
    if not a.real:
        print("NO INFERENCE RUN. Use --real --model NAME --second-model NAME after explicit model installation.")
        return
    if not a.second_model:
        raise ValueError("Lesson 2 requires --second-model for the sequential two-model comparison")
    report = []
    prompt = "Classify this synthetic status as healthy or failed. Status: backup completed successfully. Return only the label."
    for model in (a.model, a.second_model):
        infer(model, "Warm up: return hello")
        measured = [infer(model, prompt) for _ in range(3)]
        # Two requests maximum; no unbounded load generator.
        with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
            concurrent_results = list(pool.map(lambda _: infer(model, prompt), range(2)))
        report.append({"model": model, "sequential": measured, "concurrency_two": concurrent_results,
                       "runtime_residency": get_json("/api/ps")})
        # Unload before selecting the next model to bound resident model memory.
        req = urllib.request.Request("http://127.0.0.1:11434/api/generate", data=json.dumps(
            {"model": model, "keep_alive": 0}).encode(), headers={"Content-Type": "application/json"})
        with urllib.request.urlopen(req, timeout=120) as r:
            r.read()
    print(json.dumps({"real_model_measurements": report, "quality_scope": "One synthetic classification case only"}, indent=2))


def route(sensitive, local, hosted):
    try:
        return local()
    except (OSError, RuntimeError):
        if sensitive:
            return {"status": "unavailable", "route": "no_egress"}
        return hosted()


def lesson3(a):
    hosted_calls = []
    def hosted():
        hosted_calls.append(1)
        return {"status": "fixture", "route": "hosted_test_double"}
    def broken():
        raise OSError("controlled local failure")
    denied = route(True, broken, hosted)
    assert denied["route"] == "no_egress" and hosted_calls == []
    assert route(False, broken, hosted)["route"] == "hosted_test_double"
    print(json.dumps({"privacy_failure_check": denied, "hosted_fixture_calls": len(hosted_calls)}))
    if a.real:
        print(json.dumps(route(True, lambda: infer(a.model, "Return the word local."), hosted)))
    else:
        print("Router contract tested; real endpoint integration still pending --real.")


if __name__ == "__main__":
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--lesson", choices=["1", "2", "3", "all"], default="all")
    p.add_argument("--real", action="store_true", help="Use existing local runtime; no downloads")
    p.add_argument("--model", default="qwen2.5:0.5b")
    p.add_argument("--second-model")
    a = p.parse_args()
    for n, fn in enumerate((lesson1, lesson2, lesson3), 1):
        if a.lesson in (str(n), "all"):
            fn(a)
