"""
Jam Browser – eigenes Fenster, Seiten ohne System-Browser-Chaos.

Nutzt Chromium (Qt WebEngine) mit persistentem Profil: Logins bleiben erhalten.
"""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path
from urllib.parse import quote

ROOT = Path(__file__).resolve().parent.parent
PROFILE_DIR = ROOT / "data" / "jam-browser-profile"
HOME_URL = (ROOT / "data" / "jam_browser_home.html").as_uri()

JAM_SEITE_URL = "http://127.0.0.1:8765/"
JAM_DASHBOARD_URL = "http://127.0.0.1:8765/dashboard.html"

QUICK_LINKS: tuple[tuple[str, str], ...] = (
    ("Start", HOME_URL),
    ("Jam-Seite", JAM_SEITE_URL),
    ("Jam-Dashboard", JAM_DASHBOARD_URL),
    ("Gmail", "https://mail.google.com/"),
    ("Fiverr", "https://www.fiverr.com/seller_dashboard"),
    ("Gumroad", "https://gumroad.com/products/new"),
    ("Freelancer", "https://www.freelancer.com/job-search/python/"),
    ("PayPal", "https://www.paypal.com/myaccount/summary"),
    ("Google", "https://www.google.com/"),
    ("YouTube (ohne Werbung)", "https://www.youtube.com/"),
)


def _write_home_page() -> Path:
    rows = "\n".join(
        f'<li><a href="{url}">{name}</a></li>' for name, url in QUICK_LINKS[1:]
    )
    path = ROOT / "data" / "jam_browser_home.html"
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(
        f"""<!DOCTYPE html>
<html lang="de"><head><meta charset="utf-8">
<title>Jam Browser</title>
<style>
body{{font-family:Segoe UI,system-ui;max-width:720px;margin:2rem auto;padding:1.5rem;
background:#0f172a;color:#e2e8f0;line-height:1.5}}
h1{{color:#a78bfa}} a{{color:#38bdf8;font-size:1.05rem}}
ul{{padding-left:1.2rem}} .hint{{color:#94a3b8;font-size:.9rem;margin-top:2rem}}
</style></head><body>
<h1>🌐 Jam Browser</h1>
<p>Hier öffnest du Seiten <strong>ohne Probleme</strong> – ein Profil, Logins bleiben gespeichert.</p>
<p><strong>🤖 Meine Jam-Seite:</strong>
<a href="{JAM_SEITE_URL}">Shop – verkaufen</a> ·
<a href="{JAM_DASHBOARD_URL}">Dashboard – was verkauft?</a></p>
<ul>{rows}</ul>
<p><strong>🤖 Jam übernimmt</strong> (Toolbar): Alles passiert <strong>hier in diesem Fenster</strong> –
Cookie-Klicks, E-Mail/Passwort eintragen (deine Freigabe). CAPTCHA nur in Firefox.</p>
<p><strong>📧 E-Mail:</strong> „Jam, schick E-Mail an wer was braucht“ – Jam schreibt & sendet über Gmail hier.</p>
<p class="hint">start-jam-browser-auto.bat · „Jam Browser, melde dich an“</p>
</body></html>""",
        encoding="utf-8",
    )
    return path


