"""YakPanel - Database configuration"""
import os
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.orm import DeclarativeBase
from app.core.config import get_settings


settings = get_settings()

# Ensure data directory exists for SQLite
if "sqlite" in settings.database_url:
    backend_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    data_dir = os.path.join(backend_dir, "data")
    os.makedirs(data_dir, exist_ok=True)

engine = create_async_engine(
    settings.database_url,
    echo=settings.debug,
)

AsyncSessionLocal = async_sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False,
    autocommit=False,
    autoflush=False,
)


class Base(DeclarativeBase):
    """SQLAlchemy declarative base"""
    pass


async def get_db():
    """Dependency for async database sessions"""
    async with AsyncSessionLocal() as session:
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise
        finally:
            await session.close()


def _run_migrations(conn):
    """Add new columns to existing tables (SQLite)."""
    import sqlalchemy
    try:
        r = conn.execute(sqlalchemy.text("PRAGMA table_info(sites)"))
        cols = [row[1] for row in r.fetchall()]
        if "php_version" not in cols:
            conn.execute(sqlalchemy.text("ALTER TABLE sites ADD COLUMN php_version VARCHAR(16) DEFAULT '74'"))
        if "force_https" not in cols:
            conn.execute(sqlalchemy.text("ALTER TABLE sites ADD COLUMN force_https INTEGER DEFAULT 0"))
    except Exception:
        pass
    # Create backup_plans if not exists (create_all handles new installs)
    try:
        conn.execute(sqlalchemy.text("""
            CREATE TABLE IF NOT EXISTS backup_plans (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name VARCHAR(128) NOT NULL,
                plan_type VARCHAR(32) NOT NULL,
                target_id INTEGER NOT NULL,
                schedule VARCHAR(64) NOT NULL,
                enabled BOOLEAN DEFAULT 1
            )
        """))
    except Exception:
        pass
    # Create custom_plugins if not exists
    try:
        conn.execute(sqlalchemy.text("""
            CREATE TABLE IF NOT EXISTS custom_plugins (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                plugin_id VARCHAR(64) UNIQUE NOT NULL,
                name VARCHAR(128) NOT NULL,
                version VARCHAR(32) DEFAULT '1.0',
                desc VARCHAR(512) DEFAULT '',
                source_url VARCHAR(512) DEFAULT '',
                enabled BOOLEAN DEFAULT 1
            )
        """))
    except Exception:
        pass


async def init_db():
    """Initialize database tables"""
    import app.models  # noqa: F401 - register all models with Base.metadata
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
        if "sqlite" in str(engine.url):
            await conn.run_sync(_run_migrations)
