# retoor <retoor@molodetz.nl>
from __future__ import annotations

from devplacepy.services.jobs.isslop.analysis.domsignals.base import DomPageContext, dom_check
from devplacepy.services.jobs.isslop.analysis.signals import (
    AXIS_ORIGIN,
    AXIS_QUALITY,
    SEVERITY_MEDIUM,
    SEVERITY_WEAK,
    Signal,
)

LANDING_SECTION_TOKENS: tuple[str, ...] = ("hero", "features", "testimonials", "pricing", "faq", "cta")
LANDING_SECTION_THRESHOLD: int = 4
DEAD_ANCHOR_THRESHOLD: int = 5
REPEATED_CARD_THRESHOLD: int = 3


def _detect_landing_template(class_names: dict) -> Signal | None:
    matched = {
        token
        for token in LANDING_SECTION_TOKENS
        if any(token in name.lower() for name in class_names)
    }
    if len(matched) < LANDING_SECTION_THRESHOLD:
        return None
    return Signal(
        "LANDING_TEMPLATE_DOM",
        "Canonical hero-features-testimonials-pricing landing structure in the rendered DOM",
        SEVERITY_MEDIUM,
        AXIS_ORIGIN,
        2.0,
        0,
        ", ".join(sorted(matched)),
    )


def _detect_glassmorphic_navbar(samples: list[dict]) -> Signal | None:
    for sample in samples:
        tag = str(sample.get("tag", ""))
        if tag not in ("nav", "header"):
            continue
        blob = " ".join(
            str(sample.get(field, "")) for field in ("backgroundImage", "backgroundColor", "boxShadow")
        ).lower()
        if "blur(" not in blob:
            continue
        if "rgba(" in blob or "hsla(" in blob:
            return Signal(
                "GLASSMORPHIC_NAVBAR",
                "Glassmorphic translucent-blur navigation bar",
                SEVERITY_WEAK,
                AXIS_ORIGIN,
                1.0,
                0,
                blob[:150],
            )
    return None


def _detect_repeated_card_class(class_names: dict) -> Signal | None:
    for name, count in class_names.items():
        if count >= REPEATED_CARD_THRESHOLD:
            return Signal(
                "REPEATED_CARD_CLASS",
                f"Class token repeated across {count} elements, a generated card-grid shape",
                SEVERITY_WEAK,
                AXIS_ORIGIN,
                1.0,
                0,
                f"{name} x{count}",
            )
    return None


def _detect_dead_anchor_links(dead_anchor_count: int) -> Signal | None:
    if dead_anchor_count < DEAD_ANCHOR_THRESHOLD:
        return None
    return Signal(
        "DEAD_ANCHOR_LINKS_DOM",
        f'{dead_anchor_count} rendered links pointing to href="#"',
        SEVERITY_MEDIUM,
        AXIS_QUALITY,
        1.0,
        0,
        f"{dead_anchor_count} placeholder links",
    )


@dom_check
def detect_layout_signals(page: DomPageContext) -> list[Signal]:
    class_names = page.dom.get("classNames", {}) or {}
    colors = page.dom.get("colors", []) or []
    dead_anchor_count = int(page.dom.get("deadAnchorCount", 0) or 0)
    findings: list[Signal] = []
    for signal in (
        _detect_landing_template(class_names),
        _detect_glassmorphic_navbar(colors),
        _detect_repeated_card_class(class_names),
        _detect_dead_anchor_links(dead_anchor_count),
    ):
        if signal is not None:
            findings.append(signal)
    return findings
