import uuid
from datetime import datetime, timezone
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint, desc
from sqlalchemy.dialects.postgresql import UUID, JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship
from infrastructure.database.base import Base, UUIDPrimaryKeyMixin, TimestampMixin


class BotMessageTemplate(Base, UUIDPrimaryKeyMixin, TimestampMixin):
    __tablename__ = "bot_message_templates"

    tenant_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("tenants.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    bot_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("bots.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    message_key: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
    title: Mapped[str] = mapped_column(String(255), nullable=False)
    message_text: Mapped[str] = mapped_column(Text, nullable=False)
    parse_mode: Mapped[str] = mapped_column(String(20), default="HTML", nullable=False)
    media_type: Mapped[str] = mapped_column(String(20), default="none", nullable=False)
    media_file_id: Mapped[str | None] = mapped_column(String(512), nullable=True)
    locale: Mapped[str] = mapped_column(String(10), default="en", nullable=False, index=True)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    is_draft: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    current_version: Mapped[int] = mapped_column(Integer, default=1, nullable=False)

    # Relationships
    buttons: Mapped[list["BotMessageButton"]] = relationship(
        "BotMessageButton",
        back_populates="template",
        cascade="all, delete-orphan",
        order_by="BotMessageButton.row_position, BotMessageButton.column_position, BotMessageButton.sort_order",
        lazy="selectin",
    )
    versions: Mapped[list["BotMessageVersion"]] = relationship(
        "BotMessageVersion",
        back_populates="template",
        cascade="all, delete-orphan",
        order_by=lambda: desc(BotMessageVersion.version),
        lazy="selectin",
    )

    __table_args__ = (
        UniqueConstraint("bot_id", "message_key", "locale", name="uq_bot_msg_template_key_locale"),
    )


class BotMessageButton(Base, UUIDPrimaryKeyMixin, TimestampMixin):
    __tablename__ = "bot_message_buttons"

    template_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("bot_message_templates.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    text: Mapped[str] = mapped_column(String(255), nullable=False)
    button_type: Mapped[str] = mapped_column(String(30), default="callback_data", nullable=False)
    action_value: Mapped[str] = mapped_column(String(512), nullable=False)
    row_position: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    column_position: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    sort_order: Mapped[int] = mapped_column(Integer, default=0, nullable=False)

    template: Mapped["BotMessageTemplate"] = relationship("BotMessageTemplate", back_populates="buttons")


class BotMessageVersion(Base, UUIDPrimaryKeyMixin):
    __tablename__ = "bot_message_versions"

    template_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("bot_message_templates.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    version: Mapped[int] = mapped_column(Integer, nullable=False)
    snapshot_json: Mapped[dict] = mapped_column(JSONB, nullable=False)
    updated_by: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("users.id", ondelete="SET NULL"),
        nullable=True,
    )
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        default=lambda: datetime.now(timezone.utc),
        nullable=False,
    )

    template: Mapped["BotMessageTemplate"] = relationship("BotMessageTemplate", back_populates="versions")
