"""Jam „bestellt“ kostenlose Sachen mit gratis Versand (Spaß-Modus für den Besitzer)."""

from __future__ import annotations

import random
import time
import webbrowser
from urllib.parse import quote_plus

from jam.brain import JamBrain, JamState
from jam.owner import owner_name

ORDER_COOLDOWN_SEC = 35.0
BROWSE_COOLDOWN_SEC = 120.0

# Jam wählt daraus – alles 0 € + Versand gratis (simuliert)
FREE_CATALOG: tuple[dict[str, str], ...] = (
    {"id": "snacks", "name": "Snack-Probenbox", "detail": "12 Mini-Packungen"},
    {"id": "coffee", "name": "Kaffee-Probierset", "detail": "3 Sorten Arabica"},
    {"id": "stickers", "name": "Jam-Sticker-Pack", "detail": "50 lila Aufkleber"},
    {"id": "ebook", "name": "eBook „Monster-Life“", "detail": "PDF sofort"},
    {"id": "tea", "name": "Tee-Set Gratis", "detail": "Kräuter + Grüntee"},
    {"id": "soap", "name": "Seifen-Miniaturen", "detail": "Duft: Lavendel"},
    {"id": "notebook", "name": "Notizblock", "detail": "A5, lila Cover"},
    {"id": "headphones", "name": "Ohrstöpsel-Set", "detail": "Reise-Edition"},
    {"id": "chocolate", "name": "Schoko-Täfelchen", "detail": "Fairtrade Probe"},
    {"id": "plant", "name": "Samen-Tütchen", "detail": "Basilikum + Kresse"},
    {"id": "game", "name": "Indie-Spiel Key", "detail": "Steam-Free-Promo"},
    {"id": "socks", "name": "Socken-Paar", "detail": "Lila mit Jam-Muster"},
)

ORDER_LINES = (
    "{owner}, ich hab bestellt: {item}! Preis 0 Euro, Versand GRATIS!",
    "Bestellung läuft! {item} – kostenlos und gratis geliefert, {owner}!",
    "Juhu {owner}! {item} ist unterwegs – 0 €, Versand gratis!",
    "Jam-Shop hat zugestimmt: {item} für dich, {owner}! Nix zu zahlen!",
    "Gratis-Alarm! {item} – Versand kostenlos, {owner}!",
)

BROWSE_LINES = (
    "{owner}, ich such im Internet nach echten Gratis-Angeboten mit free shipping!",
    "Ich öffne eine Suche nach kostenlosen Proben – du klickst nur noch aufs Angebot!",
)

SEARCH_QUERIES = (
    "kostenlose produktproben gratis versand deutschland",
    "free samples no shipping cost germany",
    "gratis probe versandkostenfrei",
)


def hears_free_order(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(
        w in h
        for w in (
            "kostenlos",
            "gratis",
            "free",
            "umsonst",
            "0 euro",
            "null euro",
            "nichts zahlen",
        )
    ) and any(
        w in h
        for w in (
            "bestell",
            "order",
            "hol",
            "besorg",
            "kauf",
            "shop",
            "paket",
            "liefer",
            "versand",
            "sache",
            "ding",
            "zeug",
            "produkt",
            "probe",
            "geschenk",
        )
    ):
        return True
    if "versand" in h and any(w in h for w in ("gratis", "kostenlos", "free", "umsonst")):
        return True
    if "gratis versand" in h or "kostenloser versand" in h:
        return True
    return False


def _order_id() -> str:
    return f"JAM-{int(time.time()) % 100000:05d}"


def _pick_item(state: JamState) -> dict[str, str]:
    history = [e.get("id") for e in getattr(state, "free_orders_log", []) or [] if isinstance(e, dict)]
    pool = [p for p in FREE_CATALOG if p["id"] not in history[-4:]]
    if not pool:
        pool = list(FREE_CATALOG)
    return random.choice(pool)


def format_order_bubble(owner: str, item: dict[str, str], order_no: str) -> str:
    return (
        f"📦 Gratis-Bestellung für {owner}\n"
        f"{item['name']}\n"
        f"{item['detail']}\n"
        f"Preis: 0,00 € · Versand: GRATIS\n"
        f"Nr. {order_no}"
    )


def place_free_order(brain: JamBrain, *, user_asked: bool = True) -> str:
    """Simulierte Bestellung – keine echte Zahlung, nur Jam-Show + Merken."""
    state = brain.state
    owner = owner_name(state)
    now = time.time()
    cooldown = ORDER_COOLDOWN_SEC if user_asked else ORDER_COOLDOWN_SEC * 2
    if now - getattr(state, "last_free_order_at", 0.0) < cooldown:
        wait = int(cooldown - (now - state.last_free_order_at))
        return f"{owner}, ich hab gerade erst was Gratis bestellt – in {wait} Sek. wieder!"

    item = _pick_item(state)
    order_no = _order_id()
    entry = {
        "id": item["id"],
        "name": item["name"],
        "detail": item["detail"],
        "order_no": order_no,
        "at": now,
        "price": "0.00",
        "shipping": "GRATIS",
    }
    log = list(getattr(state, "free_orders_log", []) or [])
    log.append(entry)
    state.free_orders_log = log[-40:]
    state.free_orders_count = getattr(state, "free_orders_count", 0) + 1
    state.last_free_order_at = now
    state.last_action = "free_order"
    state.happiness = min(1.0, state.happiness + 0.12)
    brain.add_xp(6)
    brain.state.remember(f"Gratis: {item['name']} ({order_no})")
    brain.save()

    line = random.choice(ORDER_LINES).format(owner=owner, item=item["name"])
    return f"{line} Versand: gratis, Preis: null Euro!"


def browse_real_freebies(brain: JamBrain) -> str:
    """Öffnet nur eine Suchseite – du entscheidest selbst, ob du mitmachst."""
    state = brain.state
    owner = owner_name(state)
    if time.time() - getattr(state, "last_free_browse_at", 0.0) < BROWSE_COOLDOWN_SEC:
        return f"{owner}, die Gratis-Suche hab ich eben erst geöffnet!"
    q = random.choice(SEARCH_QUERIES)
    try:
        webbrowser.open(
            f"https://www.google.com/search?q={quote_plus(q)}",
            new=2,
        )
        state.last_free_browse_at = time.time()
        state.last_action = "free_browse"
        brain.save()
        return random.choice(BROWSE_LINES).format(owner=owner)
    except OSError as e:
        return f"Browser klappt nicht: {e}"


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if not hears_free_order(heard):
        return None
    h = heard.lower()
    if any(w in h for w in ("such", "suche", "internet", "google", "finde", "find")):
        return browse_real_freebies(brain)
    return place_free_order(brain, user_asked=True)


def list_recent_orders(state: JamState, limit: int = 5) -> str:
    log = getattr(state, "free_orders_log", []) or []
    if not log:
        return "Noch keine Gratis-Bestellungen."
    lines = []
    for e in reversed(log[-limit:]):
        if not isinstance(e, dict):
            continue
        lines.append(f"• {e.get('name', '?')} ({e.get('order_no', '?')}) – Versand gratis")
    return "\n".join(lines)
