#!/usr/bin/env python3
"""
NOW locale proxy (come dazn_proxy).
  playlist : http://127.0.0.1:8787/playlist.m3u
  mpd      : http://127.0.0.1:8787/play/<channel>/stream.mpd
I segmenti vengono presi dal CDN; l'MPD è patchato ClearKey.
Nessuna Fire Stick.
"""
from __future__ import annotations

import json
import os
import re
import sys
from typing import Any, Dict
from urllib.parse import urljoin

try:
    from aiohttp import ClientSession, web
except ImportError:
    print("pip install aiohttp")
    raise SystemExit(1)

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")
CK_UUID = "e2719d58-a985-b3c9-781a-214f90116bb0"
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


def patch_mpd(text: str, base: str) -> str:
    text = re.sub(
        r'<ContentProtection[^>]*schemeIdUri="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"[^>]*>.*?</ContentProtection>',
        "",
        text,
        flags=re.S,
    )
    text = re.sub(
        r'<ContentProtection[^>]*schemeIdUri="urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95"[^>]*>.*?</ContentProtection>',
        "",
        text,
        flags=re.S,
    )
    if CK_UUID not in text:
        text = re.sub(
            r'(<ContentProtection[^>]*value="cenc"[^>]*/>)',
            r'\1<ContentProtection schemeIdUri="urn:uuid:' + CK_UUID + '" />',
            text,
        )
    if "<BaseURL>" not in text:
        text = re.sub(r"(<Period\b[^>]*>)", r"\1<BaseURL>" + base + "</BaseURL>", text, count=1)
    return text


async def handle_playlist(request: web.Request) -> web.Response:
    host = request.host or f"127.0.0.1:{PORT}"
    lines = ["#EXTM3U"]
    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"]
    ch = load_channels().get(cid)
    if not ch:
        raise web.HTTPNotFound(text="channel")
    mpd_url = ch.get("mpd") or ""
    if not mpd_url:
        raise web.HTTPBadGateway(text="no mpd")
    headers = dict(CFG.get("headers") or {})
    async with ClientSession() as s:
        async with s.get(mpd_url, headers=headers) as r:
            text = await r.text()
            if r.status != 200:
                raise web.HTTPBadGateway(text=f"mpd {r.status}")
    base = mpd_url.split("?")[0].rsplit("/", 1)[0] + "/"
    body = patch_mpd(text, base)
    return web.Response(
        text=body,
        content_type="application/dash+xml",
        headers={"Access-Control-Allow-Origin": "*", "Cache-Control": "no-cache"},
    )


def main() -> int:
    app = web.Application()
    app.router.add_get("/playlist.m3u", handle_playlist)
    app.router.add_get("/play/{id}/stream.mpd", handle_play)
    print(f"NOW proxy http://127.0.0.1:{PORT}/playlist.m3u")
    web.run_app(app, host="127.0.0.1", port=PORT, print=None)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
