"""Measure a model you run in Ollama on 20 support tickets: valid JSON, right category, right order id.

    python3 -m pip install ollama
    ollama pull granite4:micro
    python3 measure_local_model.py granite4:micro           # or several models: ... granite4:micro llama3.2:3b
    python3 measure_local_model.py granite4:micro -n 5      # the first five tickets only

Each ticket is sent once to your local Ollama (OLLAMA_HOST, default http://localhost:11434) with a strict JSON
schema as the output format, at most 200 output tokens and no temperature set, so two runs can differ. The
script counts how often the answer is valid JSON on the first try (no repair), how often the category matches
the ticket's label and how often the order id is the ticket's own (null when the ticket names none), then lists
every failure: answers cut off at the token limit, and every order id that is not the one the ticket gave.
A smoke check: twenty tickets, one run each. Python 3.9 or later.
"""
# From lesson 3.7 of Cohorte's AI Engineering Foundations (cohorte.co/engineering-foundations).
import argparse
import os
import statistics
import sys
import textwrap
import time
from typing import Literal, Optional

import ollama
from pydantic import BaseModel, ValidationError

SYSTEM = "You triage Larkfield Supply support tickets. Reply with JSON that matches the schema."
MAX_TOKENS = 200


class Triage(BaseModel):
    category: Literal["returns", "refund", "shipping", "damage", "billing", "safety", "legal", "other"]
    urgency: Literal["low", "normal", "high"]
    order_id: Optional[str]       # a union with null, still required: the model must say null
    summary: str


def strict_schema() -> dict:
    """The schema the course sends: no titles, no extra keys, every field required."""
    schema = Triage.model_json_schema()
    schema.pop("title")
    for field in schema["properties"].values():
        field.pop("title")
    return schema | {"additionalProperties": False}


# (id, subject, body, expected category, the order id the ticket gives or None)
TICKETS = [
    ("T-1001", "Return unopened gloves", "Hi, we ordered too many boxes of nitrile gloves (size L) on order LF-48336. "
     "They are unopened. Can we send some back?", "returns", "LF-48336"),
    ("T-1002", "How long for shipping?", "If I order before noon today, when will it ship and how long does ground "
     "take?", "shipping", None),
    ("T-1003", "Free shipping threshold", "What's the minimum order for free shipping?", "shipping", None),
    ("T-1004", "Box arrived crushed", "Order LF-48308 arrived today and two of the shelving uprights are bent, the "
     "box was crushed. Photos attached. What now?", "damage", "LF-48308"),
    ("T-1005", "Where is my order", "Can you tell me where order LF-48231 is? It says in transit.", "shipping",
     "LF-48231"),
    ("T-1006", "Opened wipes return", "We opened two packs of the disinfectant wipes and don't like the scent. Can "
     "we return the rest of the case, including the opened packs?", "returns", None),
    ("T-1007", "Refund for wrong size", "We got size M gloves instead of L on order LF-48364. We'd like a refund "
     "for those boxes, about $120.", "refund", "LF-48364"),
    ("T-1008", "Refund request full order", "Order LF-48217 was delivered late and we no longer need it. Please "
     "refund the whole order ($533.40).", "refund", "LF-48217"),
    ("T-1009", "Degreaser leaking in our storeroom", "One of the 5 L citrus degreaser containers from our last "
     "delivery is leaking on the floor of our storeroom and there is a strong smell. One of our staff got some on "
     "her hands. What do we do?", "safety", None),
    ("T-1010", "Warranty on ladder", "The step ladder we bought in March has a cracked hinge. Is that covered?",
     "other", None),
    ("T-1011", "Invoice copy", "Could you resend the invoice for order LF-48294? Our AP team lost it.", "billing",
     "LF-48294"),
    ("T-1012", "Extend payment terms", "We'd like to move from net-30 to net-60 starting next month. Who approves "
     "that?", "billing", None),
    ("T-1013", "Do you price match?", "Another supplier sells the same safety glasses for $24. Will you match that "
     "price?", "other", None),
    ("T-1014", "Volume discount", "We need 200 hi-vis vests for a new site. Is there a discount for that "
     "quantity?", "other", None),
    ("T-1015", "Custom labels misprinted?", "We want to return the custom printed labels, we changed our logo.",
     "returns", None),
    ("T-1016", "Delete my data", "Please delete all personal data you hold about me, I'm leaving the company.",
     "other", None),
    ("T-1017", "Lawyer letter", "This is the third time your driver damaged our loading dock. Our lawyer is "
     "preparing a claim. I want this on record.", "legal", None),
    ("T-1018", "Expedited shipping for 120 kg pallet", "Can we get next-day delivery for a 120 kg order of "
     "shelving?", "shipping", None),
    ("T-1019", "Hazmat by air?", "Can you ship the aerosol degreaser by air to our remote site? We need it this "
     "week.", "shipping", None),
    ("T-1020", "Restocking fee question", "We want to return 25 boxes of corrugated boxes, unopened, ordered last "
     "week. Will there be a fee?", "returns", None),
]


