"""
Configuration de la base de données SQLAlchemy
"""
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from pathlib import Path

# Base pour les modèles SQLAlchemy (DB principale)
Base = declarative_base()
# Base dédiée à l'architecture
ArchBase = declarative_base()

# Engine et session
engine = None
SessionLocal = None
arch_engine = None
ArchSessionLocal = None


def init_database(db_path: str = "./data/db.sqlite"):
    """Initialise la connexion à la base de données"""
    global engine, SessionLocal

    # Créer le dossier data si nécessaire
    Path(db_path).parent.mkdir(parents=True, exist_ok=True)

    # Créer l'engine SQLite
    database_url = f"sqlite:///{db_path}"
    engine = create_engine(
        database_url,
        connect_args={"check_same_thread": False},
        echo=False
    )

    # Créer la session factory
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

    # Créer les tables
    Base.metadata.create_all(bind=engine)

    # Migration : ajouter les colonnes manquantes
    _run_migrations(engine)

    return engine


def _run_migrations(eng):
    """Ajoute les colonnes manquantes aux tables existantes"""
    import sqlalchemy
    inspector = sqlalchemy.inspect(eng)

    # Migration de la table 'ip'
    if 'ip' in inspector.get_table_names():
        existing_columns = {col['name'] for col in inspector.get_columns('ip')}
        with eng.connect() as conn:
            if 'dhcp_synced' not in existing_columns:
                conn.execute(sqlalchemy.text("ALTER TABLE ip ADD COLUMN dhcp_synced BOOLEAN DEFAULT 0"))
                conn.commit()
                print("✓ Migration: colonne dhcp_synced ajoutée à la table ip")


def init_architecture_database(db_path: str = "./architecture/database/architecture.sqlite"):
    """Initialise la connexion à la base de données d'architecture"""
    global arch_engine, ArchSessionLocal

    Path(db_path).parent.mkdir(parents=True, exist_ok=True)

    database_url = f"sqlite:///{db_path}"
    arch_engine = create_engine(
        database_url,
        connect_args={"check_same_thread": False},
        echo=False
    )

    ArchSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=arch_engine)

    # Créer les tables d'architecture si besoin
    ArchBase.metadata.create_all(bind=arch_engine)

    return arch_engine


def get_db():
    """Dependency pour obtenir une session DB"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def get_arch_db():
    """Dependency pour obtenir une session DB architecture"""
    if ArchSessionLocal is None:
        init_architecture_database()
    db = ArchSessionLocal()
    try:
        yield db
    finally:
        db.close()
