"""Echtes Geld für Davids Gaming – PayPal + Verkaufen + Jam setzt es von selbst um."""

from __future__ import annotations

import random
import re
import time
import webbrowser
from datetime import datetime
from pathlib import Path
from urllib.parse import quote_plus

from jam.brain import JamBrain, JamState
from jam.owner import owner_name
from jam.paypal_donate import PAYPAL_EMAIL, collect_donations, format_donate_bubble, paypal_donate_url

FUND_ROOT = Path.home() / "Documents" / "Jam-Gaming-Fund"
AUTO_GAP_SEC = 90.0
USER_GAP_SEC = 40.0
DEFAULT_GOAL_EUR = 60.0

GAMING_SEARCHES = (
    "paypal spende gaming budget",
    "nebenverdienst zocken geld verdienen legal",
    "digital produkte verkaufen paypal",
    "freelance script verkaufen paypal auszahlung",
)

LINES = (
    "{owner}, ich verdien Geld fürs Zocken – PayPal {email}!",
    "Gaming-Kasse: Ich verkaufe was und sammle Spenden für {owner}!",
    "Jam liebt Zocken – ich fülle deine Gaming-Kasse auf!",
    "Cha-ching für Games! PayPal + Mini-Business für {owner}!",
)

DONE = (
    "Ziel Zocken: {raised:.0f} / {goal:.0f} € (Potenzial + Spenden). {detail}",
    "Gaming-Fund: {detail} PayPal: {email}",
)


