"""porn00.org — KVS engine extractor.

Detail page wbudowuje stream URLs w JS flashvars block:
  - `video_url: 'https://.../get_file/.../<id>.mp4/?v-acctoken=...'`   (default, 360p)
  - `video_alt_url: 'https://.../get_file/.../<id>_720p.mp4/?v-acctoken=...'`  (alt, 720p)

CDN token (`v-acctoken=...`) jest IP-bound do VPS, mobile direct fetch → 403.
playback.py wraps URL przez stream_proxy z `Referer: <page_url>` — działa.

Get_file → 302 → direct mp4 (jak freshporno). Type='mp4'.
"""
from __future__ import annotations

import logging
import re

from app.extractors._fetch import fetch_tube_html
from app.extractors._models import StreamSource

log = logging.getLogger(__name__)

_VIDEO_URL_RE = re.compile(
    r"""video_url:\s*['"]([^'"]+\.mp4[^'"]*)['"]""", re.IGNORECASE,
)
_VIDEO_ALT_URL_RE = re.compile(
    r"""video_alt_url:\s*['"]([^'"]+\.mp4[^'"]*)['"]""", re.IGNORECASE,
)


def extract(page_url: str, *, timeout: float = 60.0) -> list[StreamSource] | None:
    html = fetch_tube_html(page_url, timeout=timeout)
    result: list[StreamSource] = []

    # Preferujemy alt (720p) przed default (360p).
    # CDN token `v-acctoken` jest IP-bound do VPS. Mobile direct fetch ZAWSZE → 403,
    # więc oznacz force_proxy żeby player od razu używał proxified URL bez prób direct.
    # Bez tego: każdy playback = "mrugnięcie" (direct fail → fallback na proxy).
    proxy_flag = {"force_proxy": True}
    if (m := _VIDEO_ALT_URL_RE.search(html)):
        result.append(StreamSource(link=m.group(1), type="mp4", quality="720p", raw=proxy_flag))
    if (m := _VIDEO_URL_RE.search(html)):
        url = m.group(1)
        if not result or result[0].link != url:
            result.append(StreamSource(link=url, type="mp4", quality="360p", raw=proxy_flag))

    if not result:
        log.info("porn00: no video_url flashvars on %s", page_url)
        return None

    return result
