"""Build URL slug + profanity-handling helpers for SEO.

The /b/<code> page is the most-shared surface on the site (every forum
or Discord link to us is a build URL). The slug carries keywords into
the URL itself and improves recognizability when the URL is pasted as
plain text. But user-named slugs can include profanity, which would
embed it into the URL, the og:title, and Google's snippet — bad for
domain reputation and CTR.

Hybrid policy decided 2026-05-31:
  - Slugify the user's build title.
  - Run the title through a profanity filter.
  - If clean → user-named slug.
  - If profane → parts-based slug (deterministic from build composition,
    immune by construction). Also flag the build as noindex so it
    doesn't appear in Google's index; the owner still sees the
    original title on the page.

See docs/seo.md §B + memory: build-URL slug profanity handling.
"""

from __future__ import annotations

import re
from typing import Iterable, List, Optional

from collections import Counter

from .labels import type_label, type_label_for_count

# Cache the profanity censor instance — the library has init cost
# (loads a ~3k-word list) that we don't want to repeat per render.
_censor = None


def _get_censor():
    global _censor
    if _censor is None:
        from better_profanity import profanity
        profanity.load_censor_words()
        _censor = profanity
    return _censor


def is_profane(text: Optional[str]) -> bool:
    """True if `text` contains profanity per the better-profanity
    library's default English word list. Falls back to False if the
    library is unavailable (defensive — never crash a render over a
    missing dependency)."""
    if not text:
        return False
    try:
        return _get_censor().contains_profanity(text)
    except Exception:
        return False


def _slugify(text: Optional[str]) -> str:
    """Lowercase, collapse non-alphanumeric runs to single hyphens,
    strip leading/trailing hyphens, cap at 80 chars to keep URLs
    within Google's typical visible-snippet length."""
    s = (text or "").strip().lower()
    s = re.sub(r"[^a-z0-9]+", "-", s)
    s = re.sub(r"^-+|-+$", "", s)
    return s[:80]


def parts_based_slug(items: Iterable[dict]) -> str:
    """Deterministic slug built from a build's component types.
    Format: `ar-build-<label1>-<label2>-<label3>-<label4>`.

    Uses the human-readable type labels (e.g. "Stripped Uppers" →
    "stripped-uppers") so the slug carries real keywords, not
    internal codes. Capped at 4 distinct types to keep URLs short.
    Empty build → "ar-build".
    """
    types: List[str] = []
    seen = set()
    for it in items or []:
        t = it.get("type") if isinstance(it, dict) else None
        if t and t not in seen:
            seen.add(t)
            types.append(t)
        if len(types) >= 4:
            break

    if not types:
        return "ar-build"

    parts = []
    for t in types:
        lbl = _slugify(type_label(t))
        if lbl:
            parts.append(lbl)
    return "ar-build-" + "-".join(parts) if parts else "ar-build"


def build_slug(title: Optional[str], items: Iterable[dict]) -> str:
    """Hybrid slug for a /b/<code> URL.

    1. If `title` is non-empty AND clean AND slugifies to something
       non-empty: use the user-named version.
    2. Otherwise fall back to a parts-based slug (deterministic from
       the build's items).
    """
    if title:
        candidate = _slugify(title)
        if candidate and not is_profane(title):
            return candidate
    return parts_based_slug(items)


def title_for_meta(head: dict) -> str:
    """The user-facing build title for the page (h1, browser tab).
    Always returns the original — profanity laundering is for crawler-
    visible surfaces (URL, og:title, sitemap inclusion), not for the
    owner's own view of their build. Empty/missing title → 'Untitled build'."""
    return (head.get("title") or "").strip() or "Untitled build"


def _type_counts(items: Iterable[dict]) -> "tuple[list[str], Counter]":
    """Walk the build's items once, return (first-seen-order list of
    type codes, Counter mapping code -> total qty). Quantity (`qty`
    field) is summed so a single row with qty=3 counts as 3 of that
    type — matches a user's natural read of '3 mags'."""
    type_order: List[str] = []
    counts: Counter = Counter()
    for it in items or []:
        t = it.get("type") if isinstance(it, dict) else None
        if not t:
            continue
        if t not in counts:
            type_order.append(t)
        try:
            qty = int(it.get("qty") or 1)
        except (TypeError, ValueError):
            qty = 1
        counts[t] += max(1, qty)
    return type_order, counts


def og_title_for(head: dict, items: Iterable[dict]) -> str:
    """og:title for social previews. If the user-given title is
    profane, replace with a parts-derived title so shared link cards
    don't go viral with the profanity attached to our domain.
    Count-aware labels (singular when only one of that type)."""
    title = head.get("title") or ""
    if title and not is_profane(title):
        return title
    # Profane or missing title → derive a description from parts.
    type_order, counts = _type_counts(items)
    labels = [type_label_for_count(t, counts[t]) for t in type_order[:4]]
    if not labels:
        return "AR build"
    return "AR build with " + ", ".join(labels)


def meta_description_for(head: dict, items: Iterable[dict],
                         total: Optional[float] = None) -> str:
    """Build a ~150-char meta description from the build's contents.
    Format: '<N>-part AR build: <type1>, <type2>, <type3> + N more.
    Total $<X>. Compare at ARPartsFinder.'

    Uses item count + the leading few type labels + total. Type
    labels are count-aware: 'Complete Lower' when there's one of
    that type in the build, 'Complete Lowers' for two or more
    (sums `qty` per row so a single qty=3 row counts as 3).
    Skips item names/companies (too long, too variable) — the type
    breakdown is the searchable substance.
    """
    items_list = list(items or [])
    n = len(items_list)
    type_order, counts = _type_counts(items_list)
    labels = [type_label_for_count(t, counts[t]) for t in type_order[:3]]
    extra_types = max(0, len(type_order) - 3)
    if labels:
        type_part = ", ".join(labels)
        if extra_types:
            type_part += f" + {extra_types} more"
    else:
        type_part = "no items yet"
    pieces = [
        f"{n}-part AR build" if n != 1 else "1-part AR build",
        f": {type_part}" if labels else "",
        f". Total ${total:.0f}" if (total is not None and total > 0) else "",
        ". Compare prices and availability at ARPartsFinder.",
    ]
    return "".join(pieces)[:300]
