"""Shared image URL normalization for master catalog and channel push."""

from __future__ import annotations

from typing import List
from urllib.parse import quote, unquote, urlsplit, urlunsplit


def normalize_external_image_url(url: str) -> str:
    """Normalize CSV/R2 URLs before storage or external channel upload."""
    text = str(url or "").strip()
    if not text:
        return text
    if (text.startswith('"') and text.endswith('"')) or (text.startswith("'") and text.endswith("'")):
        text = text[1:-1].strip()
    if text.startswith("//"):
        text = "https:" + text
    elif not text.lower().startswith(("http://", "https://")):
        text = "https://" + text.lstrip("/")
    return _encode_url_special_characters(text)


def _encode_url_special_characters(url: str) -> str:
    """Percent-encode spaces/parentheses in the path — browsers do this implicitly; APIs do not."""
    parts = urlsplit(url)
    if not parts.scheme or not parts.netloc:
        return url
    path = quote(unquote(parts.path), safe="/")
    query = quote(unquote(parts.query), safe="=&?/:,") if parts.query else parts.query
    return urlunsplit((parts.scheme, parts.netloc, path, query, parts.fragment))


def prepare_image_urls(urls: List[str]) -> List[str]:
    """Normalize and dedupe image URLs."""
    seen: set[str] = set()
    prepared: List[str] = []
    for url in urls:
        normalized = normalize_external_image_url(url)
        if normalized and normalized not in seen:
            seen.add(normalized)
            prepared.append(normalized)
    return prepared
