#!/usr/bin/env python3
"""Aggancia NOW TV F1 a dazn_proxy :8443 /replicainfo (id R_*)."""
from __future__ import annotations

import re
import time
from pathlib import Path

P = Path("/var/www/addictedbytheproject.nl/esdrongo/dazn/dazn_proxy.py")
bak = P.with_suffix(P.suffix + f".bak-nowtv-{time.strftime('%Y%m%d-%H%M%S')}")
bak.write_bytes(P.read_bytes())
t = P.read_text(encoding="utf-8")

HELPER = '''
# ── NOW TV F1 replica (MPD+chiavi NON proxate) ─────────────────
NOWTV_ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "nowtv")
if NOWTV_ROOT not in sys.path:
    sys.path.insert(0, NOWTV_ROOT)


def _is_nowtv_asset_id(asset_id: str) -> bool:
    return bool(re.fullmatch(r"R_\\d+(?:_HD)?", (asset_id or "").strip(), flags=re.I))


async def handle_nowtv_replica_info(request):
    """stesso contratto di /replicainfo ma extract NOW + BaseURL CDN."""
    asset_id = request.match_info.get("id") or ""
    force = request.rel_url.query.get("force") in ("1", "true", "yes")
    try:
        from now_bridge import get_replicainfo  # type: ignore
    except Exception as e:
        return web.json_response(
            {"error": f"now_bridge import: {e}", "id": asset_id}, status=500
        )
    payload = await asyncio.to_thread(get_replicainfo, asset_id, force)
    if payload.get("status") != "OK":
        return web.json_response(payload, status=503)
    return web.json_response(payload, headers={"Access-Control-Allow-Origin": "*"})


async def handle_nowtv_f1(_request):
    try:
        from now_bridge import list_f1_events  # type: ignore
    except Exception as e:
        return web.json_response({"error": str(e)}, status=500)
    return web.json_response(list_f1_events(), headers={"Access-Control-Allow-Origin": "*"})

'''

if "async def handle_nowtv_replica_info" not in t:
    # insert before handle_replica_info
    m = re.search(r"\nasync def handle_replica_info\(", t)
    if not m:
        raise SystemExit("handle_replica_info not found")
    t = t[: m.start()] + "\n" + HELPER + t[m.start() :]
    print("inserted nowtv helpers")
else:
    print("helpers already present")

# Wire start of handle_replica_info
needle = '''async def handle_replica_info(request):
    """https://host:8443/replicainfo/<assetid> → JSON con ClearKey + MPD (extract on-demand)."""
    asset_id = request.match_info.get("id")
    if not asset_id:
        return web.json_response({"error": "Bad Request", "id": None}, status=400)
    state = await ensure_replica_state(asset_id)
'''
repl = '''async def handle_replica_info(request):
    """https://host:8443/replicainfo/<assetid> → JSON con ClearKey + MPD (extract on-demand)."""
    asset_id = request.match_info.get("id")
    if not asset_id:
        return web.json_response({"error": "Bad Request", "id": None}, status=400)
    # NOW TV F1 (R_…) → MPD CDN diretto + chiavi, niente proxy segmenti
    if _is_nowtv_asset_id(asset_id):
        return await handle_nowtv_replica_info(request)
    state = await ensure_replica_state(asset_id)
'''
if "if _is_nowtv_asset_id(asset_id):" not in t:
    if needle not in t:
        raise SystemExit("handle_replica_info head not found for wire")
    t = t.replace(needle, repl, 1)
    print("wired replicainfo branch")
else:
    print("replicainfo branch already wired")

# routes
if 'add_get("/nowtv/f1.json"' not in t and "add_get('/nowtv/f1.json'" not in t:
    m = re.search(r"app\.router\.add_get\(['\"]/replicainfo/\{id\}['\"]", t)
    if not m:
        raise SystemExit("replicainfo route not found")
    insert = (
        "    app.router.add_get('/nowtv/f1.json', handle_nowtv_f1)\n"
        "    app.router.add_get('/nowtv/f1', handle_nowtv_f1)\n"
    )
    # insert before replicainfo route line
    line_start = t.rfind("\n", 0, m.start()) + 1
    t = t[:line_start] + insert + t[line_start:]
    print("added /nowtv/f1 routes")
else:
    print("nowtv routes already present")

P.write_text(t, encoding="utf-8")
import py_compile

py_compile.compile(str(P), doraise=True)
print("OK", bak)
