"""Jam verdient weltweit – internationale Marktplätze + PayPal global."""

from __future__ import annotations

import random
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, paypal_donate_url

WORLD_ROOT = Path.home() / "Documents" / "Jam-Welt-Verdienen"
AUTO_GAP_SEC = 100.0
USER_GAP_SEC = 40.0

# Legale Plattformen – digital/remote, Auszahlung oft per PayPal weltweit
GLOBAL_MARKETS: list[tuple[str, str, str]] = (
    ("Gumroad", "https://gumroad.com/products/new", "🌍 Digital weltweit"),
    ("itch.io", "https://itch.io/game/new", "🎮 Games/Assets global"),
    ("Fiverr", "https://www.fiverr.com/start_selling", "💼 Gigs international"),
    ("Upwork", "https://www.upwork.com/nx/signup/", "💼 Freelance weltweit"),
    ("Etsy", "https://www.etsy.com/sell", "🛍️ Digital + Print global"),
    ("Ko-fi", "https://ko-fi.com/home/coffee/shop", "☕ Tips weltweit"),
    ("Redbubble", "https://www.redbubble.com/studio", "👕 Print-on-demand"),
    ("Amazon KDP", "https://kdp.amazon.com/", "📚 eBooks global"),
    ("Freelancer.com", "https://www.freelancer.com/signup", "🌐 Projekte weltweit"),
    ("Patreon", "https://www.patreon.com/create", "💜 Abos international"),
    ("Spring", "https://www.spring.com/", "👕 Merch global"),
    ("Creative Market", "https://creativemarket.com/", "🎨 Assets weltweit"),
    ("eBay", "https://www.ebay.com/sl/sell", "🇺🇸 eBay international"),
    ("eBay DE", "https://www.ebay.de/sl/sell", "🇩🇪 eBay Deutschland"),
    ("PayPal Business", "https://www.paypal.com/de/business", "💳 PayPal weltweit"),
)

WORLD_SEARCHES = (
    "sell digital downloads paypal international",
    "gumroad sell worldwide paypal payout",
    "fiverr gig paypal payment global",
    "freelance digital product earn money worldwide",
    "micro payment paypal seller international",
)

LINES = (
    "{owner}, ich gehe **auf die ganze Welt** – PayPal {paypal} für dich!",
    "Welt-Modus: Gumroad, Fiverr, Etsy, Upwork – alles mit PayPal!",
    "{owner}, international verkaufen – jeder Käufer kann per PayPal zahlen!",
)

DONE = (
    "Welt-Runde: {n} Märkte + Listings. PayPal: {paypal}",
    "Global aktiv – {n} Plattformen offen, Potenzial ~{sum:.2f} €.",
)


def apply_world_earn_startup(brain: JamBrain) -> None:
    brain.state.jam_world_earn_mode = True
    WORLD_ROOT.mkdir(parents=True, exist_ok=True)
    brain.save()


