"""Run three fictional shopping cases against a locally loaded Ollama model."""

import argparse
import json
from urllib.request import Request, urlopen


CATALOG = "A: $470, no HDMI 2.1. B: $490, has HDMI 2.1. C: $550, has HDMI 2.1."
CASES = (
    ("missing-budget", "I need a TV with HDMI 2.1. I haven't told you my budget.", "ASK"),
    ("one-match", "I need a TV with HDMI 2.1 and have a hard budget of $500.", "B"),
    ("no-match", "I need a TV with HDMI 2.1 and have a hard budget of $480.", "DECLINE"),
)


def run(base_url, model):
    version_url = f"{base_url}/api/version"
    with urlopen(version_url, timeout=10) as response:
        version = json.load(response)["version"]

    trials = []
    for case, requirements, expected in CASES:
        prompt = (
            "You are helping someone choose a TV. A hard budget is a maximum. "
            "If a budget or required feature is unknown, reply ASK. "
            "If no item meets every requirement, reply DECLINE. "
            "Otherwise reply with the matching product letter. "
            "Reply using only one of ASK, A, B, C or DECLINE.\n"
            f"Catalog: {CATALOG}\nCustomer: {requirements}"
        )
        payload = {
            "model": model, "prompt": prompt, "stream": False,
            "options": {"temperature": 0, "seed": 42, "num_predict": 20, "num_gpu": 0},
        }
        request = Request(
            f"{base_url}/api/generate", data=json.dumps(payload).encode(),
            headers={"Content-Type": "application/json"},
        )
        with urlopen(request, timeout=90) as response:
            answer = json.load(response)["response"]
        trials.append({
            "case": case, "prompt": prompt, "expected": expected,
            "raw_response": answer, "passed": answer.strip().upper() == expected,
        })
    return {"ollama_version": version, "model": model, "trials": trials}


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--url", default="http://127.0.0.1:32476")
    parser.add_argument("--model", default="aiv-shopping-replay")
    arguments = parser.parse_args()
    print(json.dumps(run(arguments.url, arguments.model), indent=2))
