"""
Alembic env.py – configurazione migrazioni per PostgreSQL.
Usa il driver SYNC (psycopg2) che è più semplice e compatibile con Alembic.
"""

from logging.config import fileConfig

from alembic import context
from sqlalchemy import engine_from_config, pool

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.config import get_settings
from app.database import Base

# Importa tutti i modelli per permettere l'autogenerazione
import app.models  # noqa: F401

settings = get_settings()

# Configurazione Alembic
config = context.config

# Configura logging da alembic.ini
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

# Metadata per autogenerazione
target_metadata = Base.metadata

# Usa DATABASE_URL_SYNC (psycopg2) per le migrazioni
config.set_main_option("sqlalchemy.url", settings.database_url_sync)


def run_migrations_offline() -> None:
    """Esegui migrazioni in modalità 'offline' (genera SQL senza connettersi)."""
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
        compare_type=True,
        compare_server_default=True,
    )

    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online() -> None:
    """Esegui migrazioni in modalità 'online' con connessione DB diretta."""
    connectable = engine_from_config(
        config.get_section(config.config_ini_section, {}),
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )

    with connectable.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=target_metadata,
            compare_type=True,
            compare_server_default=True,
        )

        with context.begin_transaction():
            context.run_migrations()


if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()
