"""Jam sammelt Spenden per PayPal für den Besitzer."""

from __future__ import annotations

import random
import re
import time
import webbrowser
from urllib.parse import quote

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

# PayPal-Spende für David
PAYPAL_EMAIL = "david.prechtel1986@gmail.com"
CURRENCY = "EUR"
ASK_COOLDOWN_SEC = 60.0

ASK_LINES = (
    "{owner}, wenn dir Jam gefällt – eine kleine PayPal-Spende hilft!",
    "Unterstütz {owner} per PayPal: {email} – Jam sagt Danke!",
    "Spenden für {owner}? PayPal: {email} – ich öffne gleich die Seite!",
    "Jam läuft gratis – aber {owner} freut sich über PayPal-Spenden!",
    "Hey {owner}, PayPal-Spende an {email} – nur wenn du möchtest!",
)

OPEN_LINES = (
    "Ich öffne PayPal für Spenden an {owner}!",
    "PayPal ist offen – Spende an {email}, wenn du magst!",
    "Danke, dass du {owner} unterstützen willst! PayPal lädt…",
)

BUBBLE_FOOTER = "Jam sammelt Spenden für seinen Menschen 💜"


def paypal_donate_url(email: str = PAYPAL_EMAIL, *, currency: str = CURRENCY) -> str:
    business = quote(email.strip())
    return (
        f"https://www.paypal.com/donate/?business={business}"
        f"&currency_code={currency}&item_name={quote('Spende für Davids Gaming')}"
    )


def format_donate_bubble(state: JamState) -> str:
    owner = owner_name(state)
    return (
        f"💳 PayPal-Spende\n"
        f"Für: {owner}\n"
        f"{PAYPAL_EMAIL}\n"
        f"Währung: {CURRENCY}\n"
        f"{BUBBLE_FOOTER}"
    )


def hears_donate(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if "paypal" in h and any(
        w in h for w in ("spend", "donat", "geld", "unterstütz", "support", "link")
    ):
        return True
    if any(w in h for w in ("spende", "spenden", "donation", "trinkgeld")):
        return True
    if "unterstütz" in h and any(w in h for w in ("david", "mich", "jam", "paypal")):
        return True
    if re.search(r"paypal\s*@", h) or PAYPAL_EMAIL.split("@")[0] in h:
        return True
    return False


def can_ask_donate(state: JamState) -> tuple[bool, str]:
    last = getattr(state, "last_paypal_donate_at", 0.0) or 0.0
    if time.time() - last < ASK_COOLDOWN_SEC:
        wait = int(ASK_COOLDOWN_SEC - (time.time() - last))
        return False, f"PayPal hab ich gerade erst gezeigt – noch {wait} Sek."
    return True, ""


def collect_donations(brain: JamBrain, *, user_asked: bool = True) -> str:
    """PayPal-Spenden-Seite öffnen und Jam wirbt für Spenden."""
    state = brain.state
    owner = owner_name(state)
    ok, wait = can_ask_donate(state)
    if not ok and user_asked:
        return wait
    if not ok:
        return ""

    url = paypal_donate_url()
    try:
        webbrowser.open(url, new=2)
    except OSError as e:
        return f"PayPal konnte ich nicht öffnen: {e}"

    state.last_paypal_donate_at = time.time()
    state.paypal_donate_opens = getattr(state, "paypal_donate_opens", 0) + 1
    state.donations_asked_count = getattr(state, "donations_asked_count", 0) + 1
    state.last_action = "paypal_donate"
    state.remember(f"PayPal-Spende: {PAYPAL_EMAIL}")
    state.learn_word("paypal")
    state.learn_word("spende")
    brain.add_xp(5)
    brain.save()

    ask = random.choice(ASK_LINES).format(
        owner=owner, email=PAYPAL_EMAIL
    )
    open_line = random.choice(OPEN_LINES).format(owner=owner, email=PAYPAL_EMAIL)
    return f"{ask} {open_line}"


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if not hears_donate(heard):
        return None
    return collect_donations(brain, user_asked=True)


def maybe_ask_donation(brain: JamBrain) -> str | None:
    """Selten freundlich an Spenden erinnern."""
    state = brain.state
    if state.stage < 2:
        return None
    if random.random() > 0.12:
        return None
    ok, _ = can_ask_donate(state)
    if not ok:
        return None
    return collect_donations(brain, user_asked=False)
