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

import re

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

DEFAULT_AI_FONTS: tuple[str, ...] = (
    "Inter",
    "Poppins",
    "Manrope",
    "Geist",
    "Space Grotesk",
    "DM Sans",
    "Plus Jakarta Sans",
)
DECORATIVE_MONOSPACE_FONTS: tuple[str, ...] = ("JetBrains Mono", "Space Mono")
GOOGLE_FONTS_WEIGHTSET_PATTERN = re.compile(
    r"fonts\.googleapis\.com.*family=(Inter|Poppins|Manrope)[^&]*wght@400;500;600;700",
    re.IGNORECASE,
)


def _detect_default_font(fonts: list[dict]) -> Signal | None:
    for sample in fonts:
        family = str(sample.get("fontFamily", ""))
        for candidate in DEFAULT_AI_FONTS:
            if candidate.lower() in family.lower():
                return Signal(
                    "DEFAULT_AI_FONT",
                    f"Default AI-tool font family in use ({candidate})",
                    SEVERITY_WEAK,
                    AXIS_ORIGIN,
                    1.0,
                    0,
                    family[:100],
                )
    return None


def _detect_instrument_serif(fonts: list[dict]) -> Signal | None:
    for sample in fonts:
        family = str(sample.get("fontFamily", ""))
        if "instrument serif" in family.lower():
            return Signal(
                "INSTRUMENT_SERIF_ACCENT",
                "Instrument Serif accent font pairing",
                SEVERITY_WEAK,
                AXIS_ORIGIN,
                1.0,
                0,
                family[:100],
            )
    return None


def _detect_single_font_family(fonts: list[dict]) -> Signal | None:
    families = {str(sample.get("fontFamily", "")).strip() for sample in fonts if sample.get("fontFamily")}
    if len(fonts) >= 2 and len(families) == 1:
        return Signal(
            "SINGLE_FONT_FAMILY",
            "Every sampled element shares one exact font-family declaration",
            SEVERITY_WEAK,
            AXIS_ORIGIN,
            0.5,
            0,
            next(iter(families))[:100],
        )
    return None


def _detect_google_fonts_weightset(links: list[str]) -> Signal | None:
    for href in links:
        match = GOOGLE_FONTS_WEIGHTSET_PATTERN.search(str(href))
        if match:
            return Signal(
                "GOOGLE_FONTS_DEFAULT_WEIGHTSET",
                "Google Fonts request for the canonical AI-tool weight set (400;500;600;700)",
                SEVERITY_MEDIUM,
                AXIS_ORIGIN,
                1.5,
                0,
                str(href)[:150],
            )
    return None


def _detect_decorative_monospace(fonts: list[dict]) -> Signal | None:
    for sample in fonts:
        tag = str(sample.get("tag", ""))
        if tag not in ("h1", "h2", "h3", "button"):
            continue
        family = str(sample.get("fontFamily", ""))
        for candidate in DECORATIVE_MONOSPACE_FONTS:
            if candidate.lower() in family.lower():
                return Signal(
                    "DECORATIVE_MONOSPACE",
                    f"Decorative monospace font used outside code ({candidate})",
                    SEVERITY_WEAK,
                    AXIS_ORIGIN,
                    0.5,
                    0,
                    family[:100],
                )
    return None


@dom_check
def detect_typography_signals(page: DomPageContext) -> list[Signal]:
    fonts = page.dom.get("fonts", []) or []
    links = page.dom.get("links", []) or []
    findings: list[Signal] = []
    for signal in (
        _detect_default_font(fonts),
        _detect_instrument_serif(fonts),
        _detect_single_font_family(fonts),
        _detect_google_fonts_weightset(links),
        _detect_decorative_monospace(fonts),
    ):
        if signal is not None:
            findings.append(signal)
    return findings
