"""Convert legacy contact-person blocks into page-body contact cards."""

from __future__ import annotations

from bs4 import BeautifulSoup, Tag

from . import TransformContext


def transform(soup: BeautifulSoup, ctx: TransformContext) -> None:
    for root in list(soup.find_all(class_="contact-persons")):
        if not isinstance(root, Tag):
            continue
        upgraded = _upgrade(root, soup)
        if upgraded is not None:
            root.replace_with(upgraded)


def _upgrade(root: Tag, soup: BeautifulSoup) -> Tag | None:
    section = soup.new_tag("section", **{"class": "page-body__contact-persons"})

    headline = root.find(class_="contact-persons__headline")
    if isinstance(headline, Tag):
        h2 = soup.new_tag("h2")
        h2.string = " ".join(headline.get_text(" ", strip=True).split())
        section.append(h2)

    grid = soup.new_tag("div", **{"class": "page-body__contact-persons-grid"})
    for item in root.find_all(class_="contact-persons__item"):
        if not isinstance(item, Tag):
            continue
        card = _build_card(item, soup)
        if card is not None:
            grid.append(card)

    if grid.contents:
        section.append(grid)

    return section if section.contents else None


def _build_card(item: Tag, soup: BeautifulSoup) -> Tag | None:
    card = soup.new_tag("article", **{"class": "page-body__contact-card"})

    image_wrap = item.find(class_="contact-persons__item-image")
    if isinstance(image_wrap, Tag):
        img = image_wrap.find("img")
        if isinstance(img, Tag):
            figure = soup.new_tag("figure", **{"class": "page-body__contact-card-media"})
            extracted = img.extract()
            existing_classes = extracted.get("class") or []
            extracted["class"] = [
                c for c in existing_classes
                if c not in {"image", "image--fluid", "js-lazy"}
            ] + ["page-body__contact-card-image"]
            figure.append(extracted)
            card.append(figure)

    content = soup.new_tag("div", **{"class": "page-body__contact-card-body"})
    name = item.find(class_="contact-persons__item-name")
    if isinstance(name, Tag):
        p = soup.new_tag("p", **{"class": "page-body__contact-card-name"})
        p.string = " ".join(name.get_text(" ", strip=True).split())
        content.append(p)

    details = item.find(class_="contact-persons__item-content")
    if isinstance(details, Tag):
        for child in list(details.children):
            if isinstance(child, Tag) and child.get_text(" ", strip=True):
                if not content.find(class_="page-body__contact-card-name") and child.name == "p":
                    child["class"] = ["page-body__contact-card-name"]
                content.append(child.extract())

    if content.contents:
        card.append(content)

    return card if card.contents else None
