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

from devplacepy.services.jobs.isslop.analysis.domsignals.base import DomPageContext, DomSiteContext, dom_check, dom_site_check
from devplacepy.services.jobs.isslop.analysis.signals import AXIS_QUALITY, SEVERITY_MEDIUM, SEVERITY_WEAK, Signal


def _meta(page: DomPageContext) -> dict:
    meta = page.dom.get("meta", {})
    return meta if isinstance(meta, dict) else {}


@dom_check
def detect_metaseo_signals(page: DomPageContext) -> list[Signal]:
    meta = _meta(page)
    findings: list[Signal] = []
    if not str(meta.get("description") or "").strip():
        findings.append(
            Signal("MISSING_META_DESCRIPTION", "No meta description present", SEVERITY_WEAK, AXIS_QUALITY, 1.0, 0, "")
        )
    if int(page.dom.get("jsonld", 0) or 0) == 0:
        findings.append(
            Signal("MISSING_STRUCTURED_DATA", "No JSON-LD structured data present", SEVERITY_WEAK, AXIS_QUALITY, 0.5, 0, "")
        )
    if not str(meta.get("ogImage") or "").strip():
        findings.append(
            Signal("MISSING_OG_IMAGE", "No og:image meta tag present", SEVERITY_WEAK, AXIS_QUALITY, 0.5, 0, "")
        )
    if not meta.get("favicon"):
        findings.append(
            Signal("MISSING_FAVICON", "No favicon link present", SEVERITY_WEAK, AXIS_QUALITY, 0.5, 0, "")
        )
    if not str(meta.get("htmlLang") or "").strip():
        findings.append(
            Signal("MISSING_HTML_LANG", "No html lang attribute present", SEVERITY_WEAK, AXIS_QUALITY, 0.5, 0, "")
        )
    if not str(meta.get("canonical") or "").strip():
        findings.append(
            Signal("MISSING_CANONICAL", "No canonical link present", SEVERITY_WEAK, AXIS_QUALITY, 0.5, 0, "")
        )
    return findings


@dom_site_check
def detect_duplicate_meta_description(site: DomSiteContext) -> list[Signal]:
    if len(site.pages) < 2:
        return []
    counts: dict[str, int] = {}
    for page in site.pages:
        description = str(_meta(page).get("description") or "").strip()
        if description:
            counts[description] = counts.get(description, 0) + 1
    for description, count in counts.items():
        if count >= 2:
            return [
                Signal(
                    "DUPLICATE_META_DESCRIPTION",
                    "Identical meta description reused across multiple pages",
                    SEVERITY_MEDIUM,
                    AXIS_QUALITY,
                    1.5,
                    0,
                    description[:150],
                )
            ]
    return []
