"""Gumroad: Produkt anlegen und Publish klicken."""

from __future__ import annotations

import re
import time
from pathlib import Path

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

PROFILE_DIR = Path(__file__).resolve().parent.parent / "data" / "gumroad-playwright-profile"
NEW_PRODUCT_URL = "https://gumroad.com/products/new"


def _playwright_ok() -> bool:
    try:
        import playwright  # noqa: F401

        return True
    except ImportError:
        return False


def _try_click(page, *labels: str) -> bool:
    for label in labels:
        try:
            page.get_by_role("button", name=re.compile(label, re.I)).first.click(timeout=4000)
            page.wait_for_timeout(1200)
            return True
        except Exception:
            pass
        try:
            page.get_by_text(re.compile(label, re.I)).first.click(timeout=3000)
            page.wait_for_timeout(1200)
            return True
        except Exception:
            pass
    return False


def _try_publish(page) -> list[str]:
    done: list[str] = []
    for _ in range(6):
        for label in (
            "Publish",
            "Publish product",
            "Save and publish",
            "Save & publish",
            "Veröffentlichen",
            "Submit",
            "Go live",
            "Create product",
            "Save changes",
            "Continue",
            "Next",
        ):
            if _try_click(page, label):
                done.append(label)
                page.wait_for_timeout(2000)
    return done


def _maybe_login(page, email: str, password: str) -> str:
    try:
        if page.locator('input[type="password"]').count() == 0:
            return "schon eingeloggt?"
    except Exception:
        return ""
    try:
        from jam.platform_auth import _fill_login_form

        steps = _fill_login_form(page, email, password)
        return ", ".join(steps) if steps else "Login-Versuch"
    except Exception:
        return "Login manuell"


def run_gumroad_publish(brain: JamBrain, *, user_initiated: bool = True) -> str:
    if not _playwright_ok():
        return "Playwright fehlt."

    from jam.auto_publish import _latest_product
    from playwright.sync_api import sync_playwright

    owner = owner_name(brain.state)
    title, price, _path = _latest_product(brain)
    desc = (
        f"{title} – digital von Jam für {owner}.\n"
        f"Schnelle Lieferung. PayPal: {PAYPAL_EMAIL}\n"
        f"Python, Web, Scripts."
    )
    price_s = str(int(price) if price == int(price) else f"{price:.2f}")

    creds = None
    try:
        from jam.platform_auth import load_credentials

        creds = load_credentials()
    except Exception:
        pass

    steps: list[str] = []
    PROFILE_DIR.mkdir(parents=True, exist_ok=True)

    try:
        with sync_playwright() as p:
            try:
                context = p.chromium.launch_persistent_context(
                    str(PROFILE_DIR),
                    channel="msedge",
                    headless=False,
                    viewport={"width": 1280, "height": 900},
                    locale="de-DE",
                )
            except Exception:
                context = p.chromium.launch_persistent_context(
                    str(PROFILE_DIR),
                    headless=False,
                    viewport={"width": 1280, "height": 900},
                )

            page = context.pages[0] if context.pages else context.new_page()
            page.goto(NEW_PRODUCT_URL, wait_until="domcontentloaded", timeout=90_000)
            page.wait_for_timeout(3000)
            steps.append("Produkt-Seite")

            if creds:
                login = _maybe_login(page, creds[0], creds[1])
                if login:
                    steps.append(login)
                page.goto(NEW_PRODUCT_URL, wait_until="domcontentloaded", timeout=60_000)
                page.wait_for_timeout(2000)

            for sel, val in (
                ('input[name*="name" i], input[placeholder*="name" i]', title[:100]),
                ('input[name*="title" i]', title[:100]),
                ('input[name*="price" i], input[type="number"]', price_s),
            ):
                try:
                    loc = page.locator(sel).first
                    if loc.is_visible(timeout=1500):
                        loc.fill(val, timeout=5000)
                        steps.append("Feld")
                        break
                except Exception:
                    continue

            try:
                ta = page.locator("textarea").first
                if ta.is_visible(timeout=2000):
                    ta.fill(desc[:5000], timeout=8000)
                    steps.append("Beschreibung")
            except Exception:
                pass

            pub = _try_publish(page)
            steps.extend(pub[:5] or ["Publish-Versuch"])

            try:
                shot = Path(__file__).resolve().parent.parent / "data" / "gumroad-last-screen.png"
                page.screenshot(path=str(shot), full_page=False)
            except Exception:
                pass

            try:
                if user_initiated:
                    page.bring_to_front()
            except Exception:
                pass
            page.wait_for_timeout(8000)

        brain.state.gumroad_publish_count = getattr(brain.state, "gumroad_publish_count", 0) + 1
        brain.save()
        return f"{title} {price_s}EUR – {', '.join(steps)}"[:280]

    except Exception as e:
        return f"Gumroad: {e}"[:200]
