"""Convierte URLs de blob de GitHub/GitLab a su equivalente raw."""

from urllib.parse import urlparse, urlunparse


def convert_github_to_raw_url(url: str) -> str:
    """Convierte una URL de blob de GitHub o GitLab a su URL raw.

    GitHub blob:
        https://github.com/org/repo/blob/main/path/file.py
        → https://raw.githubusercontent.com/org/repo/main/path/file.py

    GitLab blob:
        https://gitlab.com/org/repo/-/blob/main/path/file.py
        → https://gitlab.com/org/repo/-/raw/main/path/file.py

    Si la URL no contiene un path tipo blob, la retorna sin cambios.

    Args:
        url: URL de GitHub o GitLab, posiblemente apuntando a un blob.

    Returns:
        URL raw si aplica la transformacion; la URL original en caso contrario.
    """
    url = url.strip()
    if not url:
        return url

    parsed = urlparse(url)
    host = parsed.hostname or ""

    # --- GitHub ---
    if host in ("github.com", "www.github.com"):
        # Path tipico: /org/repo/blob/ref/path/to/file
        segments = parsed.path.split("/")
        if "blob" in segments:
            blob_idx = segments.index("blob")
            # Eliminar segmento "blob": /org/repo/ref/path/...
            new_segments = segments[:blob_idx] + segments[blob_idx + 1:]
            new_path = "/".join(new_segments)
            raw_url = urlunparse((
                "https",
                "raw.githubusercontent.com",
                new_path,
                parsed.params,
                parsed.query,
                parsed.fragment,
            ))
            return raw_url
        return url

    # --- GitLab ---
    if host in ("gitlab.com", "www.gitlab.com") or host.startswith("gitlab."):
        # Path tipico: /org/repo/-/blob/ref/path o /org/repo/blob/ref/path
        new_path = parsed.path.replace("/-/blob/", "/-/raw/").replace("/blob/", "/raw/")
        if new_path != parsed.path:
            raw_url = urlunparse((
                parsed.scheme,
                parsed.netloc,
                new_path,
                parsed.params,
                parsed.query,
                parsed.fragment,
            ))
            return raw_url
        return url

    # No aplica transformacion
    return url
