"""Database configuration and session management using SQLModel"""
import os
from typing import Generator
from sqlalchemy import create_engine
from sqlmodel import SQLModel, Session, create_engine
from app.config import get_settings

settings = get_settings()

# Database URL can be overridden by environment variable DATABASE_URL
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./ohm_streaming.db")

# Create the engine
# connect_args={"check_same_thread": False} is required for SQLite and FastAPI
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})


def create_db_and_tables():
    """Create the database and tables based on the models"""
    # CRITICAL: Import ALL models here to ensure they are registered with SQLModel.metadata
    from app.models.auth import UserTable
    from app.models.watchlist import WatchlistItemTable, WatchlistSettingsTable
    from app.models.favorites import FavoriteTable
    from app.models.sonarr import SonarrMappingTable, SonarrConfigTable
    from app.models.settings import AppSettingsTable
    
    SQLModel.metadata.create_all(engine)
    
    # Add new columns to existing tables if they don't exist (SQLite workaround)
    _ensure_columns(engine)


def _ensure_columns(engine):
    """Add new columns to app_settings table if they don't exist"""
    from sqlalchemy import inspect, text
    
    inspector = inspect(engine)
    if 'app_settings' not in inspector.get_table_names():
        return
    
    existing = {col['name'] for col in inspector.get_columns('app_settings')}
    
    new_columns = {
        'recommendations_filter': 'TEXT DEFAULT "all"',
        'releases_filter': 'TEXT DEFAULT "all"',
        'anime_enabled': 'BOOLEAN DEFAULT 1',
        'series_enabled': 'BOOLEAN DEFAULT 1',
        'download_dir': 'TEXT DEFAULT "downloads"',
    }
    
    with engine.connect() as conn:
        for col_name, col_def in new_columns.items():
            if col_name not in existing:
                conn.execute(text(f'ALTER TABLE app_settings ADD COLUMN {col_name} {col_def}'))
                conn.commit()


def get_session() -> Generator[Session, None, None]:
    """Dependency for getting a database session"""
    with Session(engine) as session:
        yield session
