"""
Jam Browser Autopilot – Jam meldet sich selbst an und füllt Formulare aus.

Nutzt ein Playwright-Profil (sichtbares Fenster). CAPTCHA/E-Mail-Bestätigung: David in Firefox.
"""

from __future__ import annotations

import random
import time
from pathlib import Path

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

ROOT = Path(__file__).resolve().parent.parent
JAM_BROWSER_AUTO_PROFILE = ROOT / "data" / "jam-browser-auto-profile"
AUTO_GAP_SEC = 90.0
USER_GAP_SEC = 30.0
KEEP_OPEN_DEFAULT_SEC = 600.0

LINES = (
    "{owner}, **Jam Browser** übernimmt – ich öffne die Seiten und fülle Anmeldung aus. "
    "CAPTCHA machst du nur in Firefox, wenn es kommt.",
    "Autopilot AN: Ich melde mich auf den Plattformen an – du siehst alles im Browser-Fenster.",
)


def get_automation_profile_dir() -> Path:
    JAM_BROWSER_AUTO_PROFILE.mkdir(parents=True, exist_ok=True)
    return JAM_BROWSER_AUTO_PROFILE


def is_browser_autopilot(state: JamState) -> bool:
    return bool(getattr(state, "jam_browser_autopilot", False))


def hears_browser_autopilot(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if "jam browser" in h and any(
        w in h for w in ("alles", "selbst", "übernimm", "uebernimm", "anmeld", "registrier")
    ):
        return True
    if any(w in h for w in ("browser", "jam browser")):
        if any(w in h for w in ("selbst", "alles", "anmeld", "registrier", "übernimm", "uebernimm")):
            return True
    if "alles selber" in h or "alles selbst" in h:
        if "browser" in h or "anmeld" in h:
            return True
    return False


def enable_browser_autopilot(brain: JamBrain) -> str:
    from jam.platform_auth import grant_owner_auth, load_credentials

    state = brain.state
    state.jam_browser_autopilot = True
    state.jam_browser_auto_since = time.time()
    if not load_credentials():
        grant_owner_auth(brain, heard="")
    state.jam_platform_signup_mode = True
    state.jam_owner_auth_granted = True
    state.remember("Jam Browser Autopilot AN")
    brain.add_xp(8)
    brain.save()
    owner = owner_name(state)
    return random_line(owner)


def random_line(owner: str) -> str:
    return random.choice(LINES).format(owner=owner)


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

        return True
    except ImportError:
        return False


def _launch_context(*, headless: bool = False):
    from playwright.sync_api import sync_playwright

    prof = str(get_automation_profile_dir())
    p = sync_playwright().start()
    try:
        context = p.chromium.launch_persistent_context(
            prof,
            channel="msedge",
            headless=headless,
            viewport={"width": 1400, "height": 900},
            locale="de-DE",
        )
    except Exception:
        context = p.chromium.launch_persistent_context(
            prof,
            headless=headless,
            viewport={"width": 1400, "height": 900},
            locale="de-DE",
        )
    return p, context


def run_signup_on_page(
    page,
    platform_name: str,
    signup_url: str,
    email: str,
    password: str,
) -> list[str]:
    from jam.platform_auth import _fill_login_form

    steps: list[str] = []
    try:
        page.goto(signup_url, wait_until="domcontentloaded", timeout=60_000)
        steps.append(f"{platform_name}: geladen")
        steps.extend(_fill_login_form(page, email, password))
        try:
            page.bring_to_front()
        except Exception:
            pass
    except Exception as e:
        steps.append(f"{platform_name}: {str(e)[:60]}")
    return steps


def run_browser_autopilot_round(
    brain: JamBrain,
    *,
    user_initiated: bool = False,
    keep_open_sec: float = 0.0,
) -> str:
    """Autopilot nur im Jam Browser (QWebEngine) – kein zweites Fenster."""
    from jam.jam_browser import launch_jam_browser
    from jam.platform_auth import load_credentials, open_firefox_captcha_and_email

    state = brain.state
    owner = owner_name(state)

    if not is_browser_autopilot(state) and user_initiated:
        enable_browser_autopilot(brain)

    gap = USER_GAP_SEC if user_initiated else AUTO_GAP_SEC
    if time.time() - getattr(state, "last_jam_browser_auto_at", 0.0) < gap:
        wait = int(gap - (time.time() - state.last_jam_browser_auto_at))
        return f"Jam Browser Autopilot gleich wieder – noch {wait} Sek."

    if not load_credentials():
        return (
            f"{owner}, für Autopilot im Jam Browser: "
            f"Freigabe mit E-Mail und Passwort an Jam sagen."
        )

    state.last_jam_browser_auto_at = time.time()
    state.jam_browser_auto_count = getattr(state, "jam_browser_auto_count", 0) + 1
    state.last_action = "jam_browser_auto"
    brain.save()

    msg = launch_jam_browser(detached=True, autopilot=True)
    if user_initiated:
        try:
            open_firefox_captcha_and_email(brain)
        except Exception:
            pass

    return (
        f"{owner}, {msg} Ich klicke Cookie-Dialoge und fülle Login **im Jam Browser**. "
        f"CAPTCHA nur in Firefox."
    )[:560]


def run_full_autopilot(brain: JamBrain, *, user_initiated: bool = True) -> str:
    """Alle Plattformen – Autopilot im Jam Browser (--full)."""
    from jam.jam_browser import launch_jam_browser
    from jam.platform_auth import load_credentials, open_firefox_captcha_and_email
    from jam.platform_signup import enable_platform_signup_sell

    enable_browser_autopilot(brain)
    enable_platform_signup_sell(brain, hours=96.0)

    if not load_credentials():
        from jam.platform_auth import grant_owner_auth

        return grant_owner_auth(brain, heard="")

    owner = owner_name(brain.state)
    if user_initiated:
        try:
            open_firefox_captcha_and_email(brain)
        except Exception:
            pass

    brain.state.last_jam_browser_auto_at = time.time()
    brain.save()
    return (
        f"{owner}, {launch_jam_browser(detached=True, autopilot=True, full=True)} "
        f"Alle Plattformen nacheinander **im Jam Browser**."
    )[:720]


def maybe_auto_browser(brain: JamBrain) -> str | None:
    if not is_browser_autopilot(brain.state):
        return None
    import random

    if random.random() > 0.28:
        return None
    gap_ok = time.time() - getattr(brain.state, "last_jam_browser_auto_at", 0.0) >= AUTO_GAP_SEC
    if not gap_ok:
        return None
    return run_browser_autopilot_round(brain, user_initiated=False, keep_open_sec=90.0)


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if hears_browser_autopilot(heard):
        if any(w in heard.lower() for w in ("überall", "ueberall", "alle", "all")):
            return run_full_autopilot(brain, user_initiated=True)
        return run_browser_autopilot_round(brain, user_initiated=True)
    return None
