#!/usr/bin/env python3
"""Aggiorna i cataloghi replica. Serie A è l'intera pagina (herobar + sezioni)."""
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
from urllib.parse import quote

import requests

SERIEA_CONTENT_ID = "1r097lpxe0xn03ihb7wi98kao"
SERIEA_DIR = "SerieA"

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 _tile_to_catalog_event(tile: Dict[str, Any], competition: str, section: str) -> Optional[Dict[str, Any]]:
    """Qualsiasi tile con AssetId (live, prossimi, catchup, highlight)."""
    if not isinstance(tile, dict):
        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
    comp = _nested_title(tile.get("Competition")) or competition
    img_id = _tile_image_id(tile)
    logo = f"{DAZN_IMAGE_URL}{img_id}" if img_id else ""
    kind = str(tile.get("Type") or tile.get("DisplayType") or "tile")
    return {
        "id": asset_id,
        "name": tile.get("Title") or f"Evento {asset_id}",
        "logo": logo,
        "image": logo,
        "locandina": logo,
        "playback_url": "",
        "competition": comp,
        "label": tile.get("Label") or "",
        "description": tile.get("Description") or "",
        "source": kind.lower(),
        "type": tile.get("Type") or "",
        "display_type": tile.get("DisplayType") or "",
        "section": section,
        "event_id": tile.get("EventId") or "",
        "duration_min": duration_min,
        "is_live": bool(tile.get("IsLive")),
        "epg": {
            "start": start_dt.isoformat() if start_dt else "",
            "end": end_dt.isoformat() if end_dt else "",
        },
    }


def _link_id(node: Any) -> str:
    if isinstance(node, dict):
        return str((node.get("sys") or {}).get("id") or "")
    return ""


def _asset_url(asset: Dict[str, Any]) -> str:
    url = str(((asset.get("fields") or {}).get("file") or {}).get("url") or "")
    if url.startswith("//"):
        return "https:" + url
    return url


def _hero_image(fields: Dict[str, Any], entries: Dict[str, Any], assets: Dict[str, Any]) -> str:
    """Desktop web, poi default, poi gli altri formati del banner."""
    for key in ("backgroundImageV2", "backgroundImage"):
        group = entries.get(_link_id(fields.get(key))) or {}
        group_fields = group.get("fields") or {}
        for variant in ("web", "default", "livingRoom", "tablet", "mobile"):
            asset = assets.get(_link_id(group_fields.get(variant)))
            if asset:
                url = _asset_url(asset)
                if url:
                    return url
    return ""


def _seriea_hero(proxy: Optional[Dict[str, str]]) -> List[Dict[str, Any]]:
    url = (
        "https://dazn-content-proxy.sd.indazn.com/spaces/vhp9jnid12wf/environments/master/entries"
        "?content_type=CatalogueBanners&locale=it-IT&include=10&limit=1000"
        "&fields.platform%5Bin%5D=Web&fields.countries%5Bin%5D=IT"
        f"&fields.pageIds%5Bin%5D=Competition%3A{SERIEA_CONTENT_ID}"
        "&select=fields.loggedInBannerItems%2Cfields.slideIntervalDuration%2Csys.id%2Csys.type"
        "&fields.environment=Prod"
    )
    data = fetch_rail(url, proxy)
    if not data:
        return []
    includes = data.get("includes") or {}
    entries = {
        e.get("sys", {}).get("id"): e
        for e in (includes.get("Entry") or [])
        if isinstance(e, dict)
    }
    assets = {
        a.get("sys", {}).get("id"): a
        for a in (includes.get("Asset") or [])
        if isinstance(a, dict)
    }
    items = data.get("items") or []
    banner_ids = []
    if items:
        banner_ids = [
            x.get("sys", {}).get("id")
            for x in ((items[0].get("fields") or {}).get("loggedInBannerItems") or [])
            if isinstance(x, dict)
        ]
    slides = []
    for bid in banner_ids:
        fields = (entries.get(bid) or {}).get("fields") or {}
        title = fields.get("title") or ""
        if not title:
            continue
        image = _hero_image(fields, entries, assets)
        slides.append({
            "id": "",
            "name": title,
            "title": title,
            "subtitle": fields.get("subTitle") or "",
            "description": fields.get("description") or "",
            "image": image,
            "logo": image,
            "locandina": image,
            "section": "Herobar",
            "source": "herobar",
            "competition": "Serie A",
        })
    return slides


def _slug(title: str, rail_id: str) -> str:
    raw = (title or rail_id or "sezione").strip().lower()
    for src, dst in (("à", "a"), ("è", "e"), ("é", "e"), ("ì", "i"), ("ò", "o"), ("ù", "u")):
        raw = raw.replace(src, dst)
    raw = re.sub(r"[^a-z0-9]+", "-", raw).strip("-")
    return (raw or rail_id)[:60]


