from __future__ import annotations
from datetime import datetime, timezone
from typing import Optional
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy import BigInteger, Text, String, DateTime, Boolean, Integer, ForeignKey
from src.utils.db import Base


class ChatThread(Base):
    """Chat thread model for organizing conversations."""
    __tablename__ = "chat_threads"
    
    id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
    store_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
    branch_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
    user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
    
    # Thread metadata
    title: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
    description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
    thread_type: Mapped[str] = mapped_column(String(50), default="general")  # general, support, sales, etc.
    
    # Thread status
    is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default='true')
    is_archived: Mapped[bool] = mapped_column(Boolean, default=False, server_default='false')
    
    # System fields
    created_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.now(timezone.utc))
    updated_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.now(timezone.utc))
    
    # Relationships
    messages: Mapped[list["ChatMessage"]] = relationship("ChatMessage", back_populates="thread", cascade="all, delete-orphan")


class ChatMessage(Base):
    """Individual chat messages within a thread."""
    __tablename__ = "chat_messages"
    
    id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
    thread_id: Mapped[int] = mapped_column(BigInteger, ForeignKey("chat_threads.id"), nullable=False)
    user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
    
    # Message content
    role: Mapped[str] = mapped_column(String(20), nullable=False)  # user, assistant, system
    content: Mapped[str] = mapped_column(Text, nullable=False)
    
    # Message metadata
    message_type: Mapped[str] = mapped_column(String(50), default="text")  # text, image, file
    image_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)  # URL for generated images
    tokens_used: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
    model_used: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
    
    # System fields
    created_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.now(timezone.utc))
    updated_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.now(timezone.utc))
    is_deleted: Mapped[bool] = mapped_column(Boolean, default=False, server_default='false')
    
    # Relationships
    thread: Mapped["ChatThread"] = relationship("ChatThread", back_populates="messages")
