#!/usr/bin/env python3
"""Scarica le rail CatchUp DAZN via ISP e aggiorna serieA.json / serieB.json / ..."""
from __future__ import annotations

import json
import os
import re
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

import requests

SCRIPT_DIR = Path(__file__).resolve().parent
DAZN_DIR = SCRIPT_DIR.parent / "dazn"
CDN_PROXY_FILE = DAZN_DIR / "cdn_proxy.txt"
PROXY_FILE = DAZN_DIR / "proxy.txt"  # fallback login-style proxy se ISP assente

DAZN_IMAGE_URL = "https://image.discovery.indazn.com/eu/v2/eu/image/?id="

RAIL_HEADERS = {
    "accept": "application/json, text/plain, */*",
    "origin": "https://www.dazn.com",
    "referer": "https://www.dazn.com/",
    "user-agent": (
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
        "(KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36"
    ),
}


def _rail_competition(rail_id: str, content_id: str) -> str:
    return (
        "https://rail-router.discovery.indazn.com/eu/v11/Rail"
        f"?platform=web&id={rail_id}&country=it&brand=dazn&languageCode=it"
        f"&params=PageType:Competition%3BContentType:Competition%3BContentId:{content_id}"
    )


# (display name, json filename, rail url)
RAIL_REPLICAS: List[Tuple[str, str, str]] = [
    (
        "Serie A",
        "serieA.json",
        _rail_competition("ef9c0227-dc48-41a0-b910-00d74678838e", "1r097lpxe0xn03ihb7wi98kao"),
    ),
    (
        "Serie B",
        "serieB.json",
        _rail_competition("f0b2f2ff-9723-4e24-9963-0f30b7d995ce", "8ey0ww2zsosdmwr8ehsorh6t7"),
    ),
    (
        "LaLiga",
        "laLiga.json",
        _rail_competition("CatchUp", "34pl8szyvrbwcmfkuocjm3r6t"),
    ),
    (
        "Coppa del Mondo",
        "coppaDelMondo.json",
        _rail_competition("7496df45-c1d8-4304-b7ba-23e1dd9a3bda", "70excpe1synn9kadnbppahdn7"),
    ),
]


def _load_proxy() -> Optional[Dict[str, str]]:
    for path in (CDN_PROXY_FILE, PROXY_FILE):
        try:
            raw = path.read_text(encoding="utf-8").strip().splitlines()
        except Exception:
            continue
        line = next((ln.strip() for ln in raw if ln.strip() and not ln.strip().startswith("#")), "")
        if not line:
            continue
        if "://" not in line:
            parts = line.split(":")
            if len(parts) == 4:
                host, port, user, pwd = parts
                line = f"http://{user}:{pwd}@{host}:{port}"
            else:
                line = "http://" + line
        print(f"[proxy] using {path.name} -> {line.split('@')[-1]}")
        return {"http": line, "https": line}
    print("[proxy] WARNING: no proxy file, direct")
    return None


def _parse_dazn_dt(value: Any) -> Optional[datetime]:
    if not value:
        return None
    try:
        s = str(value).replace("Z", "+00:00")
        return datetime.fromisoformat(s)
    except Exception:
        return None


def _nested_title(obj: Any) -> str:
    if isinstance(obj, dict):
        return str(obj.get("Title") or obj.get("Name") or "")
    return str(obj or "")


def _tile_image_id(tile: Dict[str, Any]) -> str:
    """Estrae id immagine tile CatchUp (Image/Portrait/… nested Id, o ImageId flat)."""
    for key in (
        "Image",
        "PortraitImage",
        "LogoImage",
        "HeroImage",
        "BackgroundImage",
        "PromoImage",
    ):
        img = tile.get(key)
        if isinstance(img, dict) and img.get("Id"):
            return str(img["Id"])
        if isinstance(img, str) and img.strip():
            return img.strip()
    for key in ("ImageId", "imageId", "HeroImageId"):
        v = tile.get(key)
        if v:
            return str(v)
    imgs = tile.get("Images") or tile.get("ImageList") or []
    if isinstance(imgs, list) and imgs:
        first = imgs[0]
        if isinstance(first, dict):
            return str(first.get("Id") or first.get("id") or "")
        return str(first)
    return ""


