from __future__ import annotations

from typing import Optional, List, TYPE_CHECKING

from analogai.foundation.core.value_objects.attribute import Attribute

if TYPE_CHECKING:
    from analogai.foundation.modules.notion.notion import Notion
    from analogai.foundation.common.dtos.notion_expression import NotionExpression


def _format_attribute(attribute: Attribute) -> Optional[str]:
    if attribute is None:
        return None
    tag = attribute.tag
    value = attribute.value
    unit = attribute.unit
    if tag is None and value is None:
        return None
    if value is None:
        return str(tag)
    if unit:
        return f"{tag} {value} {unit}"
    return f"{tag} {value}"


def serialize_notion(
    caption: str,
    attributes: Optional[List[Attribute]] = None,
) -> str:
    caption = caption.strip() if caption else ""
    if not attributes:
        return caption
    parts: List[str] = []
    for attribute in attributes:
        formatted = _format_attribute(attribute)
        if formatted:
            parts.append(formatted)
    if not parts:
        return caption
    return f"{caption} has {', '.join(parts)}"


def serialize_notion_entity(notion: "Notion") -> str:
    return serialize_notion(notion.caption, notion.attributes)


def serialize_notion_expression(expression: "NotionExpression") -> str:
    return serialize_notion(expression.caption, expression.attributes)


__all__ = [
    "serialize_notion",
    "serialize_notion_entity",
    "serialize_notion_expression",
]
