"""Rule 8: ``.rich-bullet-list`` → ``<ul class="page-body__feature-list">``.

Source shape (seen on reference / company / product pages):

    <div class="rich-bullet-list content-element">
      <div class="container-fluid container--padded">
        <div class="row">
          <div class="col-...">
            <h2 class="rich-bullet-list__headline">Project information</h2>
            <ul class="rich-bullet-list__items rich-bullet-list__items--2-cols">
              <li class="rich-bullet-list__item">
                <div class="rich-bullet-list__item-image-wrapper">
                  <picture>…<img class="rich-bullet-list__item-image" …></picture>
                </div>
                <div class="rich-bullet-list__item-content">
                  <h3 class="rich-bullet-list__item-headline">Design</h3>
                  <div class="formatted-text"><p>…</p></div>
                </div>
              </li>
              …
            </ul>
          </div>
        </div>
      </div>
    </div>

Target (runs before strip_bootstrap_cols / normalize_typography):

    <section class="page-body__feature-list-section">
      <h2>Project information</h2>
      <ul class="page-body__feature-list">
        <li class="page-body__feature-list__item">
          <span class="page-body__feature-list__icon" aria-hidden="true">
            <img src="…" alt="">
          </span>
          <div class="page-body__feature-list__body">
            <h3>Design</h3>
            <p>…</p>
          </div>
        </li>
        …
      </ul>
    </section>

The outer <section> keeps prose siblings (the `<h2>` headline) grouped with the
feature list so upgrade_sections wraps them as one logical block later.
Idempotent: the rule skips elements already wearing ``.page-body__feature-list``.
"""

from __future__ import annotations

from bs4 import BeautifulSoup, Tag

from . import TransformContext


def transform(soup: BeautifulSoup, ctx: TransformContext) -> None:
    for legacy in list(soup.find_all(class_="rich-bullet-list")):
        if not isinstance(legacy, Tag):
            continue
        if legacy.name == "ul" and "page-body__feature-list" in (legacy.get("class") or []):
            continue  # Idempotent no-op.
        _upgrade(legacy, soup)


def _upgrade(legacy_root: Tag, soup: BeautifulSoup) -> None:
    headline_el = legacy_root.find(class_="rich-bullet-list__headline")
    items_root = legacy_root.find(class_="rich-bullet-list__items")
    items = items_root.find_all(class_="rich-bullet-list__item", recursive=False) if isinstance(items_root, Tag) else []

    # Variant seen on /en/careers/apprenticeships-kaindl/: the section carries
    # only a ``.rich-bullet-list__text formatted-text`` block (headings + prose,
    # no icon list). Fall back to a simple unwrap so the inner content survives
    # and upgrade_sections / normalize_typography clean it up.
    if not items and not isinstance(headline_el, Tag):
        legacy_root.unwrap()
        return
    if not items:
        # Has a headline but no items — emit a bare <h2> + unwrap the rest.
        h2 = soup.new_tag("h2")
        h2.string = " ".join(headline_el.get_text(" ", strip=True).split())
        legacy_root.insert_before(h2)
        headline_el.decompose()
        legacy_root.unwrap()
        return

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

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

    for item in items:
        if not isinstance(item, Tag):
            continue
        new_item = _build_item(item, soup)
        if new_item is not None:
            new_list.append(new_item)

    new_section.append(new_list)

    # Some pages (e.g. /en/careers/apprenticeships-kaindl/) carry a sibling
    # ``.rich-bullet-list__text`` block alongside ``.__items`` — prose + h3
    # that belongs to this section. Preserve it after the feature list.
    text_block = legacy_root.find(class_="rich-bullet-list__text")
    if isinstance(text_block, Tag):
        copy_wrap = soup.new_tag("div", **{"class": "kaindl-copy"})
        for child in list(text_block.children):
            if isinstance(child, Tag):
                copy_wrap.append(child.extract())
        if copy_wrap.contents:
            new_section.append(copy_wrap)

    legacy_root.replace_with(new_section)


def _build_item(item: Tag, soup: BeautifulSoup):
    new_li = soup.new_tag("li", **{"class": "page-body__feature-list__item"})

    icon_wrapper = item.find(class_="rich-bullet-list__item-image-wrapper")
    if isinstance(icon_wrapper, Tag):
        icon_img = icon_wrapper.find("img")
        if isinstance(icon_img, Tag):
            span = soup.new_tag("span", **{"class": "page-body__feature-list__icon", "aria-hidden": "true"})
            # migrate_images later rewrites the src/data-src. Re-parent the
            # existing <img> so that rule sees it.
            span.append(icon_img.extract())
            new_li.append(span)

    content = item.find(class_="rich-bullet-list__item-content")
    if not isinstance(content, Tag):
        return None

    body_wrap = soup.new_tag("div", **{"class": "page-body__feature-list__body"})

    headline = content.find(class_="rich-bullet-list__item-headline")
    if isinstance(headline, Tag):
        text = " ".join(headline.get_text(" ", strip=True).split())
        if text:
            h3 = soup.new_tag("h3")
            h3.string = text
            body_wrap.append(h3)

    # Move every remaining child of .rich-bullet-list__item-content except the
    # headline (already handled). Includes .formatted-text which
    # normalize_typography later unwraps.
    for child in list(content.children):
        if isinstance(child, Tag):
            classes = child.get("class") or []
            if "rich-bullet-list__item-headline" in classes:
                continue
            body_wrap.append(child.extract())

    new_li.append(body_wrap)
    return new_li