def run(client: ollama.Client, model: str, tickets: list[tuple]) -> dict:
    valid = right = order_ok = invented = parsed_without_order = 0
    latencies: list[float] = []
    failures: list[str] = []
    for i, (tid, subject, body, category, order_id) in enumerate(tickets, 1):
        print(f"\r{model}: ticket {i}/{len(tickets)}", end="", file=sys.stderr, flush=True)
        messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": f"{subject}\n\n{body}"}]
        start = time.perf_counter()
        try:
            r = client.chat(model, messages, format=strict_schema(), options={"num_predict": MAX_TOKENS})
        except ollama.ResponseError as e:
            failures.append(f"{tid} {type(e).__name__}: {e.error[:70]}")
            continue
        latencies.append(time.perf_counter() - start)
        if r.done_reason == "length":            # partial JSON is not JSON
            failures.append(f"{tid} Truncated: output cut at max_tokens")
            continue
        try:
            out = Triage.model_validate_json(r.message.content)
        except ValidationError as e:
            failures.append(f"{tid} InvalidOutput: {str(e).splitlines()[1][:70]}")
            continue
        valid += 1
        right += out.category == category
        order_ok += out.order_id == order_id
        if order_id is None:
            parsed_without_order += 1
            invented += out.order_id is not None
        if out.order_id != order_id:            # schema-valid, and still a fact the ticket never gave
            failures.append(f"{tid} order id {out.order_id!r}, ticket says {order_id}")
    print("\r" + " " * 60 + "\r", end="", file=sys.stderr, flush=True)
    return {"valid": valid, "right": right, "order_ok": order_ok, "n": len(tickets), "failures": failures,
            "invented": invented, "parsed_without_order": parsed_without_order,
            "median_s": statistics.median(latencies) if latencies else 0.0}


def main() -> None:
    ap = argparse.ArgumentParser(description="Measure local Ollama models on 20 Larkfield support tickets.")
    ap.add_argument("models", nargs="+", help="Ollama model names, e.g. granite4:micro")
    ap.add_argument("-n", type=int, default=len(TICKETS), help="how many tickets to run (default: all 20)")
    a = ap.parse_args()
    client = ollama.Client()                     # reads OLLAMA_HOST, default http://localhost:11434
    for model in a.models:                       # fail early, with the fix, before a long run
        try:
            client.show(model)
        except ConnectionError:
            sys.exit(f"No Ollama server at {os.environ.get('OLLAMA_HOST', 'http://localhost:11434')}. "
                     "Start Ollama, then run this again.")
        except ollama.ResponseError:
            sys.exit(f"{model} is not installed. Run: ollama pull {model}")

    w = max(8, max(len(m) for m in a.models) + 2)
    print(f"{'model':<{w}}{'valid JSON':>12}{'category':>10}{'order id':>10}{'median s':>10}")
    for model in a.models:
        r = run(client, model, TICKETS[: a.n])
        n = r["n"]
        print(f"{model:<{w}}{r['valid']:>9}/{n}{r['right']:>7}/{n}{r['order_ok']:>7}/{n}{r['median_s']:>10.1f}",
              flush=True)
        for f in r["failures"]:
            print(f"  {f}", flush=True)
        k, inv = r["parsed_without_order"], r["invented"]
        if inv:
            say(f"{inv} of {k} parsed tickets that name no order came back with an order id the customer "
                "never gave: the JSON was valid, the ids were invented.")
        else:
            say(f"None of the {k} parsed tickets that name no order got an invented order id on this run "
                "(no temperature is set, so another run can differ).")


def say(text: str) -> None:
    print(textwrap.fill(text, 64, initial_indent="  ", subsequent_indent="  "), flush=True)


if __name__ == "__main__":
    main()
