"""小意规则预检与规则兜底打分。"""

from __future__ import annotations

import re
from typing import Any

_SL5_CONFLICT_KEYWORDS = (
    "推翻共产主义",
    "否定马克思主义",
    "guest数据进三观",
    "反对毛泽东思想",
)

_GUEST_POLLUTION = re.compile(r"guest.*(三观|SL5|价值观)", re.I)

from niannian.soul.firewall import validate_atom_meta


def rules_precheck(
    text: str,
    *,
    values: dict[str, Any] | None = None,
    meta: dict[str, Any] | None = None,
) -> tuple[bool, list[str]]:
    """席 A 硬门禁。返回 (pass, doubts)。"""
    doubts: list[str] = []
    if not text.strip():
        return False, ["empty_proposal"]

    for kw in _SL5_CONFLICT_KEYWORDS:
        if kw in text:
            return False, [f"sl5_conflict:{kw}"]

    if _GUEST_POLLUTION.search(text):
        return False, ["guest_pollution_sl5"]

    atom_meta = meta if isinstance(meta, dict) else {}
    if atom_meta.get("memory_scope") == "object":
        return False, ["object_scope_forbidden"]

    if atom_meta:
        ok, violations = validate_atom_meta(atom_meta)
        if not ok:
            return False, violations

    if values:
        wv = values.get("worldview") if isinstance(values.get("worldview"), dict) else {}
        for neg in wv.get("non_negotiables") or []:
            if neg == "no_object_pollution_to_subject" and "客体" in text and "主体" in text:
                doubts.append("possible_object_pollution")

    if len(text.strip()) < 8:
        doubts.append("too_short")

    return True, doubts


def rules_seat_score(
    text: str,
    *,
    seat: str,
    doubts: list[str],
    values: dict[str, Any] | None = None,
) -> float:
    """LLM 不可用时的 B/C 规则打分。"""
    base = 62.0 if seat == "skeptic" else 58.0
    if len(text) > 40:
        base += 8
    if len(text) > 120:
        base += 5
    base -= 12 * len(doubts)
    if values and seat == "integrator":
        wv = values.get("worldview") if isinstance(values.get("worldview"), dict) else {}
        if wv.get("primary"):
            base += 5
    return max(0.0, min(100.0, round(base, 2)))
