from datetime import datetime
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Boolean, JSON, Table
from sqlalchemy.orm import relationship
from ..database import Base

session_skills = Table('session_skills', Base.metadata,
    Column('session_id', Integer, ForeignKey('sessions.id', ondelete="CASCADE"), primary_key=True),
    Column('skill_id', Integer, ForeignKey('skills.id', ondelete="CASCADE"), primary_key=True)
)

class Session(Base):
    __tablename__ = 'sessions'

    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(String, ForeignKey('users.id'), index=True, nullable=False)
    title = Column(String, index=True, nullable=True)
    provider_name = Column(String, nullable=True)
    model_name = Column(String, nullable=True)
    stt_provider_name = Column(String, nullable=True)
    tts_provider_name = Column(String, nullable=True)
    feature_name = Column(String, default="default", nullable=False)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    is_archived = Column(Boolean, default=False, nullable=False)
    is_cancelled = Column(Boolean, default=False, nullable=False)
    
    sync_workspace_id = Column(String, nullable=True, index=True)
    attached_node_ids = Column(JSON, default=[], nullable=True)
    node_sync_status = Column(JSON, default={}, nullable=True)
    sync_config = Column(JSON, default={}, nullable=True)
    
    restrict_skills = Column(Boolean, default=False, nullable=False)
    allowed_skill_names = Column(JSON, default=[], nullable=True)
    system_prompt_override = Column(Text, nullable=True)
    is_locked = Column(Boolean, default=False, nullable=False)
    auto_clear_history = Column(Boolean, default=False, nullable=False)

    messages = relationship("Message", back_populates="session", cascade="all, delete-orphan")
    skills = relationship("Skill", secondary=session_skills, backref="sessions")
    user = relationship("User", back_populates="sessions")

    def __repr__(self):
        return f"<Session(id={self.id}, title='{self.title}', user_id='{self.user_id}')>"

class Message(Base):
    __tablename__ = 'messages'

    id = Column(Integer, primary_key=True, index=True)
    session_id = Column(Integer, ForeignKey('sessions.id'), nullable=False)
    sender = Column(String, nullable=False)
    content = Column(Text, nullable=False)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    model_response_time = Column(Integer, nullable=True)
    token_count = Column(Integer, nullable=True)
    message_metadata = Column(JSON, nullable=True)
    reasoning_content = Column(Text, nullable=True)
    audio_path = Column(String, nullable=True)

    session = relationship("Session", back_populates="messages")

    def __repr__(self):
        return f"<Message(id={self.id}, session_id={self.session_id}, sender='{self.sender}')>"
