from urllib.parse import urljoin, urlsplit


def transformar_manifest_v4(
    contenido,
    origen,
    registrar_segmento,
    canal
):
    """
    Transformador HLS experimental.

    Conserva las etiquetas originales.
    Identifica segmentos mediante canal,
    secuencia y ruta de origen.
    """

    lineas = contenido.splitlines()
    resultado = []

    secuencia = None
    indice = 0

    for linea in lineas:
        texto = linea.strip()

        if texto.startswith("#EXT-X-MEDIA-SEQUENCE:"):
            secuencia = int(texto.split(":", 1)[1])

        if not texto or texto.startswith("#"):
            resultado.append(linea)
            continue

        destino = urljoin(origen, texto)
        p = urlsplit(destino)

        if secuencia is None:
            raise ValueError(
                "Playlist sin MEDIA-SEQUENCE"
            )

        identidad = (
            canal,
            secuencia + indice,
            p.scheme,
            p.hostname,
            p.port,
            p.path
        )

        enlace = registrar_segmento(
            destino,
            identidad
        )

        resultado.append(enlace)
        indice += 1

    return "\n".join(resultado) + "\n"