def build_seriea_catalog(proxy: Optional[Dict[str, str]], now: str) -> Optional[Dict[str, Any]]:
    """Pagina Serie A intera: herobar, live, prossimi, recenti e le altre rail."""
    params = quote(
        f"PageType:Competition;ContentType:Competition;ContentId:{SERIEA_CONTENT_ID}",
        safe="",
    )
    group_url = (
        "https://rails.discovery.indazn.com/eu/v9/rails?groupId=competition&country=it"
        f"&params={params}&openBrowse=false&userEntitlements=tier_silver_it&brand=dazn"
    )
    group = fetch_rail(group_url, proxy)
    rails = (group or {}).get("Rails") or (group or {}).get("rails") or []
    if not rails:
        return None
    sections: List[Dict[str, Any]] = []
    hero = _seriea_hero(proxy)
    sections.append({
        "title": "Herobar",
        "rail_id": "herobar",
        "file": "herobar.json",
        "count": len(hero),
        "events": hero,
    })
    flat: List[Dict[str, Any]] = []
    seen = set()
    for rail in rails:
        rail_id = str(rail.get("Id") or rail.get("id") or "")
        if not rail_id:
            continue
        url = _rail_competition(rail_id, SERIEA_CONTENT_ID)
        data = fetch_rail(url, proxy)
        if not data:
            print(f"  skip rail {rail_id}")
            continue
        title = str(data.get("Title") or rail_id)
        events = []
        for tile in data.get("Tiles") or []:
            ev = _tile_to_catalog_event(tile, "Serie A", title)
            if not ev:
                continue
            events.append(ev)
            if ev["id"] not in seen:
                seen.add(ev["id"])
                flat.append(ev)
        sections.append({
            "title": title,
            "rail_id": rail_id,
            "file": f"{_slug(title, rail_id)}.json",
            "count": len(events),
            "events": events,
        })
        print(f"  {title}: {len(events)}")
    return {
        "updated_at": now,
        "competition": "Serie A",
        "count": len(flat),
        "sections": sections,
        "events": flat,
    }


def _write_seriea_folder(catalog: Dict[str, Any], index: Dict[str, Any]) -> int:
    folder = SCRIPT_DIR / SERIEA_DIR
    folder.mkdir(parents=True, exist_ok=True)
    used = set()
    section_index = []
    for section in catalog["sections"]:
        fname = section["file"]
        if fname in used:
            stem = fname[:-5] if fname.endswith(".json") else fname
            fname = f"{stem}-{section['rail_id'][:8]}.json"
        used.add(fname)
        payload = {
            "updated_at": catalog["updated_at"],
            "competition": "Serie A",
            "section": section["title"],
            "rail_id": section["rail_id"],
            "count": section["count"],
            "events": section["events"],
        }
        (folder / fname).write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
        section_index.append({
            "file": fname,
            "title": section["title"],
            "rail_id": section["rail_id"],
            "count": section["count"],
        })
        for ev in section["events"]:
            if not ev.get("id") or ev["id"] in index["by_id"]:
                continue
            index["by_id"][ev["id"]] = {
                "name": ev.get("name") or ev.get("title") or "",
                "competition": "Serie A",
                "file": f"{SERIEA_DIR}/{fname}",
                "logo": ev.get("logo") or "",
                "source": ev.get("source") or "catchup",
                "section": section["title"],
            }
    for stale in folder.glob("*.json"):
        if stale.name != "index.json" and stale.name not in used:
            stale.unlink()
    folder_index = {
        "updated_at": catalog["updated_at"],
        "competition": "Serie A",
        "count": catalog["count"],
        "sections": section_index,
    }
    (folder / "index.json").write_text(json.dumps(folder_index, ensure_ascii=False, indent=2), encoding="utf-8")
    old = SCRIPT_DIR / "serieA.json"
    if old.exists():
        old.unlink()
        print("  removed serieA.json")
    index["competitions"]["Serie A"] = {
        "folder": SERIEA_DIR,
        "index": f"{SERIEA_DIR}/index.json",
        "count": catalog["count"],
        "sections": [s["title"] for s in section_index],
    }
    print(f"  wrote {SERIEA_DIR}/: {catalog['count']} eventi, {len(section_index)} json")
    return catalog["count"]


def _keep_seriea_folder(index: Dict[str, Any]) -> int:
    folder = SCRIPT_DIR / SERIEA_DIR
    idx_path = folder / "index.json"
    if not idx_path.exists():
        return 0
    meta = json.loads(idx_path.read_text(encoding="utf-8"))
    n = 0
    for section in meta.get("sections") or []:
        path = folder / section["file"]
        if not path.exists():
            continue
        data = json.loads(path.read_text(encoding="utf-8"))
        for ev in data.get("events") or []:
            if not ev.get("id"):
                continue
            index["by_id"][ev["id"]] = {
                "name": ev.get("name") or ev.get("title") or "",
                "competition": "Serie A",
                "file": f"{SERIEA_DIR}/{section['file']}",
                "logo": ev.get("logo") or "",
                "source": ev.get("source") or "catchup",
                "section": section.get("title") or "",
            }
            n += 1
    index["competitions"]["Serie A"] = {
        "folder": SERIEA_DIR,
        "index": f"{SERIEA_DIR}/index.json",
        "count": meta.get("count") or n,
        "sections": [s.get("title") for s in (meta.get("sections") or [])],
    }
    return int(meta.get("count") or n)


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} ==")
        if name == "Serie A":
            catalog = build_seriea_catalog(proxy, now)
            if catalog:
                total += _write_seriea_folder(catalog, index)
            else:
                print("  pagina Serie A non letta, tengo la cartella già presente")
                total += _keep_seriea_folder(index)
            continue
        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())
