import os
from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy.sql import func
from pgvector.sqlalchemy import Vector

# Example connection string: postgresql://user:pass@localhost:5432/outlook_ai
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./test.db") # Fallback to SQLite for initial testing

engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

class AIMemory(Base):
    __tablename__ = "ai_memory"

    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(String, index=True)
    email_thread_id = Column(String, index=True)
    content = Column(Text)
    # 1536 is the dimension for OpenAI text-embedding-ada-002
    embedding = Column(Vector(1536))
    created_at = Column(DateTime(timezone=True), server_default=func.now())

# Create tables
# Note: In production with pgvector, you must execute 'CREATE EXTENSION vector;' before creating tables
def init_db():
    Base.metadata.create_all(bind=engine)
