"""Assembly 块 — subject_pack + SL5 values_gate。"""

from __future__ import annotations

from typing import Any

from niannian.soul.firewall import guest_reference_disclaimer
from niannian.soul.values import values_summary


def build_persona_assembly_block(pack) -> str:
    """Persona overlay 块 — 接受 PersonaPack 或同形 duck type。"""
    if getattr(pack, "detached", False):
        return ""
    block = getattr(pack, "prompt_block", "") or ""
    if not str(block).strip():
        return ""
    label = getattr(pack, "label", "") or getattr(pack, "preset_id", "人格")
    return f"[人格·{label}]\n{str(block).strip()}"


def build_values_gate(values: dict[str, Any]) -> dict[str, Any]:
    wv = values.get("worldview") if isinstance(values.get("worldview"), dict) else {}
    return {
        "primary": list(wv.get("primary") or []),
        "non_negotiables": list(wv.get("non_negotiables") or []),
        "guest_reference_only": "guest_data_reference_only" in (wv.get("non_negotiables") or []),
        "summary": values_summary(values),
    }


def build_object_assembly_block(object_id: str, *, snippets: list[str] | None = None) -> str:
    lines = [f"[客体上下文·{object_id}·仅本轮·可空]"]
    if snippets:
        for s in snippets[:5]:
            lines.append(f"- {s[:160]}")
    else:
        lines.append("（本轮无告知记忆）")
    lines.append(guest_reference_disclaimer())
    return "\n".join(lines)


def build_subject_assembly_blocks(pack: dict[str, Any]) -> str:
    """拼 [主体·念念] + [主体三观·SL5] 文本块。"""
    identity = pack.get("identity") if isinstance(pack.get("identity"), dict) else {}
    values = pack.get("values") if isinstance(pack.get("values"), dict) else {}
    emotion = pack.get("emotion") if isinstance(pack.get("emotion"), dict) else {}
    name = identity.get("name") or "念念"
    tone = identity.get("tone") or ""
    mood = emotion.get("mood") or "calm"
    gate = build_values_gate(values)

    lines = [
        f"[主体·{name}]",
        f"口吻：{tone}",
        f"此刻 mood：{mood}",
        "[主体三观·SL5]",
        gate["summary"],
    ]
    return "\n".join(lines)
