"""
Plattformen: Anmeldung versuchen + programmierte Produkte verkaufen.

Jam kann keine Konten ohne dich erstellen (E-Mail, CAPTCHA, Passwort).
Jam öffnet Anmelde- und Verkaufsseiten, baut Produkte, kopiert Listing-Texte.
"""

from __future__ import annotations

import random
import time
import webbrowser
from datetime import datetime
from pathlib import Path

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

SIGNUP_ROOT = Path.home() / "Documents" / "Jam-Plattformen"
AUTO_GAP_SEC = 150.0
USER_GAP_SEC = 35.0

# name, signup_url, sell_url, kurzer Hinweis
PLATFORMS: tuple[tuple[str, str, str, str], ...] = (
    (
        "Gumroad",
        "https://gumroad.com/signup",
        "https://gumroad.com/products/new",
        "E-Mail + Passwort → Produkt hochladen → Publish",
    ),
    (
        "itch.io",
        "https://itch.io/register",
        "https://itch.io/game/new",
        "Account → ZIP/HTML aus Jam-Ordner hochladen",
    ),
    (
        "Fiverr",
        "https://www.fiverr.com/join",
        "https://www.fiverr.com/start_selling",
        "Verkäufer werden → Gig aus Zwischenablage → Publish",
    ),
    (
        "Etsy",
        "https://www.etsy.com/sell",
        "https://www.etsy.com/your/shops/me/onboarding",
        "Shop eröffnen → digitales Produkt",
    ),
    (
        "Ko-fi",
        "https://ko-fi.com/account/register",
        "https://ko-fi.com/manage/shop",
        "Account → Shop-Artikel",
    ),
    (
        "Kleinanzeigen",
        "https://www.kleinanzeigen.de/m-einloggen.html",
        "https://www.kleinanzeigen.de/p-anzeige-aufgeben-schritt2.html",
        "Login → Anzeige mit Jam-Text",
    ),
    (
        "Upwork",
        "https://www.upwork.com/nx/signup/",
        "https://www.upwork.com/nx/create-profile/",
        "Freelancer-Profil → Service anbieten",
    ),
    (
        "PayPal Business",
        "https://www.paypal.com/de/business",
        "https://www.paypal.com/myaccount/transfer/homepage",
        "PayPal für Auszahlungen verknüpfen",
    ),
)

LINES = (
    "{owner}, ich versuche **{platform}**: Anmeldung + dein Produkt **{title}** ({price:.2f} €) verkaufen!",
    "Plattform-Runde: {platform} – Anmeldeseite + Verkauf offen. PayPal: {paypal}",
    "{owner}, nächste Plattform **{platform}** – Text in Zwischenablage, du klickst nur noch Publish!",
)


