"""Convert section-local TYPO3 scope navigation into page-body tabs."""

from __future__ import annotations

from bs4 import BeautifulSoup, Tag

from . import TransformContext


CAREERS_SCOPE = {
    "keys": {
        "/en/careers/",
        "/en/careers/job-offers/",
        "/en/careers/apprenticeships-kaindl/",
        "/en/careers/application/",
    },
    "intro": (
        "<strong>Boards, Floors, Careers – working for Kaindl.</strong> "
        "Our workforce of some 800 employees is characterised by more than technical competence. "
        "We all share a passion for our innovative products, our respective professions and wood "
        "as the material we work with. We are always forging new paths together as the world "
        "market leader in flooring and interior design. Would you like to be a part of it? "
        "Then we look forward to meeting you!"
    ),
    "links": [
        ("Careers", "/en/careers/"),
        ("Job offers", "/en/careers/job-offers/"),
        ("Apprenticeships @ Kaindl", "/en/careers/apprenticeships-kaindl/"),
        ("Application", "/en/careers/application/"),
    ],
    "intro_by_key": {
        "/en/careers/": (
            "<strong>Boards, Floors, Careers – working for Kaindl.</strong> "
            "Our workforce of some 800 employees is characterised by more than technical competence. "
            "We all share a passion for our innovative products, our respective professions and wood "
            "as the material we work with. We are always forging new paths together as the world "
            "market leader in flooring and interior design. Would you like to be a part of it? "
            "Then we look forward to meeting you!"
        ),
        "/en/careers/job-offers/": (
            "<strong>Are you interested in a career at Kaindl?</strong> "
            "You can find all the open positions at our plants in Wals/Salzburg and Lungötz here. "
            "Simply submit your application via our career portal. We look forward to hearing from you!"
        ),
        "/en/careers/apprenticeships-kaindl/": (
            "<strong>Aim high – with an apprenticeship at Kaindl.</strong> "
            "Are you interested in an apprenticeship in a specific craft? Or perhaps in the field "
            "of technology or commerce? Would you like an apprenticeship with exciting and interesting "
            "tasks and friendly colleagues? Then Kaindl is the right place for you."
        ),
        "/en/careers/application/": (
            "<strong>Get your dream job with the right application.</strong> "
            "Do you want to apply for a job at Kaindl? We'll show you what you should pay attention "
            "to in your application and what steps you will take during the application process."
        ),
    },
}


DOWNLOADS_SCOPE = {
    "keys": {
        "/en/service-knowledge/downloads/",
        "/en/service-knowledge/downloads/brochures/",
        "/en/service-knowledge/downloads/factsheets/",
        "/en/service-knowledge/downloads/technical-downloads-boards/",
        "/en/service-knowledge/downloads/technical-downloads-floors/",
        "/en/service-knowledge/downloads/ukca/",
        "/en/service-knowledge/downloads/dop/",
        "/en/service-knowledge/downloads/installation-instructions/",
        "/en/service-knowledge/downloads/tenderspecifications/",
    },
    "intro": "",
    "links": [
        ("Downloads", "/en/service-knowledge/downloads/"),
        ("Brochures", "/en/service-knowledge/downloads/brochures/"),
        ("Fact sheets", "/en/service-knowledge/downloads/factsheets/"),
        ("Technical Downloads BOARDS", "/en/service-knowledge/downloads/technical-downloads-boards/"),
        ("Technical Downloads FLOORS", "/en/service-knowledge/downloads/technical-downloads-floors/"),
        ("UKCA", "/en/service-knowledge/downloads/ukca/"),
        ("DOPs", "/en/service-knowledge/downloads/dop/"),
        ("Installation Instructions", "/en/service-knowledge/downloads/installation-instructions/"),
        ("Tender Specifications", "/en/service-knowledge/downloads/tenderspecifications/"),
    ],
    "intro_by_key": {},
    "force_rebuild": True,
}


