from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime, ForeignKey, Float, JSON
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from datetime import datetime
from .config import settings

engine = create_engine(settings.DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

class Meeting(Base):
    __tablename__ = "meetings"

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True)
    filename = Column(String)
    file_path = Column(String)
    date_recorded = Column(DateTime, default=datetime.utcnow)
    
    duration_seconds = Column(Float, nullable=True)
    status = Column(String, default="UPLOADED") # UPLOADED, SPLITTING, TRANSCRIBING, ANALYZING, COMPLETED, ERROR
    
    participants = Column(JSON, nullable=True) # List of names
    summary = Column(Text, nullable=True)
    
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    chunks = relationship("TranscriptChunk", back_populates="meeting", cascade="all, delete-orphan")
    analysis_results = relationship("AnalysisResult", back_populates="meeting", cascade="all, delete-orphan")

class TranscriptChunk(Base):
    __tablename__ = "transcript_chunks"

    id = Column(Integer, primary_key=True, index=True)
    meeting_id = Column(Integer, ForeignKey("meetings.id"))
    chunk_index = Column(Integer)
    
    raw_text = Column(Text)
    json_content = Column(JSON, nullable=True) # Structured timestamps/speakers
    
    meeting = relationship("Meeting", back_populates="chunks")

class AnalysisResult(Base):
    __tablename__ = "analysis_results"

    id = Column(Integer, primary_key=True, index=True)
    meeting_id = Column(Integer, ForeignKey("meetings.id"))
    prompt_key = Column(String) # summary, tasks, notes
    result_text = Column(Text)
    
    created_at = Column(DateTime, default=datetime.utcnow)
    meeting = relationship("Meeting", back_populates="analysis_results")

def init_db():
    Base.metadata.create_all(bind=engine)

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
