import httpx

from fastapi import APIRouter, HTTPException
from fastapi.responses import Response
from urllib.parse import urlsplit

from hermes_hls_registry import HLSRegistry
from hermes_hls_manifest import transformar_manifest
from hermes_hls_fetch import descargar_hls
from hermes_hls_security import validar_destino

router = APIRouter(
    prefix="/api/player",
    tags=["Hermes Web Player"]
)

registro = HLSRegistry(ttl=300)


def resolver_canal(liga, equipo):
    if not liga.isalnum() or not equipo.isalnum():
        raise ValueError("Identificador invalido")

    ruta = (
        "http://127.0.0.1:8005/live/"
        + liga + "/" + equipo + ".m3u8"
    )

    with httpx.Client(
        timeout=10,
        follow_redirects=False
    ) as cliente:
        r = cliente.get(ruta)

    if r.status_code != 302:
        raise ValueError("Canal no disponible")

    destino = r.headers.get("location")

    if not destino:
        raise ValueError("Canal sin destino")

    return validar_destino(destino)


def enlace_privado(url):
    validar_destino(url)
    identificador = registro.registrar(url)
    return "/api/player/resource/" + identificador


def responder_recurso(url):
    resultado = descargar_hls(
        url,
        "manifest" if urlsplit(url).path.endswith(".m3u8") else "segment"
    )

    contenido = resultado["contenido"]
    url_final = resultado["url_final"]

    if contenido.startswith(b"#EXTM3U"):
        texto = contenido.decode("utf-8-sig")

        transformado = transformar_manifest(
            texto,
            url_final,
            enlace_privado
        )

        return Response(
            content=transformado,
            media_type="application/vnd.apple.mpegurl",
            headers={"Cache-Control": "no-store"}
        )

    return Response(
        content=contenido,
        media_type=resultado["tipo"].split(";")[0],
        headers={"Cache-Control": "no-store"}
    )


@router.get("/play/{liga}/{equipo}.m3u8")
def iniciar_reproduccion(liga: str, equipo: str):
    try:
        destino = resolver_canal(liga, equipo)
        return responder_recurso(destino)
    except Exception:
        raise HTTPException(
            status_code=502,
            detail="No se pudo iniciar la reproduccion"
        )


@router.get("/resource/{identificador}")
def obtener_recurso(identificador: str):
    try:
        url = registro.resolver(identificador)
        return responder_recurso(url)
    except ValueError:
        raise HTTPException(
            status_code=404,
            detail="Recurso no disponible"
        )
    except Exception:
        raise HTTPException(
            status_code=502,
            detail="Error al recuperar recurso HLS"
        )


@router.get("/health")
def player_health():
    return {
        "servicio": "Hermes Web Player",
        "estado": "laboratorio",
        "reproduccion": True
    }
