from logging.config import fileConfig
import logging
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from sqlalchemy.ext.asyncio import create_async_engine, AsyncConnection

from alembic import context
from app.core import config as app_config

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from app.core.database.ModelsBase import Base
from app.core.database.models.Notification import Notification
from app.core.database.models.NotificationChannel import NotificationChanel
from app.core.database.models.NotificationType import NotificationType
from app.core.database.models.Target import Target
from app.core.database.models.TargetType import TargetType
from app.core.database.models.TargetUrl import TargetUrl
from app.core.database.models.TargetUrlType import TargetUrlType
from sqlalchemy.ext.asyncio import create_async_engine
import asyncio
# Base.metadata contiene toda la estructura de los modelos
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
logger = logging.getLogger('alembic')
logger.setLevel(logging.DEBUG)  # Configurar el nivel de log (DEBUG, INFO, etc.)
db_user = app_config.DB_USER
db_password = app_config.DB_PASSWORD
db_host = app_config.DB_HOST
db_port = app_config.DB_PORT
db_name = app_config.DB_NAME
DATABASE_URL = f"postgresql://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}"
print(f"Intentando conectar con usuario: {DATABASE_URL}")
def run_migrations_offline() -> None:
    print(f"1111")
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    config.set_main_option("sqlalchemy.url", str(DATABASE_URL))
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
    )

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

async def run_migrations_online():
    print(f"1111")

    try:
        # Intentar crear la conexión asincrónica
        connectable = create_async_engine(DATABASE_URL, echo=True)

        # Configurar el contexto de migración
        async with connectable.connect() as connection:
            await connection.run_sync(lambda conn: context.configure(
                connection=conn,
                target_metadata=target_metadata,
                process_bind_parameters=True,
            ))
            print(111)
            # Ejecutar las migraciones
            async with connection.begin():
                await context.run_migrations()

    except Exception as e:
        logger.error(f"Error al conectar a la base de datos: {e}")
        raise  # Volver a lanzar el error después de registrar el problema
    
async def run_migrations_online1():
    connectable = create_async_engine(DATABASE_URL, echo=True)
   # connectable = engine_from_config(
      #  config.get_section(config.config_ini_section),
      #  prefix="sqlalchemy.",
      #  poolclass=pool.NullPool,
   # )
   
     # Configurar el contexto de migración
    async with connectable.connect() as connection:
        await connection.run_sync(lambda conn: context.configure(
            connection=conn,
            target_metadata=None,  # Aquí puedes pasar tu metadata si la tienes
            process_bind_parameters=True,
        ))

        # Ejecutar las migraciones
        async with connection.begin():
            await context.run_migrations()

    """
     with connectable.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=target_metadata,
            compare_type=True,  # Detecta cambios en tipos de columnas
        )

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

    """
   

if __name__ == "__main__":
    asyncio.run(run_migrations_online())