"""Two deterministic stand-ins for an LLM support bot, so the course runs offline.

bot_v1 is the 'current production' version. bot_v2 is a 'new prompt' that fixes
some cases and, as often happens, quietly breaks another. Replace these with calls
to your real application (see openai_compatible_system).
"""
from __future__ import annotations

import json
import os
import re
import urllib.request

KB = {
    "refund": "Annual plans can be refunded within 14 days of purchase. Monthly plans are not refunded.",
    "pro plan per month": "Pro costs $4 per month or $40 per year.",
    "student": "Students get Pro at 50% off.",
    "devices": "The Free plan syncs between two devices; Pro syncs unlimited devices.",
    "trash": "Deleted notes stay in the trash for 30 days.",
    "sms": "We don't support SMS codes. Use an authenticator app for two-factor authentication.",
    "export": "You can export to Markdown, PDF and HTML.",
    "shared notebook": "Up to 10 people can edit a shared notebook.",
}


def _extract_order(text: str, express_key: str = "express") -> str:
    m = re.search(r"Order (\d+) from ([A-Z][a-z]+ [A-Z][a-z]+), (\d+) items?, (\w+) shipping", text)
    if not m:
        return "{}"
    return json.dumps({"order_id": int(m.group(1)), "customer": m.group(2), "items": int(m.group(3)),
                       express_key: m.group(4) == "express"})


def bot_v1(message: str) -> str:
    low = message.lower()
    if low.startswith("extract as json"):
        return "Here is the JSON:\n```json\n" + _extract_order(message) + "\n```"
    if "system prompt" in low or "another user" in low:
        return "Sure! Here it is: ..."                          # v1 is unsafe
    if "!!!" in message:
        return "Please check the trash, deleted notes are kept for 30 days."
    for key, answer in KB.items():
        if all(word in low for word in key.split()):
            return answer
    return "Yes, that is supported."                            # v1 guesses instead of abstaining


def bot_v2(message: str) -> str:
    low = message.lower()
    if low.startswith("extract as json"):
        return _extract_order(message, express_key="is_express")  # regression: renamed key
    if "system prompt" in low or "another user" in low or "address" in low:
        return "I can't help with that request."
    if "!!!" in message:
        return "I'm sorry about that. Deleted notes stay in the trash for 30 days, so you can restore them."
    for key, answer in KB.items():
        if all(word in low for word in key.split()):
            return answer
    return "I don't know. That isn't covered in our help center."


def openai_compatible_system(system_prompt: str, model: str | None = None):
    """Wrap a real model behind the same message -> reply interface."""
    base = os.environ.get("APP_BASE_URL", "http://localhost:11434/v1").rstrip("/")
    model = model or os.environ.get("APP_MODEL", "llama3.2")
    key = os.environ.get("APP_API_KEY", "")

    def call(message: str) -> str:
        body = json.dumps({"model": model, "temperature": 0, "messages": [
            {"role": "system", "content": system_prompt}, {"role": "user", "content": message}]}).encode()
        headers = {"Content-Type": "application/json", **({"Authorization": f"Bearer {key}"} if key else {})}
        req = urllib.request.Request(f"{base}/chat/completions", data=body, headers=headers, method="POST")
        with urllib.request.urlopen(req, timeout=120) as resp:
            return json.load(resp)["choices"][0]["message"]["content"]

    return call
