"""VP daily incremental assembly distill — append turn summaries to Daily notes."""

from __future__ import annotations

from datetime import datetime, timezone
from typing import TYPE_CHECKING, Callable

from niannian.virtual_persona.assembly_master import (
    DAILY_NOTES_HEADING,
    DEFAULT_DAILY_APPEND_CHARS,
    append_section_body,
)
from niannian.virtual_persona.pack import read_pack
from niannian.virtual_persona.stage import get_stage

if TYPE_CHECKING:
    from niannian.virtual_persona.store import VirtualPersonaStore

DISTILL_STAGES = frozenset({"daily", "perfect"})

SummarizeFn = Callable[[str, str], str]


def _now_iso() -> str:
    return datetime.now(timezone.utc).isoformat()


def _default_summarize(user_text: str, reply: str) -> str:
    user = (user_text or "").strip()
    assistant = (reply or "").strip()
    if len(user) > 120:
        user = user[:117] + "..."
    if len(assistant) > 120:
        assistant = assistant[:117] + "..."
    parts: list[str] = []
    if user:
        parts.append(f"用户：{user}")
    if assistant:
        parts.append(f"回复：{assistant}")
    if not parts:
        return ""
    return f"[{_now_iso()}] " + " · ".join(parts)


def stage_allows_distill(stage: str) -> bool:
    return str(stage or "").strip() in DISTILL_STAGES


def maybe_distill_turn(
    store: VirtualPersonaStore,
    vp_id: str,
    *,
    user_text: str,
    reply: str,
    pack_stage: str | None = None,
    summarize_fn: SummarizeFn | None = None,
    max_append_chars: int = DEFAULT_DAILY_APPEND_CHARS,
) -> bool:
    stage = pack_stage if pack_stage is not None else get_stage(store, vp_id)
    if not stage_allows_distill(stage):
        return False

    fn = summarize_fn or _default_summarize
    summary = fn(user_text, reply).strip()
    if not summary:
        return False

    pack = read_pack(store, vp_id)
    locked = pack.get("locked_sections")
    locked_list = list(locked) if isinstance(locked, list) else None

    return append_section_body(
        store,
        vp_id,
        DAILY_NOTES_HEADING,
        summary,
        max_append_chars=max_append_chars,
        locked_sections=locked_list,
    )
