"""Sanitize URL-bearing attributes.

The source CMS occasionally emits HTML where ``href`` / ``src`` values carry
stray ``&quot;``, ``&#39;``, backslash-escaped quotes, or trailing whitespace.
Once BeautifulSoup decodes the entities those artefacts end up as literal
characters inside the attribute value, which in turn forces the serializer to
pick single-quote or escaped delimiters — and the URL itself is still broken.

Example observed on ``/en/company/references/11decks-community-spaces/``:

    <a href="https://pasch-design.com/…11decks-community-spaces&quot;">

after entity decode becomes

    <a href='https://pasch-design.com/…11decks-community-spaces"'>

This rule strips trailing quotes / backslashes / whitespace from the values
of ``<a href>``, ``<img src>``, and ``<source src>``. Leading junk is also
trimmed. Purely local — no network, no URL rewriting logic.
"""

from __future__ import annotations

from bs4 import BeautifulSoup, Tag

from . import TransformContext


_URL_TRIM_CHARS = "\"'\\ \t\r\n"


def _clean(value: str) -> str:
    return value.strip().strip(_URL_TRIM_CHARS).strip()


def transform(soup: BeautifulSoup, ctx: TransformContext) -> None:
    for a in list(soup.find_all("a", href=True)):
        if not isinstance(a, Tag):
            continue
        cleaned = _clean(a["href"])
        if cleaned != a["href"]:
            a["href"] = cleaned

    for img in list(soup.find_all("img", src=True)):
        if not isinstance(img, Tag):
            continue
        cleaned = _clean(img["src"])
        if cleaned != img["src"]:
            img["src"] = cleaned

    for source in list(soup.find_all("source", src=True)):
        if not isinstance(source, Tag):
            continue
        cleaned = _clean(source["src"])
        if cleaned != source["src"]:
            source["src"] = cleaned