def _is_highlight_tile(tile: Dict[str, Any]) -> bool:
    typ = str(tile.get("Type") or "").lower()
    display = str(tile.get("DisplayType") or "").lower()
    title = str(tile.get("Title") or "").lower()
    if typ in ("highlights", "ondemand") or display in ("highlights", "ondemand"):
        return True
    needles = ("highlight", "tutti i gol", "gli altri gol", "tutti i goal", "gli altri goal")
    return any(n in title for n in needles)


def _tile_to_replay(tile: Dict[str, Any], competition_fallback: str) -> Optional[Dict[str, Any]]:
    if not isinstance(tile, dict):
        return None
    typ = tile.get("Type") or ""
    display = tile.get("DisplayType") or ""
    if typ != "CatchUp" and display != "CatchUp":
        return None
    if _is_highlight_tile(tile):
        return None
    asset_id = tile.get("AssetId")
    if not asset_id:
        return None
    start_dt = _parse_dazn_dt(tile.get("Start") or tile.get("EventStartTime") or tile.get("MediaStartTime"))
    end_dt = _parse_dazn_dt(tile.get("End"))
    duration_ms = tile.get("DurationInMillis") or 0
    try:
        duration_min = int(duration_ms) // 60000
    except Exception:
        duration_min = 0
    competition = _nested_title(tile.get("Competition")) or competition_fallback
    title = tile.get("Title") or f"Replica {asset_id}"
    img_id = _tile_image_id(tile)
    logo = f"{DAZN_IMAGE_URL}{img_id}" if img_id else ""
    return {
        "id": asset_id,
        "name": title,
        "logo": logo,
        "image": logo,
        "locandina": logo,
        "playback_url": "",
        "competition": competition,
        "label": tile.get("Label") or "",
        "source": "catchup",
        "event_id": tile.get("EventId") or "",
        "duration_min": duration_min,
        "epg": {
            "start": start_dt.isoformat() if start_dt else "",
            "end": end_dt.isoformat() if end_dt else "",
        },
    }


def fetch_rail(url: str, proxy: Optional[Dict[str, str]]) -> Optional[Dict[str, Any]]:
    try:
        r = requests.get(url, headers=RAIL_HEADERS, proxies=proxy, timeout=45)
        if not r.ok:
            print(f"  HTTP {r.status_code}")
            return None
        return r.json()
    except Exception as e:
        print(f"  ERR {e}")
        return None


def main() -> int:
    SCRIPT_DIR.mkdir(parents=True, exist_ok=True)
    proxy = _load_proxy()
    now = datetime.now(timezone.utc).astimezone().isoformat(timespec="seconds")
    index: Dict[str, Any] = {"updated_at": now, "competitions": {}, "by_id": {}}
    total = 0

    for name, filename, url in RAIL_REPLICAS:
        print(f"== {name} ==")
        data = fetch_rail(url, proxy)
        events: List[Dict[str, Any]] = []
        skipped_hl = 0
        if data:
            tiles = data.get("Tiles") or []
            seen = set()
            for tile in tiles:
                if _is_highlight_tile(tile):
                    skipped_hl += 1
                    continue
                ch = _tile_to_replay(tile, name)
                if not ch or ch["id"] in seen:
                    continue
                seen.add(ch["id"])
                events.append(ch)
        out = {
            "updated_at": now,
            "competition": name,
            "count": len(events),
            "skipped_highlights": skipped_hl,
            "events": events,
        }
        path = SCRIPT_DIR / filename
        path.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
        print(f"  wrote {filename}: {len(events)} CatchUp (hl skip {skipped_hl})")
        index["competitions"][name] = {"file": filename, "count": len(events)}
        for ev in events:
            index["by_id"][ev["id"]] = {
                "name": ev["name"],
                "competition": name,
                "file": filename,
                "logo": ev.get("logo") or "",
                "source": "catchup",
            }
        total += len(events)

    index_path = SCRIPT_DIR / "index.json"
    index_path.write_text(json.dumps(index, ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"OK total={total} index={index_path}")
    return 0 if total > 0 else 1


if __name__ == "__main__":
    sys.exit(main())