def transform(soup: BeautifulSoup, ctx: TransformContext) -> None:
    for root in list(soup.find_all(class_="scope-navigation")):
        if not isinstance(root, Tag):
            continue
        replacement = _build_scope_block(
            soup,
            ctx,
            _extract_links(root),
            _extract_intro(root),
        )
        root.replace_with(replacement)

    if ctx.source_key in CAREERS_SCOPE["keys"]:
        _ensure_scope_navigation(soup, ctx, CAREERS_SCOPE)
    if ctx.source_key in DOWNLOADS_SCOPE["keys"]:
        _ensure_scope_navigation(soup, ctx, DOWNLOADS_SCOPE)


def _extract_links(root: Tag) -> list[tuple[str, str]]:
    links: list[tuple[str, str]] = []
    for anchor in root.select(".scope-navigation__items a[href]"):
        text = " ".join(anchor.get_text(" ", strip=True).split())
        href = str(anchor.get("href") or "").strip()
        if text and href:
            links.append((text, href))
    return links


def _extract_intro(root: Tag) -> str:
    clone = BeautifulSoup(str(root), "html.parser")
    for nav in clone.select(".scope-navigation__items"):
        nav.decompose()
    text_container = clone.find(class_="formatted-text") or clone
    parts = []
    for child in text_container.find_all(["p", "strong"], recursive=True):
        text = " ".join(child.get_text(" ", strip=True).split())
        if text:
            parts.append(text)
    return " ".join(dict.fromkeys(parts))


def _ensure_scope_navigation(soup: BeautifulSoup, ctx: TransformContext, scope: dict) -> None:
    existing = soup.find(class_="page-body__scope-nav")
    if existing is not None and not scope.get("force_rebuild", False):
        return
    if existing is not None:
        wrapper = existing.find_parent(class_="page-body__section")
        target = wrapper or existing.find_parent(class_="page-body__scope-nav-block") or existing
        target.decompose()

    intro = scope["intro_by_key"].get(ctx.source_key, scope.get("intro", ""))
    intro_position = scope.get("intro_position", "below")
    block = _build_scope_block(soup, ctx, scope["links"], intro, intro_position)

    article = soup.find("article", class_="page-body")
    if isinstance(article, Tag):
        section = soup.new_tag(
            "section",
            **{"class": "page-body__section section-spacer page-body__scope-nav-section"},
        )
        section.append(block)
        article.insert(0, section)
    else:
        first = next((child for child in soup.children if isinstance(child, Tag)), None)
        if first is not None:
            first.insert_before(block)
        else:
            soup.append(block)


def _build_scope_block(
    soup: BeautifulSoup,
    ctx: TransformContext,
    links: list[tuple[str, str]],
    intro: str,
    intro_position: str = "below",
) -> Tag:
    block = soup.new_tag("div", **{"class": "page-body__scope-nav-block"})

    intro_wrap = None
    if intro:
        intro_wrap = soup.new_tag("div", **{"class": "page-body__scope-nav-intro kaindl-copy"})
        p = BeautifulSoup(f"<p>{intro}</p>", "html.parser").p
        if p is not None:
            intro_wrap.append(p)

    nav = soup.new_tag("nav", **{"class": "page-body__scope-nav", "aria-label": "Section navigation"})
    ul = soup.new_tag("ul", **{"class": "page-body__scope-nav-list"})

    for text, href in links:
        li_classes = ["page-body__scope-nav-item"]
        if _is_active(ctx.source_key, href):
            li_classes.append("is-active")
        li = soup.new_tag("li", **{"class": " ".join(li_classes)})
        a = soup.new_tag("a", href=href, **{"class": "page-body__scope-nav-link"})
        a.string = text
        li.append(a)
        ul.append(li)

    nav.append(ul)

    if intro_position == "above" and intro_wrap is not None:
        block.append(intro_wrap)
        block.append(nav)
    else:
        block.append(nav)
        if intro_wrap is not None:
            block.append(intro_wrap)

    return block


def _is_active(source_key: str, href: str) -> bool:
    normalized = href if href.startswith("/en/") else f"/en{href}"
    if not normalized.endswith("/"):
        normalized += "/"
    return normalized == source_key
