"""Speaker identity models."""

from __future__ import annotations

from datetime import datetime
from typing import TYPE_CHECKING
from uuid import UUID as PyUUID
from uuid import uuid4

from sqlalchemy import DateTime, ForeignKey, String, Text, UniqueConstraint
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship

from noteflow.domain.utils.time import utc_now

from .._base import Base

if TYPE_CHECKING:
    from noteflow.infrastructure.persistence.models.core.meeting import MeetingModel
    from noteflow.infrastructure.persistence.models.identity.identity import (
        WorkspaceModel,
    )
    from noteflow.infrastructure.persistence.models.organization.task import TaskModel


class PersonModel(Base):
    """Represent a known person (speaker identity) in a workspace.

    Enables cross-meeting speaker recognition once voice embeddings are added.
    """

    __tablename__ = "persons"
    __table_args__: tuple[UniqueConstraint, dict[str, str]] = (
        UniqueConstraint("workspace_id", "email", name="persons_unique_email_per_workspace"),
        {"schema": "noteflow"},
    )

    id: Mapped[PyUUID] = mapped_column(
        UUID(as_uuid=True),
        primary_key=True,
        default=uuid4,
    )
    workspace_id: Mapped[PyUUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("noteflow.workspaces.id", ondelete="CASCADE"),
        nullable=False,
    )
    display_name: Mapped[str] = mapped_column(Text, nullable=False)
    email: Mapped[str | None] = mapped_column(Text, nullable=True)
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        nullable=False,
        default=utc_now,
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        nullable=False,
        default=utc_now,
        onupdate=utc_now,
    )
    metadata_: Mapped[dict[str, object]] = mapped_column(
        "metadata",
        JSONB,
        nullable=False,
        default=dict,
    )

    # Relationships
    workspace: Mapped[WorkspaceModel] = relationship(
        "WorkspaceModel",
        back_populates="persons",
    )
    meeting_speakers: Mapped[list[MeetingSpeakerModel]] = relationship(
        "MeetingSpeakerModel",
        back_populates="person",
    )
    assigned_tasks: Mapped[list[TaskModel]] = relationship(
        "TaskModel",
        back_populates="assignee_person",
    )


class MeetingSpeakerModel(Base):
    """Map speaker labels to display names and persons within a meeting."""

    __tablename__ = "meeting_speakers"
    __table_args__: dict[str, str] = {"schema": "noteflow"}

    meeting_id: Mapped[PyUUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("noteflow.meetings.id", ondelete="CASCADE"),
        primary_key=True,
    )
    speaker_id: Mapped[str] = mapped_column(String(50), primary_key=True)
    display_name: Mapped[str | None] = mapped_column(Text, nullable=True)
    person_id: Mapped[PyUUID | None] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("noteflow.persons.id", ondelete="SET NULL"),
        nullable=True,
    )
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        nullable=False,
        default=utc_now,
    )

    # Relationships
    meeting: Mapped[MeetingModel] = relationship(
        "MeetingModel",
        back_populates="speakers",
    )
    person: Mapped[PersonModel | None] = relationship(
        "PersonModel",
        back_populates="meeting_speakers",
    )