def hears_jam_browser(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if "jam browser" in h:
        return True
    if any(w in h for w in ("browser", "webbrowser", "edge fenster")):
        if any(w in h for w in ("öffn", "oeffn", "start", "eigen", "jam")):
            return True
    if "eigener browser" in h or "eigenen browser" in h:
        return True
    if "seiten öffnen" in h or "seiten oeffnen" in h:
        return True
    return False


def launch_jam_browser(*, detached: bool = True, autopilot: bool = False, full: bool = False) -> str:
    """Startet Jam Browser in separatem Prozess (blockiert nicht)."""
    _write_home_page()
    script = ROOT / "scripts" / "run_jam_browser.py"
    if not script.is_file():
        return "Jam Browser – Start-Skript fehlt."

    py = ROOT / ".venv" / "Scripts" / "pythonw.exe"
    if not py.is_file():
        py = Path(sys.executable)

    cmd = [str(py), str(script)]
    if autopilot:
        cmd.append("--autopilot")
    if full:
        cmd.append("--full")

    try:
        if detached and sys.platform == "win32":
            subprocess.Popen(
                cmd,
                cwd=str(ROOT),
                creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP,
                close_fds=True,
            )
        else:
            subprocess.Popen(cmd, cwd=str(ROOT))
    except OSError as e:
        return f"Jam Browser konnte nicht starten: {e}"

    return (
        "Jam Browser startet – eigenes Fenster mit Adresszeile. "
        "Logins bleiben im Profil gespeichert. Startseite: Gmail, Fiverr, Gumroad."
    )


def open_jam_browser_quick() -> str:
    return launch_jam_browser(detached=True)


def launch_browser_autopilot(*, detached: bool = True, full: bool = False) -> str:
    """Autopilot **im Jam Browser** – ein Fenster, Jam füllt Seiten selbst aus."""
    return launch_jam_browser(detached=detached, autopilot=True, full=full) + (
        " Autopilot läuft **im Jam Browser** (Cookie-Dialoge + Login). "
        "CAPTCHA nur in Firefox, wenn die Seite danach fragt."
    )


def handle_speech(brain, heard: str) -> str | None:
    try:
        from jam.jam_browser_auto import handle_speech as auto_speech

        hit = auto_speech(brain, heard)
        if hit:
            return hit
    except Exception:
        pass
    if hears_jam_browser(heard):
        brain.state.remember("Jam Browser geöffnet")
        brain.save()
        return open_jam_browser_quick()
    return None


def run_browser_app(*, autostart_autopilot: bool = False, autopilot_full: bool = False) -> int:
    """Qt-Hauptfenster – nur wenn PyQt6-WebEngine installiert ist."""
    _write_home_page()

    try:
        from PyQt6.QtCore import QTimer, QUrl, Qt
        from PyQt6.QtGui import QAction, QKeySequence
        from PyQt6.QtWidgets import (
            QApplication,
            QHBoxLayout,
            QLineEdit,
            QMainWindow,
            QMessageBox,
            QPushButton,
            QToolBar,
            QVBoxLayout,
            QWidget,
        )
        from PyQt6.QtWebEngineCore import QWebEnginePage, QWebEngineProfile
        from PyQt6.QtWebEngineWidgets import QWebEngineView
    except ImportError:
        print(
            "PyQt6-WebEngine fehlt. Bitte ausführen:\n"
            "  .venv\\Scripts\\pip install PyQt6-WebEngine\n"
            "Danach: start-jam-browser.bat",
            file=sys.stderr,
        )
        return 1

    PROFILE_DIR.mkdir(parents=True, exist_ok=True)

    from jam.youtube_no_ads import inject_on_page, install_on_profile, is_youtube_url

    class JamBrowserWindow(QMainWindow):
        def __init__(self) -> None:
            super().__init__()
            self.setWindowTitle("Jam Browser")
            self.resize(1280, 860)

            storage = str(PROFILE_DIR / "storage")
            cache = str(PROFILE_DIR / "cache")
            self._profile = QWebEngineProfile("jam-browser", self)
            self._profile.setPersistentStoragePath(storage)
            self._profile.setCachePath(cache)
            self._profile.setPersistentCookiesPolicy(
                QWebEngineProfile.PersistentCookiesPolicy.AllowPersistentCookies
            )

            install_on_profile(self._profile)

            self._view = QWebEngineView(self)
            page = QWebEnginePage(self._profile, self._view)
            self._view.setPage(page)

            self._url_bar = QLineEdit(self)
            self._url_bar.returnPressed.connect(self._navigate_bar)
            self._url_bar.setPlaceholderText("Adresse eingeben oder suchen…")

            go_btn = QPushButton("Los")
            go_btn.clicked.connect(self._navigate_bar)

            central = QWidget()
            layout = QVBoxLayout(central)
            row = QHBoxLayout()
            row.addWidget(self._url_bar, stretch=1)
            row.addWidget(go_btn)
            layout.addLayout(row)
            layout.addWidget(self._view, stretch=1)
            self.setCentralWidget(central)

            tb = QToolBar("Navigation")
            self.addToolBar(tb)
            for label, slot in (
                ("◀", self._back),
                ("▶", self._forward),
                ("↻", self._reload),
                ("🏠", self._home),
            ):
                act = QAction(label, self)
                act.triggered.connect(slot)
                tb.addAction(act)
            tb.addSeparator()
            for name, url in QUICK_LINKS[:7]:
                act = QAction(name, self)
                act.triggered.connect(lambda _=False, u=url: self._open(u))
                tb.addAction(act)
            tb.addSeparator()
            act_auto = QAction("🤖 Jam übernimmt", self)
            act_auto.triggered.connect(self._run_autopilot)
            tb.addAction(act_auto)

            self._view.urlChanged.connect(self._on_url_changed)
            self._view.loadFinished.connect(self._on_load_finished)

            QAction("Zurück", self).setShortcut(QKeySequence("Alt+Left"))
            QAction("Vor", self).setShortcut(QKeySequence("Alt+Right"))
            QAction("Neu laden", self).setShortcut(QKeySequence("F5"))

            from jam.jam_browser_autopilot_runner import JamBrowserAutopilotRunner

            self._autopilot = JamBrowserAutopilotRunner(self)
            self._open(HOME_URL)
            if autostart_autopilot:
                QTimer.singleShot(2500, lambda: self._autopilot.start(full=autopilot_full))

        def _open(self, url: str) -> None:
            if not url.startswith(("http://", "https://", "file:")):
                url = "https://" + url
            self._view.setUrl(QUrl(url))

        def _navigate_bar(self) -> None:
            raw = self._url_bar.text().strip()
            if not raw:
                return
            if " " in raw and "." not in raw.split()[0]:
                q = quote(raw)
                self._open(f"https://www.google.com/search?q={q}")
            elif "." in raw or raw.startswith(("http", "file:")):
                self._open(raw)
            else:
                self._open(f"https://www.google.com/search?q={quote(raw)}")

        def _back(self) -> None:
            self._view.back()

        def _forward(self) -> None:
            self._view.forward()

        def _reload(self) -> None:
            self._view.reload()

        def _home(self) -> None:
            self._open(HOME_URL)

        def _run_autopilot(self) -> None:
            from jam.jam_browser_auto import enable_browser_autopilot
            from jam.brain import JamBrain

            enable_browser_autopilot(JamBrain())
            if not self._autopilot.start(full=False):
                return
            self.statusBar().showMessage(
                "Jam übernimmt **in diesem Fenster** – Anmeldung + Cookie-Klicks.",
                10000,
            )

        def _on_url_changed(self, url: QUrl) -> None:
            self._url_bar.setText(url.toString())

        def _on_load_finished(self, ok: bool) -> None:
            url = self._view.url().toString()
            if ok and is_youtube_url(url):
                inject_on_page(self._view.page())
                QTimer.singleShot(1200, lambda: inject_on_page(self._view.page()))
            if not ok and url not in ("about:blank", HOME_URL):
                self.statusBar().showMessage(
                    "Seite hat Probleme beim Laden – F5 oder andere URL probieren.",
                    8000,
                )
            else:
                self.statusBar().clearMessage()

    app = QApplication(sys.argv)
    app.setApplicationName("Jam Browser")
    win = JamBrowserWindow()
    win.show()
    return app.exec()
