import httpx
from contextlib import contextmanager
from urllib.parse import urljoin

from hermes_hls_security import validar_destino
from hermes_hls_fetch import MAX_SEGMENT


@contextmanager
def abrir_segmento(url):
    actual = validar_destino(url)

    with httpx.Client(
        timeout=httpx.Timeout(20.0, connect=5.0),
        follow_redirects=False,
        trust_env=False
    ) as cliente:

        for _ in range(4):
            validar_destino(actual)

            with cliente.stream("GET", actual) as respuesta:

                if respuesta.status_code in (
                    301, 302, 303, 307, 308
                ):
                    destino = respuesta.headers.get("location")

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

                    actual = validar_destino(
                        urljoin(actual, destino)
                    )
                    continue

                # Validar ANTES de iniciar HTTP 200
                respuesta.raise_for_status()

                longitud = respuesta.headers.get("content-length")

                if longitud and int(longitud) > MAX_SEGMENT:
                    raise ValueError("Segmento demasiado grande")

                def bloques():
                    total = 0

                    for bloque in respuesta.iter_bytes(65536):
                        total += len(bloque)

                        if total > MAX_SEGMENT:
                            raise ValueError(
                                "Limite de segmento excedido"
                            )

                        yield bloque

                yield bloques()
                return

    raise ValueError("Demasiadas redirecciones")
