"""
Jam Browser nur für YouTube – mit eingebautem Werbeblocker.
"""

from __future__ import annotations

import sys
from pathlib import Path

from jam.jam_browser import PROFILE_DIR
from jam.youtube_no_ads import inject_on_page, install_on_profile, is_youtube_url

ROOT = Path(__file__).resolve().parent.parent
YOUTUBE_URL = "https://www.youtube.com/"


def run_youtube_browser() -> int:
    PROFILE_DIR.mkdir(parents=True, exist_ok=True)

    try:
        from PyQt6.QtCore import QTimer, QUrl
        from PyQt6.QtGui import QAction, QKeySequence
        from PyQt6.QtWidgets import (
            QApplication,
            QHBoxLayout,
            QLineEdit,
            QMainWindow,
            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",
            file=sys.stderr,
        )
        return 1

    class YoutubeNoAdsWindow(QMainWindow):
        def __init__(self) -> None:
            super().__init__()
            self.setWindowTitle("YouTube ohne Werbung – Jam")
            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("YouTube-URL oder Suche…")

            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._view.back),
                ("▶", self._view.forward),
                ("↻", self._view.reload),
                ("▶ YouTube", lambda: self._open(YOUTUBE_URL)),
            ):
                act = QAction(label, self)
                act.triggered.connect(slot)
                tb.addAction(act)

            self._view.urlChanged.connect(lambda url: self._url_bar.setText(url.toString()))
            self._view.loadFinished.connect(self._on_load_finished)

            QAction("Neu laden", self).setShortcut(QKeySequence("F5"))

            self._open(YOUTUBE_URL)

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

        def _navigate_bar(self) -> None:
            raw = self._url_bar.text().strip()
            if not raw:
                return
            if "youtube.com" in raw or raw.startswith(("http://", "https://")):
                self._open(raw)
            else:
                from urllib.parse import quote

                self._open(f"https://www.youtube.com/results?search_query={quote(raw)}")

        def _on_load_finished(self, ok: bool) -> None:
            if not ok:
                return
            url = self._view.url().toString()
            if is_youtube_url(url):
                inject_on_page(self._view.page())
                QTimer.singleShot(1200, lambda: inject_on_page(self._view.page()))

    app = QApplication(sys.argv)
    app.setApplicationName("Jam YouTube")
    win = YoutubeNoAdsWindow()
    win.show()
    return app.exec()
