#!/usr/bin/env python3
"""
NOW TV replica proxy (stile dazn :8443).
  GET /nowtv/f1.json          → rail F1 auto
  GET /replicainfo/<id>       → ClearKey + MPD CDN (NON proxato)
  GET /playlist.m3u             → canali già estratti
  GET /play/<id>/stream.mpd   → MPD ClearKey (BaseURL CDN)

Default port 8787; su VPS gira dietro/accanto a dazn :8443.
"""
from __future__ import annotations

import asyncio
import json
import os
import re
from typing import Any, Dict

try:
    from aiohttp import web
except ImportError:
    print("pip install aiohttp")
    raise SystemExit(1)

from now_bridge import get_replicainfo, list_f1_events, load_f1_index, patch_mpd_clearkey_cdn

SCRIPT = os.path.dirname(os.path.abspath(__file__))
CFG = json.loads(open(os.path.join(SCRIPT, "now_config.json"), encoding="utf-8").read())
DATA = os.path.join(SCRIPT, "now_proxy_data.json")
CACHE = os.path.join(SCRIPT, "nowtv_cache")
PORT = int(CFG.get("proxy_port") or 8787)


def load_channels() -> Dict[str, Dict[str, Any]]:
    if not os.path.exists(DATA):
        return {}
    raw = json.loads(open(DATA, encoding="utf-8").read())
    out = {}
    for ch in raw.get("channels") or []:
        out[ch["id"]] = ch
    return out


async def handle_f1_json(_request: web.Request) -> web.Response:
    data = list_f1_events()
    return web.json_response(data, headers={"Access-Control-Allow-Origin": "*"})


async def handle_replica_info(request: web.Request) -> web.Response:
    asset_id = request.match_info.get("id") or ""
    force = request.rel_url.query.get("force") in ("1", "true", "yes")
    if not re.fullmatch(r"R_\d+(?:_HD)?", asset_id, flags=re.I):
        # accetta comunque id presenti nella rail
        if not any(
            str(e.get("id")) == asset_id for e in (load_f1_index().get("events") or [])
        ):
            return web.json_response(
                {"error": "Bad NOW asset id", "id": asset_id}, status=400
            )

    payload = await asyncio.to_thread(get_replicainfo, asset_id, force)
    if payload.get("status") != "OK":
        code = 503 if "Extract" in str(payload.get("error") or "") else 502
        return web.json_response(payload, status=code)
    return web.json_response(payload, headers={"Access-Control-Allow-Origin": "*"})


async def handle_playlist(request: web.Request) -> web.Response:
    host = request.host or f"127.0.0.1:{PORT}"
    lines = ["#EXTM3U"]
    # rail F1 (solo metadati — le chiavi arrivano da /replicainfo)
    for ev in (load_f1_index().get("events") or []):
        cid = ev.get("id")
        name = ev.get("name") or cid
        lines.append(f'#EXTINF:-1 tvg-id="{cid}" group-title="NOW F1",{name}')
        lines.append(f"http://{host}/replicainfo/{cid}")
    for cid, ch in load_channels().items():
        kid, key = ch.get("kid"), ch.get("key")
        lines.append(f'#EXTINF:-1 tvg-id="{cid}" group-title="NOW Italia",{ch.get("name", cid)}')
        lines.append("#KODIPROP:inputstream=inputstream.adaptive")
        lines.append("#KODIPROP:inputstream.adaptive.manifest_type=mpd")
        if kid and key:
            lines.append("#KODIPROP:inputstream.adaptive.license_type=clearkey")
            lines.append(f"#KODIPROP:inputstream.adaptive.license_key={kid}:{key}")
        lines.append(f"http://{host}/play/{cid}/stream.mpd")
    return web.Response(text="\n".join(lines) + "\n", content_type="audio/mpegurl")


async def handle_play(request: web.Request) -> web.Response:
    cid = request.match_info["id"]
    # cache da replicainfo
    cached = os.path.join(CACHE, f"{cid}.mpd")
    if os.path.isfile(cached):
        body = open(cached, encoding="utf-8").read()
        return web.Response(
            text=body,
            content_type="application/dash+xml",
            headers={"Access-Control-Allow-Origin": "*", "Cache-Control": "no-cache"},
        )
    payload = await asyncio.to_thread(get_replicainfo, cid, False)
    if payload.get("status") != "OK" or not payload.get("mpd"):
        raise web.HTTPBadGateway(text=str(payload.get("error") or "extract failed"))
    return web.Response(
        text=payload["mpd"],
        content_type="application/dash+xml",
        headers={"Access-Control-Allow-Origin": "*", "Cache-Control": "no-cache"},
    )


def main() -> int:
    app = web.Application()
    app.router.add_get("/nowtv/f1.json", handle_f1_json)
    app.router.add_get("/nowtv/f1", handle_f1_json)
    app.router.add_get("/replicainfo/{id}", handle_replica_info)
    app.router.add_get("/playlist.m3u", handle_playlist)
    app.router.add_get("/play/{id}/stream.mpd", handle_play)
    print(f"NOW replica http://127.0.0.1:{PORT}/nowtv/f1.json")
    print(f"NOW replicainfo http://127.0.0.1:{PORT}/replicainfo/R_xxxxxx_HD")
    web.run_app(app, host="0.0.0.0", port=PORT, print=None)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
