"""Rule: ``.product-detail__downloads*`` → ``<ul class="page-body__downloads">``.

Source (/service-knowledge/downloads/**, /sales-delivery/):

    <h2 class="product-detail__downloads-headline">Downloads</h2>
    <div class="product-detail__downloads">
      <a class="product-detail__downloads-item" href="/fileadmin/…PDF" target="_blank">
        <div class="product-detail__downloads-item-icon">…svg…</div>
        <div class="product-detail__downloads-item-body">
          <div class="product-detail__downloads-item-header flex">
            <p class="…">File title</p>
            <div class="formatted-text">Language</div>
          </div>
          <div class="formatted-text">
            <span class="…">Size (e.g. 65 MB)</span>
          </div>
        </div>
      </a>
      …
    </div>

Target (reuses ``.page-body__downloads`` CSS):

    <section class="page-body__downloads-section">
      <h2>Downloads</h2>
      <ul class="page-body__downloads">
        <li class="page-body__download">
          <a href="public://…PDF" target="_blank" rel="noopener">
            <span class="page-body__download__title">File title</span>
            <span class="page-body__download__meta">Language · Size</span>
          </a>
        </li>
        …
      </ul>
    </section>

``migrate_images`` runs later and rewrites the ``<a href>`` to the
``public://kaindl-pages/page-bodies/…`` URI, downloading the PDF to the
shared workspace.
"""

from __future__ import annotations

from bs4 import BeautifulSoup, Tag

from . import TransformContext


def _attr_str(value: object) -> str:
    if isinstance(value, str):
        return value
    if isinstance(value, list):
        return " ".join(str(part) for part in value)
    return "" if value is None else str(value)


def transform(soup: BeautifulSoup, ctx: TransformContext) -> None:
    for root in list(soup.find_all(class_="product-detail__downloads")):
        if not isinstance(root, Tag):
            continue
        if root.attrs is None or root.parent is None:
            continue
        _upgrade(root, soup)


def _upgrade(root: Tag, soup: BeautifulSoup) -> None:
    # Find an immediately-preceding ``.product-detail__downloads-headline``
    # and promote it to an ``<h2>`` inside the new section wrapper.
    headline_el = None
    sib = root.previous_sibling
    while sib is not None and not isinstance(sib, Tag):
        sib = sib.previous_sibling
    if isinstance(sib, Tag) and "product-detail__downloads-headline" in (sib.get("class") or []):
        headline_el = sib
    else:
        # Fallback: look up the parent tree for a headline element.
        headline_el = root.parent.find(class_="product-detail__downloads-headline") if root.parent else None

    new_section = soup.new_tag("section", **{"class": "page-body__downloads-section"})
    if isinstance(headline_el, Tag):
        text = " ".join(headline_el.get_text(" ", strip=True).split())
        if text:
            h2 = soup.new_tag("h2")
            h2.string = text
            new_section.append(h2)
        headline_el.decompose()

    new_list = soup.new_tag("ul", **{"class": "page-body__downloads"})

    items = root.find_all(class_="product-detail__downloads-item", recursive=True)
    for item in items:
        if not isinstance(item, Tag):
            continue
        new_li = _build_download_li(item, soup)
        if new_li is not None:
            new_list.append(new_li)

    new_section.append(new_list)
    root.replace_with(new_section)


def _build_download_li(item: Tag, soup: BeautifulSoup) -> Tag | None:
    href = _attr_str(item.get("href")).strip()
    if not href:
        return None

    li = soup.new_tag("li", **{"class": "page-body__download"})
    a = soup.new_tag("a", href=href, target="_blank", rel="noopener")

    title_el = item.find(class_="product-detail__downloads-item-header")
    title_text = ""
    meta_parts: list[str] = []
    if isinstance(title_el, Tag):
        first_p = title_el.find("p")
        if isinstance(first_p, Tag):
            title_text = " ".join(first_p.get_text(" ", strip=True).split())
        # Any remaining text (e.g. language) in the header becomes meta.
        for child in title_el.find_all(string=True):
            text = " ".join(str(child).split())
            if text and text not in title_text:
                if text not in meta_parts:
                    meta_parts.append(text)

    # Size / secondary meta lives in a sibling .formatted-text after the header.
    body_el = item.find(class_="product-detail__downloads-item-body")
    if isinstance(body_el, Tag):
        for ft in body_el.find_all(class_="formatted-text"):
            if isinstance(ft, Tag) and ft is not title_el and (ft.parent is title_el is False):
                # Skip the header's own nested formatted-text (language label) — it was
                # already captured above — only pick the separate meta block.
                if not any(a in ft.parents for a in body_el.find_all(class_="product-detail__downloads-item-header")):
                    text = " ".join(ft.get_text(" ", strip=True).split())
                    if text and text not in meta_parts:
                        meta_parts.append(text)

    if title_text:
        title_span = soup.new_tag("span", **{"class": "page-body__download__title"})
        title_span.string = title_text
        a.append(title_span)
    if meta_parts:
        meta_span = soup.new_tag("span", **{"class": "page-body__download__meta"})
        meta_span.string = " · ".join(meta_parts)
        a.append(meta_span)

    if not a.contents:
        return None
    li.append(a)
    return li
