# database.py
import os
import logging
from sqlalchemy import create_engine, pool, text
from sqlalchemy.orm import sessionmaker, declarative_base
from dotenv import load_dotenv

# Load env
load_dotenv()

logger = logging.getLogger(__name__)

# Get DB URL
DATABASE_URL = os.getenv("DATABASE_URL")

if not DATABASE_URL:
    logger.error("❌ DATABASE_URL not found in .env")
    raise ValueError("DATABASE_URL is required")

# 🔥 Safe DB URL (hide password)
safe_db_url = DATABASE_URL.split("@")[-1]

# Control SQL logs
LOG_SQL = os.getenv("LOG_SQL", "false").lower() == "true"

# Create engine
engine = create_engine(
    DATABASE_URL,
    poolclass=pool.NullPool,
    echo=LOG_SQL
)

# ✅ Test DB connection at startup
try:
    with engine.connect() as connection:
        connection.execute(text("SELECT 1"))
    logger.info(f"✅ Database connected successfully | {safe_db_url}")
except Exception as e:
    logger.exception(f"❌ Database connection failed | {safe_db_url}")

# Session
SessionLocal = sessionmaker(
    autocommit=False,
    autoflush=False,
    bind=engine
)

# Base
Base = declarative_base()

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

# Init DB
def init_db():
    # Schema is owned by Alembic migrations (see alembic/versions/) — do not
    # create_all here, it silently pre-creates tables and makes Alembic think
    # they don't exist yet, causing DuplicateTable on the next `upgrade head`.
    _migrate_add_is_deleted()


def _migrate_add_is_deleted():
    from sqlalchemy import inspect, text
    inspector = inspect(engine)
    cols = [c["name"] for c in inspector.get_columns("conversations")]
    if "is_deleted" not in cols:
        with engine.connect() as conn:
            conn.execute(text(
                "ALTER TABLE conversations ADD COLUMN is_deleted SMALLINT NOT NULL DEFAULT 0"
            ))
            conn.commit()
        logger.info("✅ Migration: added is_deleted column to conversations")