"""
Autopilot läuft **im Jam Browser** (QWebEngine) – keine zweites Playwright-Fenster.
"""

from __future__ import annotations

from jam.jam_browser_page_ops import js_assist_page, parse_js_result


def signup_queue(*, full: bool = False) -> list[tuple[str, str, str]]:
    from jam.platform_signup import PLATFORMS

    items = [p for p in PLATFORMS if p[0] != "PayPal Business"]
    return items if full else items[:3]


class JamBrowserAutopilotRunner:
    """Steuert dasselbe QWebEngineView-Fenster Schritt für Schritt."""

    def __init__(self, window) -> None:
        self._win = window
        self._view = window._view
        self._email = ""
        self._password = ""
        self._queue: list[tuple[str, str, str, str]] = []  # name, url, phase
        self._idx = 0
        self._steps_log: list[str] = []
        self._running = False

    def start(self, *, full: bool = False) -> bool:
        from jam.platform_auth import load_credentials

        creds = load_credentials()
        if not creds:
            self._win.statusBar().showMessage(
                "Zuerst Freigabe: E-Mail + Passwort an Jam sagen.", 12000
            )
            return False
        self._email, self._password = creds
        self._queue = []
        for name, signup, sell, _ in signup_queue(full=full):
            self._queue.append((name, signup, "signup"))
            self._queue.append((name, sell, "sell"))
        self._idx = 0
        self._steps_log = []
        self._running = True
        self._win.statusBar().showMessage("Jam Browser Autopilot – ich übernehme…", 0)
        self._connect_load()
        self._go_next()
        return True

    def _connect_load(self) -> None:
        try:
            self._view.loadFinished.disconnect(self._on_load)
        except Exception:
            pass
        self._view.loadFinished.connect(self._on_load)

    def _on_load(self, ok: bool) -> None:
        if not self._running or not ok:
            return
        from PyQt6.QtCore import QTimer

        QTimer.singleShot(1200, self._assist_on_page)

    def _assist_on_page(self) -> None:
        if not self._running:
            return
        js = js_assist_page(self._email, self._password)

        def _done(raw) -> None:
            steps = parse_js_result(raw)
            if self._idx < len(self._queue):
                name = self._queue[self._idx][0]
                if steps:
                    self._steps_log.append(f"{name}: {','.join(steps)}")
            self._win.statusBar().showMessage(
                f"Jam Browser: {self._steps_log[-1] if self._steps_log else 'Seite bereit'}",
                6000,
            )

        self._view.page().runJavaScript(js, _done)

    def _go_next(self) -> None:
        from PyQt6.QtCore import QTimer, QUrl

        if not self._running or self._idx >= len(self._queue):
            self._running = False
            summary = "; ".join(self._steps_log[-6:]) or "fertig"
            self._win.statusBar().showMessage(
                f"Autopilot durch – {summary}. CAPTCHA ggf. in Firefox.",
                20000,
            )
            try:
                from jam.brain import JamBrain

                b = JamBrain()
                b.state.last_jam_browser_auto_at = __import__("time").time()
                b.state.jam_browser_autopilot = True
                b.state.remember("Jam Browser Autopilot im Browser")
                b.save()
            except Exception:
                pass
            return

        name, url, phase = self._queue[self._idx]
        self._idx += 1
        label = "Anmeldung" if phase == "signup" else "Verkauf"
        self._win.statusBar().showMessage(f"Jam Browser → {name} ({label})…", 0)
        self._view.setUrl(QUrl(url))
        QTimer.singleShot(5500, self._go_next)

    def stop(self) -> None:
        self._running = False
