"""ThalamusGate — 输入归一化 · P1 感知。"""

from __future__ import annotations

import re
from dataclasses import dataclass, field
from typing import Any

from niannian.personas import THALAMUS

_WS = re.compile(r"\s+")


@dataclass(frozen=True)
class NormalizedEvent:
    text: str
    source: str
    channel: str
    trust_tier: str
    flags: frozenset[str] = field(default_factory=frozenset)


class ThalamusGate:
    def __init__(self, config: dict[str, Any] | None = None) -> None:
        self._config = config or {}

    def normalize(
        self,
        raw: str,
        *,
        source: str = "chat",
        session_meta: dict[str, Any] | None = None,
    ) -> NormalizedEvent:
        meta = dict(session_meta or {})
        text = _WS.sub(" ", (raw or "").strip())
        flags: set[str] = set()
        channel = "subject"
        trust = "owner"

        if meta.get("current_object_id"):
            channel = "object"
            flags.add("object_turn")
        if meta.get("guest_session") or meta.get("trust_tier") == "guest_reference":
            trust = "guest_reference"
            flags.add("guest_reference")

        if not text:
            flags.add("empty")

        return NormalizedEvent(
            text=text,
            source=source,
            channel=channel,
            trust_tier=trust,
            flags=frozenset(flags),
        )

    def trace_line(self, event: NormalizedEvent) -> str:
        flag_str = ",".join(sorted(event.flags)) if event.flags else "none"
        return f"[{THALAMUS}] source={event.source} channel={event.channel} trust={event.trust_tier} flags={flag_str}"
