from home_agent.contracts.types import Item, ItemKind, RenderedItemText


class DefaultItemTextRenderer:
    def render(self, item: Item) -> RenderedItemText:
        if item.kind == ItemKind.EMAIL:
            snippet = _string_metadata(item.metadata.get("snippet"))
            importance = _string_metadata(item.metadata.get("importance"))
            embedding_parts = [
                "kind=email",
                f"subject={item.subject}",
                f"sender={item.sender}",
            ]
            if snippet:
                embedding_parts.append(f"snippet={snippet}")
            if importance:
                embedding_parts.append(f"importance={importance}")
            summary_parts = [item.subject, f"from {item.sender}"]
            if snippet:
                summary_parts.append(snippet)
            return RenderedItemText(
                provider=item.provider,
                external_id=item.external_id,
                kind=item.kind,
                embedding_text="\n".join(embedding_parts),
                summary_text=" | ".join(summary_parts),
            )

        start_at = _string_metadata(item.metadata.get("start_at"))
        status = _string_metadata(item.metadata.get("status"))
        embedding_parts = [
            "kind=calendar_event",
            f"title={item.subject}",
            f"owner={item.sender}",
        ]
        if start_at:
            embedding_parts.append(f"start_at={start_at}")
        if status:
            embedding_parts.append(f"status={status}")
        summary_parts = [item.subject, f"by {item.sender}"]
        if start_at:
            summary_parts.append(start_at)
        return RenderedItemText(
            provider=item.provider,
            external_id=item.external_id,
            kind=item.kind,
            embedding_text="\n".join(embedding_parts),
            summary_text=" | ".join(summary_parts),
        )


def _string_metadata(value: object) -> str:
    if isinstance(value, str):
        return value.strip()
    return ""
