"""Structured answer contract shared across server, desktop, and widget runtimes."""

from __future__ import annotations

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


@dataclass
class StructuredAnswerContract:
    """Canonical answer payload produced by composers and consumed by renderers."""

    title: str = ""
    body_md: str = ""
    sources: list[str] = field(default_factory=list)
    level: str = ""
    quality_meta: dict[str, Any] = field(default_factory=dict)

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, payload: dict[str, Any] | None) -> StructuredAnswerContract:
        data = dict(payload or {})
        sources = data.get("sources")
        quality_meta = data.get("quality_meta")
        return cls(
            title=str(data.get("title") or ""),
            body_md=str(data.get("body_md") or data.get("answer") or data.get("body") or ""),
            sources=[str(item) for item in sources] if isinstance(sources, list) else [],
            level=str(data.get("level") or ""),
            quality_meta=dict(quality_meta) if isinstance(quality_meta, dict) else {},
        )

    @classmethod
    def from_text(
        cls,
        text: str,
        *,
        title: str = "",
        sources: list[str] | None = None,
        level: str = "",
        quality_meta: dict[str, Any] | None = None,
    ) -> StructuredAnswerContract:
        return cls(
            title=str(title or ""),
            body_md=str(text or ""),
            sources=list(sources or []),
            level=str(level or ""),
            quality_meta=dict(quality_meta or {}),
        )

    def render_body(self) -> str:
        """Return body suitable for channel renderers (title stripped from body when duplicated)."""
        return str(self.body_md or "").strip()
