from __future__ import annotations

from typing import Any

from niannian.cognitive.planes import (
    DEFAULT_COMPANION_PLANES,
    DEFAULT_EDUCATION_PLANES,
    DEFAULT_HYBRID_PLANES,
    DEFAULT_WORK_PLANES,
    PlanePack,
    Regime,
)
from niannian.personas import JUDGMENT


class PlanePackGate:
    """PlanePack 运行时门禁 — honor active/skip。"""

    def __init__(self, pack: PlanePack) -> None:
        self._pack = pack

    @classmethod
    def from_session_meta(cls, meta: dict[str, Any]) -> PlanePackGate:
        tp = meta.get("turn_policy") if isinstance(meta.get("turn_policy"), dict) else {}
        regime = str(tp.get("regime") or meta.get("regime") or "companion")
        if regime not in ("companion", "work", "hybrid", "education"):
            regime = "companion"
        active_raw = [str(x) for x in (tp.get("planes") or []) if isinstance(x, str)]
        if active_raw:
            active = frozenset(active_raw)
        elif regime == "work":
            active = DEFAULT_WORK_PLANES
        elif regime == "hybrid":
            active = DEFAULT_HYBRID_PLANES
        elif regime == "education":
            active = DEFAULT_EDUCATION_PLANES
        else:
            active = DEFAULT_COMPANION_PLANES
        skip = frozenset(str(x) for x in (tp.get("skip") or []) if isinstance(x, str))
        return cls(PlanePack(regime=regime, active=active, skip=skip))  # type: ignore[arg-type]

    def allows(self, plane_id: str) -> bool:
        return self._pack.is_active(plane_id)

    def trace_skip(self, plane_id: str, reason: str = "plane_pack") -> str:
        return f"[{JUDGMENT}] skip {plane_id} ({reason})"
