"""NER domain ↔ ORM converters."""

from __future__ import annotations

from typing import TYPE_CHECKING

from noteflow.domain.entities.named_entity import EntityCategory, NamedEntity
from noteflow.domain.value_objects import MeetingId

if TYPE_CHECKING:
    from noteflow.infrastructure.persistence.models import NamedEntityModel


class NerConverter:
    """Convert between NamedEntity domain objects and ORM models."""

    @staticmethod
    def orm_to_domain(model: NamedEntityModel) -> NamedEntity:
        """Convert ORM model to domain entity.

        Args:
            model: SQLAlchemy NamedEntityModel instance.

        Returns:
            Domain NamedEntity with validated and normalized fields.

        Raises:
            ValueError: If model data is invalid (e.g., confidence out of range).
        """
        # Validate and convert segment_ids to ensure it's a proper list
        segment_ids = list(model.segment_ids) if model.segment_ids else []

        # Create domain entity - validation happens in __post_init__
        return NamedEntity(
            id=model.id,
            meeting_id=MeetingId(model.meeting_id),
            text=model.text,
            normalized_text=model.normalized_text,
            category=EntityCategory(model.category),
            segment_ids=segment_ids,
            confidence=model.confidence,
            is_pinned=model.is_pinned,
            db_id=model.id,
        )

    @staticmethod
    def to_orm_kwargs(entity: NamedEntity) -> dict[str, object]:
        """Convert domain entity to ORM model kwargs.

        Returns a dict of kwargs rather than instantiating NamedEntityModel
        directly to avoid circular imports and allow the repository to
        handle ORM construction.

        Args:
            entity: Domain NamedEntity.

        Returns:
            Kwargs dict for NamedEntityModel construction.
        """
        return {
            "id": entity.id,
            "meeting_id": entity.meeting_id,
            "text": entity.text,
            "normalized_text": entity.normalized_text,
            "category": entity.category.value,
            "segment_ids": entity.segment_ids,
            "confidence": entity.confidence,
            "is_pinned": entity.is_pinned,
        }
