from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, sessionmaker
from dotenv import load_dotenv
import os

load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), '..', '.env'))

DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./aidsmonitoring.db")

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

class Base(DeclarativeBase):
    pass

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


def ensure_column(table: str, column: str, ddl: str):
    """Add `column` to `table` if it doesn't exist. SQLite-safe additive
    migration — runs at startup so model evolutions don't break existing DBs.
    `ddl` is the column definition only, e.g. 'TEXT' or 'REAL DEFAULT 0'."""
    from sqlalchemy import text
    with engine.connect() as conn:
        cols = conn.execute(text(f"PRAGMA table_info({table})")).fetchall()
        if column not in {c[1] for c in cols}:
            conn.execute(text(f"ALTER TABLE {table} ADD COLUMN {column} {ddl}"))
            conn.commit()