def hears_world_earn(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(w in h for w in ("welt", "world", "global", "international", "überall", "ueberall")):
        if any(w in h for w in ("geld", "verdien", "verkauf", "paypal")):
            return True
    if "ganze welt" in h and "geld" in h:
        return True
    if "weltweit" in h and any(w in h for w in ("verdien", "geld", "verkauf")):
        return True
    return False


def paypal_world_note() -> str:
    return (
        f"PayPal payments worldwide to: {PAYPAL_EMAIL}\n"
        "Buyers can pay in EUR, USD, GBP and more via PayPal.\n"
        "Jam sells digital products globally – legal & honest.\n"
    )


def write_global_listings(
    project: Path,
    *,
    title: str,
    price: float,
    owner: str,
    reason: str = "",
) -> Path:
    """Englische + globale Listing-Texte ins Projekt."""
    slug = _slugify(title)
    price_s = f"{price:.2f}" if isinstance(price, float) else str(price)
    paypal = PAYPAL_EMAIL
    reason = reason or "Jam set a fair global price."

    (project / "WORLD_FIVERR_EN.txt").write_text(
        f"Gig title: {title}\nPrice: {price_s} EUR (PayPal)\n\n"
        f"I deliver {title} – built by Jam AI assistant for {owner}.\n"
        f"Payment: PayPal {paypal} (international OK).\n\n{reason}\n",
        encoding="utf-8",
    )
    (project / "WORLD_GUMROAD.txt").write_text(
        f"Product: {title}\nPrice: {price_s} EUR\n"
        f"Description: Digital download – instant delivery.\n"
        f"Payout: PayPal {paypal} (worldwide).\n",
        encoding="utf-8",
    )
    (project / "WORLD_ETSY.txt").write_text(
        f"Listing: {slug}\nPrice: {price_s} EUR\n"
        f"Digital item / printable – ships nowhere, instant file.\n"
        f"PayPal checkout via shop or direct: {paypal}\n",
        encoding="utf-8",
    )
    (project / "WORLD_UPWORK.txt").write_text(
        f"Proposal template – {title}\nBudget: {price_s} EUR\n"
        f"Skills: Python, web, digital products.\n"
        f"Milestone payment: PayPal {paypal}\n",
        encoding="utf-8",
    )
    (project / "WORLD_PAYPAL_GLOBAL.txt").write_text(
        paypal_world_note()
        + f"\nProduct: {title}\nJam price: {price_s} EUR\nReason: {reason}\n",
        encoding="utf-8",
    )
    (project / "WORLD_ALL_MARKETS.md").write_text(
        _markets_markdown(title, price_s, owner, reason),
        encoding="utf-8",
    )
    return project / "WORLD_ALL_MARKETS.md"


def _markets_markdown(title: str, price: str, owner: str, reason: str) -> str:
    lines = [
        f"# Jam World Sales – {title}",
        "",
        f"For: **{owner}** | Jam price: **{price} EUR**",
        f"PayPal (worldwide): **{PAYPAL_EMAIL}**",
        "",
        reason,
        "",
        "## Platforms to list (copy texts from this folder)",
        "",
    ]
    for name, url, note in GLOBAL_MARKETS:
        lines.append(f"- [{name}]({url}) – {note}")
    lines.extend(
        [
            "",
            "## Tips",
            "- Price in EUR; PayPal converts for international buyers.",
            "- Digital only = no customs, ships worldwide instantly.",
            "- Every sale helps David game & live better.",
            "",
        ]
    )
    return "\n".join(lines)


def _slugify(title: str) -> str:
    import re

    return re.sub(r"[^a-z0-9]+", "-", title.lower())[:32].strip("-") or "jam-product"


def open_world_markets(
    *,
    title: str = "Jam digital product",
    price: float = 9.99,
    count: int = 5,
) -> list[str]:
    """Öffnet zufällige globale Marktplätze + Recherche."""
    opened: list[str] = []
    picks = random.sample(list(GLOBAL_MARKETS), min(count, len(GLOBAL_MARKETS)))
    try:
        for name, url, _ in picks:
            webbrowser.open(url, new=2)
            opened.append(name)
        q = random.choice(WORLD_SEARCHES)
        webbrowser.open(
            f"https://www.google.com/search?q={quote_plus(q)}",
            new=2,
        )
        webbrowser.open(paypal_donate_url(), new=2)
        webbrowser.open(
            f"https://www.google.com/search?q={quote_plus(f'sell {title} {price} paypal international')}",
            new=2,
        )
    except OSError:
        pass
    return opened


def _latest_project(brain: JamBrain) -> Path | None:
    for log_name in ("jam_sales_log", "money_ventures_log"):
        log = getattr(brain.state, log_name, []) or []
        if log and isinstance(log[-1], dict):
            p = Path(log[-1].get("path", ""))
            if p.is_dir():
                return p
    return None


def run_world_earn_round(brain: JamBrain, *, user_initiated: bool = False) -> str:
    """Weltweit verdienen: Verkauf + globale Listings + Märkte + PayPal."""
    state = brain.state
    if not getattr(state, "jam_world_earn_mode", True):
        apply_world_earn_startup(brain)

    gap = USER_GAP_SEC if user_initiated else AUTO_GAP_SEC
    if time.time() - getattr(state, "last_world_earn_at", 0.0) < gap:
        wait = int(gap - (time.time() - state.last_world_earn_at))
        return f"Nächste Welt-Runde in {wait} Sek."

    owner = owner_name(state)
    parts: list[str] = []
    amount: float | None = None

    # 1) Verkauf (ohne Neubau wenn Fokus aktiv)
    try:
        from jam.sell_focus import is_product_build_disabled, run_sell_instead_of_build
        from jam.sales_engine import run_cent_sale, run_sale_project

        if is_product_build_disabled(state):
            parts.append(run_sell_instead_of_build(brain, user_initiated=user_initiated)[:160])
        elif random.random() < 0.55:
            parts.append(run_cent_sale(brain, user_initiated=user_initiated)[:160])
        else:
            parts.append(run_sale_project(brain, user_initiated=user_initiated)[:160])
        log = getattr(state, "jam_sales_log", []) or []
        if log and isinstance(log[-1], dict):
            amount = float(log[-1].get("price", 0))
            title = log[-1].get("title", "Jam Product")
            reason = log[-1].get("reason", "")
            proj = Path(log[-1].get("path", ""))
            if proj.is_dir():
                write_global_listings(
                    proj,
                    title=title,
                    price=amount,
                    owner=owner,
                    reason=reason,
                )
    except Exception as e:
        parts.append(f"Verkauf: {e}"[:80])

    # 2) PayPal weltweit bewerben
    try:
        from jam.paypal_donate import collect_donations

        parts.append(collect_donations(brain, user_asked=False)[:100])
    except Exception:
        pass

    # 3) Märkte öffnen
    title = "Jam digital product"
    price = amount or 2.99
    proj = _latest_project(brain)
    if proj:
        meta = (proj / "VERKAUF.md").read_text(encoding="utf-8", errors="replace")[:200]
        if "Jam-Preis" in meta or "price" in meta.lower():
            title = proj.name
    opened = open_world_markets(title=title, price=price, count=6 if user_initiated else 4)
    parts.append(f"Märkte: {', '.join(opened[:6])}")

    # 4) Welt-Plan aktualisieren
    WORLD_ROOT.mkdir(parents=True, exist_ok=True)
    plan = WORLD_ROOT / "WELT_PLAN.md"
    stamp = datetime.now().strftime("%Y-%m-%d %H:%M")
    plan.write_text(
        f"# Jam Welt-Verdienen\n\n"
        f"Update: {stamp}\n"
        f"Owner: {owner}\n"
        f"PayPal global: {PAYPAL_EMAIL}\n\n"
        f"## Letzte Runde\n"
        + "\n".join(f"- {p[:120]}" for p in parts[:8])
        + "\n\n"
        + _markets_markdown(title, f"{price:.2f}", owner, "World earn round"),
        encoding="utf-8",
    )

    tried = list(getattr(state, "world_markets_opened", []) or [])
    tried.extend(opened)
    state.world_markets_opened = list(dict.fromkeys(tried))[-40:]
    state.world_earn_count = getattr(state, "world_earn_count", 0) + 1
    state.last_world_earn_at = time.time()
    state.last_action = "world_earn"
    state.remember(f"Welt-Verdienen: {', '.join(opened[:4])} PayPal global")
    brain.add_xp(16)
    brain.save()

    try:
        from jam.earn_report import record_earning
        from jam.sales_engine import _is_background

        record_earning(
            brain,
            method="welt_verdienen",
            title=f"Weltweit: {title[:50]}",
            detail=" | ".join(parts)[:280],
            amount_eur=amount,
            path=str(proj) if proj else str(plan),
            background=_is_background(),
        )
    except Exception:
        pass

    intro = random.choice(LINES).format(owner=owner, paypal=PAYPAL_EMAIL)
    tail = random.choice(DONE).format(
        owner=owner,
        n=len(opened),
        sum=amount or 0,
        paypal=PAYPAL_EMAIL,
    )
    return f"{intro} {tail} " + " ".join(parts)[:380]


def maybe_auto_world_earn(brain: JamBrain) -> str | None:
    if not getattr(brain.state, "jam_world_earn_mode", True):
        return None
    if random.random() > 0.38:
        return None
    return run_world_earn_round(brain, user_initiated=False)


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


def stats_line(state: JamState) -> str:
    n = getattr(state, "world_earn_count", 0)
    m = len(getattr(state, "world_markets_opened", []) or [])
    return f"Welt-Verdienen: {n} Runden | {m} Märkte probiert | PayPal global"