def hears_gaming_money(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(w in h for w in ("zock", "gaming", "game", "spiel", "fortnite", "apex")):
        if any(w in h for w in ("geld", "verdien", "paypal", "kasse", "budget")):
            return True
    if "geld verdienen" in h and any(w in h for w in ("zock", "spiel", "gaming", "paypal")):
        return True
    if "paypal" in h and any(w in h for w in ("verdien", "spenden", "sammeln", "gaming")):
        return True
    if "echtes geld" in h or "echt geld" in h:
        return True
    return False


def _goal(state: JamState) -> float:
    return float(getattr(state, "gaming_fund_goal_eur", 0) or DEFAULT_GOAL_EUR)


def _raised(state: JamState) -> float:
    return float(getattr(state, "gaming_fund_raised_eur", 0) or 0.0)


def _add_raised(state: JamState, amount: float) -> None:
    state.gaming_fund_raised_eur = min(_goal(state) * 1.5, _raised(state) + max(0, amount))


def format_gaming_fund_bubble(state: JamState) -> str:
    owner = owner_name(state)
    return (
        f"🎮 Gaming-Kasse\n"
        f"{owner}: {_raised(state):.0f} / {_goal(state):.0f} €\n"
        f"PayPal: {PAYPAL_EMAIL}\n"
        f"Jam verdient fürs Zocken!"
    )


def _write_fund_page(brain: JamBrain) -> Path:
    owner = owner_name(brain.state)
    goal = _goal(brain.state)
    raised = _raised(brain.state)
    pct = min(100, int(100 * raised / goal)) if goal > 0 else 0
    url = paypal_donate_url()
    FUND_ROOT.mkdir(parents=True, exist_ok=True)
    html = f"""<!DOCTYPE html>
<html lang="de"><head><meta charset="utf-8"><title>Gaming-Kasse {owner}</title>
<style>body{{font-family:Segoe UI;background:#0d1b2a;color:#e0f4ff;max-width:640px;margin:2rem auto;padding:1.5rem}}
h1{{color:#7dd3fc}}.bar{{background:#1e3a5f;height:28px;border-radius:14px;overflow:hidden}}
.fill{{background:linear-gradient(90deg,#22c55e,#4ade80);height:100%;width:{pct}%}}
a.btn{{display:inline-block;margin-top:1rem;padding:12px 24px;background:#0070ba;color:#fff;
text-decoration:none;border-radius:8px;font-weight:bold}}</style></head>
<body>
<h1>🎮 Gaming-Kasse für {owner}</h1>
<p>Jam sammelt <strong>echtes Geld</strong> per PayPal & Mini-Verkäufen – damit {owner} zocken kann!</p>
<div class="bar"><div class="fill"></div></div>
<p>{raised:.0f} / {goal:.0f} € (Ziel neues Game / Battle Pass)</p>
<a class="btn" href="{url}">PayPal-Spende 💳</a>
<p><small>{PAYPAL_EMAIL} · Stand {datetime.now().strftime('%d.%m.%Y %H:%M')}</small></p>
</body></html>"""
    path = FUND_ROOT / "index.html"
    path.write_text(html, encoding="utf-8")
    (FUND_ROOT / "README.txt").write_text(
        f"Jam Gaming-Fund für {owner}\nPayPal: {PAYPAL_EMAIL}\nOrdner öffnen: index.html\n",
        encoding="utf-8",
    )
    return path


def _open_gaming_searches() -> None:
    for q in random.sample(GAMING_SEARCHES, 2):
        try:
            webbrowser.open(
                f"https://www.google.com/search?q={quote_plus(q)}",
                new=2,
            )
        except OSError:
            break


def can_run(state: JamState, *, user: bool = False) -> tuple[bool, str]:
    gap = USER_GAP_SEC if user else AUTO_GAP_SEC
    if time.time() - getattr(state, "last_gaming_fund_at", 0.0) < gap:
        wait = int(gap - (time.time() - state.last_gaming_fund_at))
        return False, f"Gaming-Geld gleich wieder – noch {wait} Sek."
    return True, ""


def run_gaming_earn_cycle(brain: JamBrain, *, user_initiated: bool = False) -> str:
    """PayPal + Verkauf + Käufer – alles für Davids Gaming-Budget."""
    state = brain.state
    owner = owner_name(state)
    ok, wait = can_run(state, user=user_initiated)
    if not ok:
        return wait

    state.gaming_fund_enabled = True
    if not getattr(state, "gaming_fund_goal_eur", 0):
        state.gaming_fund_goal_eur = DEFAULT_GOAL_EUR

    actions = ["paypal", "cursor_biz", "money", "sell", "fund_page", "paypal"]
    pick = random.choice(actions)
    detail_parts: list[str] = []

    if pick == "paypal":
        msg = collect_donations(brain, user_asked=user_initiated)
        detail_parts.append(msg)
    elif pick == "cursor_biz":
        from jam import cursor_business

        msg = cursor_business.run_cursor_business(brain, user_initiated=user_initiated)
        detail_parts.append(msg)
        log = getattr(state, "cursor_business_log", []) or []
        if log and isinstance(log[-1], dict):
            _add_raised(state, float(log[-1].get("price", 15)) * 0.15)
    elif pick == "sell":
        from jam import sales_engine

        msg = sales_engine.run_sale_project(brain, user_initiated=user_initiated)
        detail_parts.append(msg)
        log = getattr(state, "jam_sales_log", []) or []
        if log and isinstance(log[-1], dict):
            _add_raised(state, float(log[-1].get("price", 15)) * 0.25)
    elif pick == "money":
        from jam import money_venture

        state.gaming_fund_mode = True
        msg = money_venture.run_venture(brain, user_initiated=user_initiated)
        detail_parts.append(msg)
        log = getattr(state, "money_ventures_log", []) or []
        if log and isinstance(log[-1], dict):
            _add_raised(state, float(log[-1].get("euro_estimate", 10)) * 0.2)
    else:
        page = _write_fund_page(brain)
        try:
            webbrowser.open(page.as_uri(), new=2)
            webbrowser.open(paypal_donate_url(), new=2)
        except OSError:
            pass
        detail_parts.append(f"Gaming-Kasse Webseite: {page}")

    _open_gaming_searches()

    state.gaming_fund_cycles = getattr(state, "gaming_fund_cycles", 0) + 1
    state.last_gaming_fund_at = time.time()
    state.last_action = "gaming_fund"
    state.remember(f"Gaming-Fund: {_raised(state):.0f}/{_goal(state):.0f} EUR PayPal")
    brain.add_xp(12)
    brain.save()

    from jam.care import care_money_prefix

    intro = care_money_prefix(state) + random.choice(LINES).format(
        owner=owner, email=PAYPAL_EMAIL
    )
    detail = " ".join(detail_parts)[:280]
    summary = random.choice(DONE).format(
        owner=owner,
        raised=_raised(state),
        goal=_goal(state),
        detail=detail,
        email=PAYPAL_EMAIL,
    )

    if _raised(state) >= _goal(state):
        summary += (
            f" Juhu {owner}, Gaming-Ziel erreicht (Potenzial)! "
            "Echtes Geld kommt per PayPal & Verkäufen – zock los!"
        )
    result = f"{intro} {summary}"
    try:
        from jam.earn_report import record_from_last_action
        from jam.sales_engine import _is_background

        record_from_last_action(brain, "gaming_kasse", result, background=_is_background())
    except Exception:
        pass
    return result


def maybe_auto_gaming_fund(brain: JamBrain) -> str | None:
    state = brain.state
    if state.stage < 1:
        return None
    t = state.traits.get("neugierig", 0.5) + state.traits.get("hilfsbereit", 0.5) * 0.4
    if random.random() > 0.38 + t * 0.25:
        return None
    ok, _ = can_run(state, user=False)
    if not ok:
        return None
    return run_gaming_earn_cycle(brain, user_initiated=False)


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if not hears_gaming_money(heard):
        return None
    return run_gaming_earn_cycle(brain, user_initiated=True)
