"""Associative brief — wiki/keyword expansion, not raw memory dump."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any

from niannian.chat.proactive_scope import ProactiveScope

_KEYWORD_EXPANSIONS: dict[str, tuple[str, ...]] = {
    "夏天": ("游泳", "西瓜", "乘凉", "短袖"),
    "summer": ("swim", "watermelon", "vacation"),
    "衣服": ("搭配", "场合", "季节"),
    "游泳": ("夏天", "泳池", "海边"),
}


@dataclass(frozen=True)
class AssociationBrief:
    lines: tuple[str, ...]
    confidence: float


def build_association_brief(
    scope: ProactiveScope,
    *,
    seeds: list[str],
    wiki_hits: list[dict[str, Any]] | None = None,
) -> AssociationBrief:
    del scope  # namespace reserved for wiki path in M9
    lines: list[str] = []
    seen: set[str] = set()

    for seed in seeds:
        s = (seed or "").strip()
        if not s:
            continue
        key = s.lower()
        for kw, expansions in _KEYWORD_EXPANSIONS.items():
            if kw in s or kw in key:
                for ex in expansions:
                    line = f"{s} → {ex}"
                    if line not in seen:
                        seen.add(line)
                        lines.append(line)

    for hit in wiki_hits or []:
        if not isinstance(hit, dict):
            continue
        title = str(hit.get("title") or hit.get("page_id") or "").strip()
        snippet = str(hit.get("snippet") or hit.get("label") or "").strip()
        if title:
            line = f"wiki:{title}" + (f" — {snippet[:80]}" if snippet else "")
            if line not in seen:
                seen.add(line)
                lines.append(line)

    if not lines and seeds:
        lines.append(f"续聊：{seeds[0]}")

    conf = min(0.9, 0.4 + 0.1 * len(lines))
    return AssociationBrief(lines=tuple(lines[:5]), confidence=conf)
