"""
Jam veröffentlicht selbst auf Fiverr & Gumroad (Playwright).

David kann nicht klicken – Jam versucht Publish/Submit bis zum Limit.
CAPTCHA oder fehlender Login im Jam Browser Profil kann es trotzdem blockieren.
"""

from __future__ import annotations

import random
import time
from pathlib import Path

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

ROOT = Path(__file__).resolve().parent.parent
PUBLISH_LOG = ROOT / "data" / "jam-publish.log"
AUTO_GAP_SEC = 300.0


def hears_auto_publish(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(
        w in h
        for w in (
            "veröffentlich",
            "veroeffentlich",
            "publish",
            "live schalten",
            "gig online",
        )
    ):
        if any(w in h for w in ("fiverr", "gumroad", "jam", "du", "soll", "mach")):
            return True
    if "kann nicht" in h and any(w in h for w in ("publish", "veröffentlich", "gig", "gumroad")):
        return True
    if "soll jam" in h or "jam machen" in h or "jam soll" in h:
        if any(w in h for w in ("veröffentlich", "publish", "fiverr", "gumroad")):
            return True
    return False


def _log(msg: str) -> None:
    line = f"[{time.strftime('%H:%M:%S')}] {msg}\n"
    try:
        PUBLISH_LOG.parent.mkdir(parents=True, exist_ok=True)
        prev = PUBLISH_LOG.read_text(encoding="utf-8") if PUBLISH_LOG.is_file() else ""
        PUBLISH_LOG.write_text(prev[-8000:] + line, encoding="utf-8")
    except OSError:
        pass


def _latest_product(brain: JamBrain) -> tuple[str, float, str]:
    log = getattr(brain.state, "jam_sales_log", []) or []
    for entry in reversed(log):
        if isinstance(entry, dict) and entry.get("title"):
            return (
                str(entry["title"]),
                float(entry.get("price", 39)),
                str(entry.get("path", "")),
            )
    return "Python Mini-Tool (schnell)", 39.0, ""


def run_auto_publish_all(brain: JamBrain, *, user_initiated: bool = True) -> str:
    """Fiverr + Gumroad: ausfüllen und Publish versuchen."""
    state = brain.state
    gap = 60.0 if user_initiated else AUTO_GAP_SEC
    if time.time() - getattr(state, "last_auto_publish_at", 0.0) < gap:
        wait = int(gap - (time.time() - state.last_auto_publish_at))
        return f"Nächster Publish-Versuch in {wait} Sek."

    owner = owner_name(state)
    state.jam_auto_publish = True
    parts: list[str] = [
        f"{owner}, ich versuche **selbst** auf Fiverr & Gumroad zu veröffentlichen – du musst nichts klicken!"
    ]

    try:
        from jam.fiverr_assist import run_fiverr_assist

        parts.append("Fiverr: " + run_fiverr_assist(brain, mode="full", user_initiated=user_initiated, try_publish=True)[:200])
    except Exception as e:
        parts.append(f"Fiverr: {e}"[:100])

    time.sleep(2.0)

    try:
        from jam.gumroad_assist import run_gumroad_publish

        parts.append("Gumroad: " + run_gumroad_publish(brain, user_initiated=user_initiated)[:200])
    except Exception as e:
        parts.append(f"Gumroad: {e}"[:100])

    state.last_auto_publish_at = time.time()
    state.auto_publish_count = getattr(state, "auto_publish_count", 0) + 1
    state.last_action = "auto_publish"
    state.remember(f"Auto-Publish #{state.auto_publish_count}")
    brain.add_xp(15)
    brain.save()

    _log(" | ".join(parts))
    return (
        " ".join(parts)
        + " Wenn Login/CAPTCHA kommt: einmal anmelden im Jam Browser – "
        f"dann sag nochmal „Jam veröffentlichen“. PayPal: {PAYPAL_EMAIL}"
    )[:720]


def maybe_auto_publish(brain: JamBrain) -> str | None:
    state = brain.state
    if not getattr(state, "jam_owner_rest_mode", False) and not getattr(
        state, "jam_auto_publish", False
    ):
        return None
    if time.time() - getattr(state, "last_auto_publish_at", 0.0) < AUTO_GAP_SEC:
        return None
    if random.random() > 0.4:
        return None
    return run_auto_publish_all(brain, user_initiated=False)


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if hears_auto_publish(heard):
        return run_auto_publish_all(brain, user_initiated=True)
    return None