def hears_platform_signup_sell(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(
        w in h
        for w in (
            "plattform",
            "anmelden",
            "anmeldung",
            "registrier",
            "account erstellen",
            "konto erstellen",
            "gumroad",
            "etsy",
            "itch",
        )
    ):
        if any(w in h for w in ("verkauf", "verkaufen", "anmeld", "registrier", "einlogg")):
            return True
    if "programmier" in h and "verkauf" in h:
        return True
    if "auf plattform" in h or "plattformen verkauf" in h:
        return True
    if "versuch" in h and any(w in h for w in ("anmeld", "plattform", "registrier")):
        return True
    return False


def is_signup_sell_mode(state: JamState) -> bool:
    return bool(getattr(state, "jam_platform_signup_mode", False))


def _next_platform_index(state: JamState) -> int:
    idx = int(getattr(state, "jam_platform_signup_index", 0) or 0)
    return idx % len(PLATFORMS)


def _advance_index(state: JamState) -> tuple[str, str, str, str]:
    idx = _next_platform_index(state)
    state.jam_platform_signup_index = idx + 1
    return PLATFORMS[idx]


def _latest_product(brain: JamBrain) -> tuple[Path, str, float] | None:
    log = getattr(brain.state, "jam_sales_log", []) or []
    for entry in reversed(log):
        if not isinstance(entry, dict):
            continue
        path = Path(entry.get("path", ""))
        if path.is_dir():
            return path, str(entry.get("title", "Jam Produkt")), float(entry.get("price", 9.0))
    return None


def _ensure_product(brain: JamBrain, *, user_initiated: bool) -> tuple[Path, str, float]:
    hit = _latest_product(brain)
    if hit:
        return hit
    from jam.sales_engine import run_sale_project

    run_sale_project(brain, user_initiated=user_initiated)
    hit = _latest_product(brain)
    if hit:
        return hit
    root = Path.home() / "Documents" / "Jam-Verkauf"
    return root, "Jam Digital Produkt", 9.0


def _write_guide(
    platform: str,
    signup_url: str,
    sell_url: str,
    hint: str,
    project: Path,
    title: str,
    price: float,
    owner: str,
) -> Path:
    SIGNUP_ROOT.mkdir(parents=True, exist_ok=True)
    path = SIGNUP_ROOT / f"ANMELDEN_{platform.replace(' ', '_')}.txt"
    path.write_text(
        f"Jam Plattform – {platform}\n"
        f"{'=' * 40}\n"
        f"Für: {owner}\n"
        f"Stand: {datetime.now().strftime('%d.%m.%Y %H:%M')}\n\n"
        f"1. ANMELDEN (nur du – Passwort/E-Mail):\n   {signup_url}\n\n"
        f"2. PRODUKT VERKAUFEN:\n   {sell_url}\n\n"
        f"3. Jam-Produkt:\n   Ordner: {project}\n"
        f"   Titel: {title}\n   Preis: {price:.2f} EUR\n"
        f"   PayPal: {PAYPAL_EMAIL}\n\n"
        f"Hinweis: {hint}\n\n"
        f"Texte: FIVERR_GIG.txt, VERKAUF.md, JAM_WERBUNG.txt im Produktordner.\n"
        f"Listing liegt auch in der Zwischenablage (Strg+V).\n",
        encoding="utf-8",
    )
    return path


def run_platform_signup_and_sell(
    brain: JamBrain,
    *,
    user_initiated: bool = False,
    try_fiverr_browser: bool = False,
) -> str:
    """Eine Plattform: Anmeldung öffnen, Produkt sichern, Verkauf + Zwischenablage."""
    state = brain.state
    gap = USER_GAP_SEC if user_initiated else AUTO_GAP_SEC
    if time.time() - getattr(state, "last_platform_signup_at", 0.0) < gap:
        wait = int(gap - (time.time() - state.last_platform_signup_at))
        return f"Nächste Plattform-Runde in {wait} Sek."

    owner = owner_name(state)
    name, signup_url, sell_url, hint = _advance_index(state)
    project, title, price = _ensure_product(brain, user_initiated=user_initiated)

    auth_steps = ""
    try:
        from jam.platform_auth import is_auth_granted, load_credentials, attempt_browser_signup

        if is_auth_granted(state) or load_credentials():
            creds = load_credentials()
            if creds:
                email, password = creds
                _st, steps = attempt_browser_signup(
                    name,
                    signup_url,
                    email,
                    password,
                    keep_open_sec=5.0 if user_initiated else 3.0,
                )
                if steps:
                    auth_steps = f" Auto-Anmeldung: {', '.join(steps)}."
                try:
                    from jam.platform_auth import open_firefox_captcha_and_email

                    open_firefox_captcha_and_email(
                        brain, platform=name, signup_url=signup_url
                    )
                    auth_steps += " Firefox für CAPTCHA+E-Mail offen."
                except Exception:
                    pass
    except Exception:
        pass

    from jam.active_sell import _listing_clipboard_text, paypal_buy_url, push_product_sale
    from jam.auto_ops import clipboard_text

    guide = _write_guide(name, signup_url, sell_url, hint, project, title, price, owner)
    clip_ok = clipboard_text(_listing_clipboard_text(project, title, price))

    opened: list[str] = []
    minimal = getattr(state, "jam_browser_minimal", False) and not user_initiated
    if not minimal:
        try:
            webbrowser.open(signup_url, new=2)
            opened.append(f"Anmeldung {name}")
            time.sleep(0.4)
            webbrowser.open(sell_url, new=2)
            opened.append(f"Verkauf {name}")
            if user_initiated:
                webbrowser.open(paypal_buy_url(price, title), new=2)
                opened.append("PayPal-Kauf")
            shop = project / "index.html"
            if shop.is_file() and user_initiated:
                webbrowser.open(shop.as_uri(), new=2)
                opened.append("Shop")
        except OSError:
            pass

    fiverr_extra = ""
    if try_fiverr_browser and name == "Fiverr":
        try:
            from jam.fiverr_assist import run_fiverr_assist

            fiverr_extra = " " + (run_fiverr_assist(brain, user_initiated=False) or "")[:120]
        except Exception as e:
            fiverr_extra = f" Fiverr-Browser: {e}"[:80]

    if name == "Fiverr":
        try:
            from jam.fiverr_connect import connect_fiverr, push_latest_gig

            state.fiverr_connected = True
            connect_fiverr(brain, user_asked=False)
            gig = push_latest_gig(brain, user_initiated=False)
            if gig:
                fiverr_extra += " " + gig[:100]
        except Exception:
            pass

    push = ""
    if user_initiated or random.random() < 0.45:
        try:
            push = push_product_sale(brain, project, title, price, user_initiated=user_initiated)[:100]
        except Exception:
            pass

    state.jam_platform_signup_mode = True
    state.jam_platform_signup_attempts = getattr(state, "jam_platform_signup_attempts", 0) + 1
    state.last_platform_signup_at = time.time()
    log = list(getattr(state, "jam_platform_signup_log", []) or [])
    log.append(
        {
            "platform": name,
            "title": title,
            "price": price,
            "at": time.time(),
        }
    )
    state.jam_platform_signup_log = log[-40:]
    state.last_action = "platform_signup_sell"
    state.remember(f"Plattform {name}: Anmeldung + Verkauf {title[:40]}")
    brain.add_xp(6)
    brain.save()

    clip_bit = (
        "Text in **Zwischenablage** – einfügen & Veröffentlichen!"
        if clip_ok
        else "Texte im Produktordner."
    )
    return (
        random.choice(LINES).format(
            owner=owner, platform=name, title=title, price=price, paypal=PAYPAL_EMAIL
        )
        + f" Geöffnet: {', '.join(opened)}. {clip_bit} "
        f"Anleitung: {guide.name}. Jam kann nicht für dich auf „Registrieren“ klicken – "
        f"einmal anmelden, dann nur noch Publish. {auth_steps}{push}{fiverr_extra}"
    )[:680]


def run_all_platforms_mission(brain: JamBrain, *, max_platforms: int = 4) -> str:
    """David fragt aktiv: mehrere Plattformen nacheinander."""
    parts: list[str] = []
    n = min(max_platforms, len(PLATFORMS))
    for _ in range(n):
        brain.state.last_platform_signup_at = 0.0
        parts.append(run_platform_signup_and_sell(brain, user_initiated=True)[:160])
        time.sleep(1.2)
    return " | ".join(parts)[:700]


def enable_platform_signup_sell(
    brain: JamBrain,
    *,
    heard: str = "",
    hours: float = 72.0,
    intensity: float = 0.5,
) -> str:
    """Modus: Plattform-Anmeldung + Verkauf programmierter Produkte."""
    from jam.active_sell import apply_active_sell_startup
    from jam.delegate_mode import enable_delegate_mode
    from jam.max_earn import apply_max_earn_startup
    from jam.night_focus import enable_learn_sell_platforms
    from jam.world_earn import apply_world_earn_startup

    enable_learn_sell_platforms(brain, heard=heard, hours=hours, intensity=intensity)
    enable_delegate_mode(brain, remember_grant=True, open_browser=False)
    apply_max_earn_startup(brain)
    apply_world_earn_startup(brain)
    apply_active_sell_startup(brain)

    state = brain.state
    state.jam_platform_signup_mode = True
    state.jam_platform_signup_until = time.time() + hours * 3600
    state.remember("Plattform-Anmeldung + Verkauf AN")
    brain.save()

    owner = owner_name(state)
    first = run_platform_signup_and_sell(brain, user_initiated=True, try_fiverr_browser=True)
    return (
        f"{owner}, ich versuche mich auf **Gumroad, Fiverr, Etsy, itch & Co.** anzumelden "
        f"und deine **programmierten Produkte** zu verkaufen! PayPal: {PAYPAL_EMAIL}. "
        f"Du musst einmal E-Mail/Passwort eingeben – danach nur noch Einfügen+Publish. "
        f"{first}"
    )[:720]


def maybe_auto_signup_sell(brain: JamBrain) -> str | None:
    """Desktop: gelegentlich Plattform-Runde."""
    state = brain.state
    if not is_signup_sell_mode(state):
        return None
    until = float(getattr(state, "jam_platform_signup_until", 0) or 0)
    if until > 0 and time.time() > until:
        state.jam_platform_signup_mode = False
        brain.save()
        return None
    gap = 240.0
    if time.time() - getattr(state, "last_platform_signup_at", 0.0) < gap:
        return None
    if random.random() > 0.42:
        return None
    try_fiverr = random.random() < 0.2
    return run_platform_signup_and_sell(
        brain, user_initiated=False, try_fiverr_browser=try_fiverr
    )


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    from jam.platform_auth import handle_speech as auth_speech

    hit = auth_speech(brain, heard)
    if hit:
        return hit
    if hears_platform_signup_sell(heard):
        if any(w in heard.lower() for w in ("alle", "überall", "ueberall", "jede")):
            enable_platform_signup_sell(brain, heard=heard)
            return run_all_platforms_mission(brain, max_platforms=4)
        return enable_platform_signup_sell(brain, heard=heard)
    return None


def status_line(state: JamState) -> str:
    if not is_signup_sell_mode(state):
        return ""
    n = getattr(state, "jam_platform_signup_attempts", 0)
    idx = _next_platform_index(state)
    nxt = PLATFORMS[idx][0]
    return f"Plattform-Verkauf: AN ({n} Runden, nächste: {nxt})"
