"""Rule-based page classifier: determines page class and product role."""

from __future__ import annotations

import logging
from typing import Any

log = logging.getLogger("crawler.classifier")

_CONFIGURATOR_KEYWORDS_EN = {
    "customize this product", "configure", "configurator", "technical data",
    "design", "light", "complete", "choose your color", "size", "sensor",
    "plug", "diffuser", "light emission", "colourtemperature", "color temperature",
    "product sketch", "article number", "degree of protection", "luminous flux",
    "power consumption", "efficacy", "beam angle", "light distribution curve",
    "connection", "length", "width", "height",
}
_CONFIGURATOR_KEYWORDS_DE = {
    "konfigurieren", "konfigurator", "technische daten", "farbe", "groesse",
    "sensor", "stecker", "diffusor", "lichtaustritt", "artikelnr",
    "auswaehlen", "lichtfarbe", "schutzart", "leistungsaufnahme",
    "lichtstrom", "abstrahlwinkel", "anschluss", "laenge", "breite", "hoehe",
    "konfiguration", "schritt",
}

_CATALOGUE_KEYWORDS = {
    "product categories", "application", "product families",
    "search products in this category", "detail filter", "efficiency",
    "length", "colour", "colour temperature", "control", "luminous flux",
    "power", "mounting type", "product category", "product type",
    "segment", "crafted for",
}

_PRODUCT_DETAIL_KEYWORDS = {
    "quickinfo", "products and codes", "downloads and links",
    "aggregated downloads", "description", "simple drawing",
    "light distribution", "article number", "mounting set", "colour",
    "product codes", "downloads", "technical specifications",
    "specifications", "product details",
}

_MODAL_CONTENT_KEYWORDS = {
    "configure now", "most configured", "all about", "discover family",
    "learn more", "explore", "view details", "show more",
}


def classify_page(
    url: str = "",
    title: str = "",
    visible_text: str = "",
    links: list[dict[str, str]] | None = None,
    headings: list[str] | None = None,
) -> dict[str, Any]:
    text_lower = visible_text.lower()
    title_lower = title.lower()

    link_texts = {l.get("text", "").lower() for l in (links or []) if l.get("text")}
    headings_set = {h.lower() for h in (headings or []) if h}

    # --- Signal scoring ---
    config_score = 0
    catalogue_score = 0
    product_score = 0

    for kw in _CONFIGURATOR_KEYWORDS_EN:
        if kw in text_lower:
            config_score += 1
    for kw in _CONFIGURATOR_KEYWORDS_DE:
        if kw in text_lower:
            config_score += 1

    for kw in _CATALOGUE_KEYWORDS:
        if kw in text_lower:
            catalogue_score += 1

    for kw in _PRODUCT_DETAIL_KEYWORDS:
        if kw in text_lower:
            product_score += 1

    # Link-based signals
    config_links = sum(1 for t in link_texts if any(kw in t for kw in ("configure", "configurator", "customize")))
    catalogue_links = sum(1 for t in link_texts if any(kw in t for kw in ("all products", "categories", "filter")))
    product_links = sum(1 for t in link_texts if any(kw in t for kw in ("family", "downloads", "products and codes")))

    config_score += config_links * 2
    catalogue_score += catalogue_links * 2
    product_score += product_links * 2

    # Heading signals
    for h in headings_set:
        if any(kw in h for kw in _CONFIGURATOR_KEYWORDS_EN):
            config_score += 2
        if any(kw in h for kw in _CATALOGUE_KEYWORDS):
            catalogue_score += 2
        if any(kw in h for kw in _PRODUCT_DETAIL_KEYWORDS):
            product_score += 2

    # URL-based signals
    url_lower = url.lower()
    if "/configurator" in url_lower or "/configure" in url_lower:
        config_score += 5
    if "/product" in url_lower:
        product_score += 3
    if any(p in url_lower for p in ("/category", "/listing", "/filter", "/catalogue")):
        catalogue_score += 3
    if "/p/" in url_lower or ("/products" in url_lower and "/c/" not in url_lower):
        product_score += 4
    if "/c/" in url_lower:
        catalogue_score += 4

    # --- Decision tree ---
    if config_score >= 6:
        page_class = "product_configurator_entry"
        product = True
        product_page_role = "product_configurator_entry"
        confidence = min(0.85, 0.5 + config_score * 0.05)
    elif catalogue_score >= 5 and product_score < catalogue_score:
        page_class = "catalogue_context_page"
        product = False
        product_page_role = "catalogue_context"
        confidence = min(0.85, 0.5 + catalogue_score * 0.05)
        has_product_catalogue = True
    elif product_score >= 4 and product_score >= catalogue_score:
        page_class = "product_family_page" if "family" in text_lower else "product_detail_page"
        product = True
        product_page_role = page_class
        confidence = min(0.85, 0.5 + product_score * 0.05)
    else:
        page_class = "normal_page"
        product = False
        product_page_role = "none"
        confidence = max(0.3, 0.8 - (config_score + catalogue_score + product_score) * 0.05)

    result = {
        "page_class": page_class,
        "product": product,
        "has_product_catalogue": catalogue_score >= 3 and product_score < catalogue_score,
        "product_page_role": product_page_role,
        "confidence": round(confidence, 2),
        "signals": {
            "configurator": config_score,
            "catalogue": catalogue_score,
            "product": product_score,
        },
        "classified_by": "rule_based",
    }

    log.info("Page classifier: %s -> %s (conf=%.2f, signals: c=%d cat=%d prod=%d)",
             url[:80], page_class, confidence, config_score, catalogue_score, product_score)
    return result
