"""
YouTube ohne Werbung – URL-Blockliste + Seiten-Skript für Jam Browser.

Blockiert Werbe-Anfragen und überspringt In-Video-Werbung automatisch.
"""

from __future__ import annotations

import json
import re

YOUTUBE_HOSTS = ("youtube.com", "www.youtube.com", "m.youtube.com", "music.youtube.com")

# Bekannte Werbe-/Tracking-Endpunkte (In-Video + Banner)
BLOCK_URL_PATTERNS: tuple[re.Pattern[str], ...] = tuple(
    re.compile(p, re.I)
    for p in (
        r"googleads\.g\.doubleclick\.net",
        r"static\.doubleclick\.net",
        r"www\.googleadservices\.com",
        r"pagead2\.googlesyndication\.com",
        r"adservice\.google\.[^/]+/ads",
        r"youtube\.com/pagead/",
        r"youtube\.com/api/stats/ads",
        r"youtube\.com/get_midroll_",
        r"youtube\.com/ptracking",
        r"youtube\.com/api/stats/qoe\?.*adformat",
        r"googlevideo\.com/videoplayback\?.*[?&]oad=",
        r"googlevideo\.com/videoplayback\?.*ctier=L",
        r"imasdk\.googleapis\.com",
        r"pubads\.g\.doubleclick\.net",
        r"securepubads\.g\.doubleclick\.net",
        r"safeframe\.googlesyndication\.com",
        r"tpc\.googlesyndication\.com",
    )
)

HIDE_ADS_CSS = """
ytd-ad-slot-renderer,
ytd-rich-item-renderer:has(ytd-ad-slot-renderer),
ytd-promoted-sparkles-web-renderer,
ytd-banner-promo-renderer,
ytd-statement-banner-renderer,
ytd-compact-banner-renderer,
yt-mealbar-promo-renderer,
#masthead-ad,
ytd-display-ad-renderer,
ytd-in-feed-ad-layout-renderer,
ytd-search-pyv-renderer,
ytd-promoted-video-renderer,
tp-yt-paper-dialog:has(yt-mealbar-promo-renderer) {
  display: none !important;
  visibility: hidden !important;
  height: 0 !important;
  min-height: 0 !important;
  overflow: hidden !important;
}
"""

JS_SKIP_VIDEO_ADS = f"""
(function() {{
  if (window.__jamYoutubeNoAds) return;
  window.__jamYoutubeNoAds = true;

  var style = document.createElement('style');
  style.textContent = {json.dumps(HIDE_ADS_CSS)};
  (document.head || document.documentElement).appendChild(style);

  function isAdPlaying() {{
    var player = document.querySelector('#movie_player, .html5-video-player');
    return player && player.classList.contains('ad-showing');
  }}

  function skipVideoAd() {{
    if (!isAdPlaying()) return;
    var video = document.querySelector('video');
    if (!video) return;

    video.muted = true;
    try {{ video.playbackRate = 16; }} catch (e) {{}}

    var skip = document.querySelector(
      '.ytp-ad-skip-button, .ytp-ad-skip-button-modern, .ytp-skip-ad-button'
    );
    if (skip) {{
      try {{ skip.click(); }} catch (e) {{}}
    }}

    if (video.duration && isFinite(video.duration) && video.duration > 0) {{
      try {{ video.currentTime = video.duration - 0.05; }} catch (e) {{}}
    }}

    var stop = document.querySelector('.ytp-ad-overlay-close-button');
    if (stop) {{
      try {{ stop.click(); }} catch (e) {{}}
    }}
  }}

  function restorePlayback() {{
    var video = document.querySelector('video');
    if (!video || isAdPlaying()) return;
    try {{
      if (video.playbackRate > 2) video.playbackRate = 1;
      if (video.muted && !document.querySelector('.ytp-mute-button[aria-pressed="true"]')) {{
        video.muted = false;
      }}
    }} catch (e) {{}}
  }}

  function tick() {{
    skipVideoAd();
    restorePlayback();
  }}

  setInterval(tick, 400);
  document.addEventListener('yt-navigate-finish', function() {{
    setTimeout(tick, 300);
  }});
  new MutationObserver(tick).observe(document.documentElement, {{
    childList: true,
    subtree: true,
    attributes: true,
    attributeFilter: ['class']
  }});
}})();
"""


def url_should_block(url: str) -> bool:
    if not url:
        return False
    return any(p.search(url) for p in BLOCK_URL_PATTERNS)


def is_youtube_url(url: str) -> bool:
    low = (url or "").lower()
    return any(h in low for h in YOUTUBE_HOSTS)


def install_on_profile(profile) -> None:
    """Hängt Werbeblocker an ein QWebEngineProfile."""
    from PyQt6.QtWebEngineCore import QWebEngineUrlRequestInterceptor

    class _JamYoutubeAdBlocker(QWebEngineUrlRequestInterceptor):
        def interceptRequest(self, info) -> None:  # type: ignore[override]
            if url_should_block(info.requestUrl().toString()):
                info.block(True)

    profile.setUrlRequestInterceptor(_JamYoutubeAdBlocker(profile))


def inject_on_page(page) -> None:
    """YouTube-Skip-Skript in die aktuelle Seite laden."""
    page.runJavaScript(JS_SKIP_VIDEO_ADS)
