#!/usr/bin/env python3
"""Aggiorna f1.json dalla pagina NOW TV (come dazn_replica/refresh_rails.py)."""
from __future__ import annotations

import json
import os
import re
import sys
import time
from pathlib import Path

SCRIPT = Path(__file__).resolve().parent
ROOT = SCRIPT.parent
OUT = SCRIPT / "f1.json"
F1_SERIES = "skysport_cbaf73415c294b07be6c6291c36ce182"
F1_SEASON = "skysport_936ace52e0534d62977fad5686a80364"
F1_PAGE = f"https://www.nowtv.it/streaming/f1/{F1_SERIES}/{F1_SEASON}/seasons/2026"

sys.path.insert(0, str(ROOT))
try:
    from now import fetch_f1_vods, pretty_vod_name, F1_PAGE as PAGE  # type: ignore
except Exception:
    fetch_f1_vods = None  # type: ignore
    PAGE = F1_PAGE


def _pretty(slug: str) -> str:
    s = re.sub(r"-episode-\d+$", "", slug or "")
    s = s.replace("-", " ").strip()
    if not s:
        return slug
    titled = s.title()
    return re.sub(r"\bGp\b", "GP", titled)


def scrape() -> list:
    if fetch_f1_vods:
        return fetch_f1_vods()
    try:
        from curl_cffi import requests as rq
        s = rq.Session(impersonate="chrome99_android")
    except Exception:
        import requests as rq
        s = rq.Session()
    r = s.get(
        F1_PAGE,
        headers={
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0 Safari/537.36",
            "accept": "text/html",
            "accept-language": "it-IT,it;q=0.9",
        },
        timeout=30,
    )
    html = r.text if r.ok else ""
    pairs = list(
        dict.fromkeys(
            re.findall(
                r"/streaming/f1/[^\"\\]+/episodes/([^/\"\\]+)/((?:R_\d+(?:_HD)?))",
                html,
            )
        )
    )
    return [
        {"variant": rid, "slug": slug, "name": _pretty(slug), "id": rid}
        for slug, rid in pairs
    ]


def main() -> int:
    vods = scrape()
    if not vods and OUT.exists():
        print(f"scrape vuoto, mantengo {OUT}")
        return 0
    if not vods:
        print("nessun VOD F1", file=sys.stderr)
        return 1
    events = []
    for ep in vods:
        eid = ep.get("variant") or ep.get("id")
        events.append(
            {
                "id": eid,
                "name": ep.get("name") or eid,
                "slug": ep.get("slug") or "",
                "competition": "Formula 1",
                "label": "NOW F1",
                "source": "nowtv_vod",
                "variant": eid,
            }
        )
    payload = {
        "updated_at": time.strftime("%Y-%m-%dT%H:%M:%S%z") or time.strftime("%Y-%m-%dT%H:%M:%S"),
        "competition": "Formula 1",
        "source": PAGE if "PAGE" in dir() else F1_PAGE,
        "series": F1_SERIES,
        "season": F1_SEASON,
        "count": len(events),
        "events": events,
    }
    OUT.parent.mkdir(parents=True, exist_ok=True)
    OUT.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    # mirror anche f1_vod.json in root (compat now.py)
    mirror = ROOT / "f1_vod.json"
    mirror.write_text(
        json.dumps(
            {
                "source": payload["source"],
                "series": F1_SERIES,
                "season": F1_SEASON,
                "count": len(events),
                "episodes": [
                    {
                        "variant": e["id"],
                        "slug": e.get("slug") or "",
                        "name": e["name"],
                        "id": e["id"],
                    }
                    for e in events
                ],
                "updated_at": payload["updated_at"],
            },
            indent=2,
            ensure_ascii=False,
        )
        + "\n",
        encoding="utf-8",
    )
    print(f"OK {OUT} count={len(events)}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
