import asyncio
from logging.config import fileConfig
import os
import sys

from sqlalchemy import pool
from sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context

# --- ÚTVONAL JAVÍTÁS ---
sys.path.insert(0, "/app")

try:
    from app.core.config import settings
    from app.db.base import Base
    # Minden modellt importálunk a szinkronhoz
    import app.models
except ImportError as e:
    print(f"Hiba az importálásnál: {e}")
    raise

config = context.config
config.set_main_option("sqlalchemy.url", settings.DATABASE_URL)

if config.config_file_name is not None:
    fileConfig(config.config_file_name)

target_metadata = Base.metadata

# CSAK a 'data' sémával foglalkozunk!
def include_object(object, name, type_, reflected, compare_to):
    if type_ == "table":
        return object.schema == "data"
    return True

def do_run_migrations(connection):
    context.configure(
        connection=connection,
        target_metadata=target_metadata,
        include_schemas=True,
        include_object=include_object,
        version_table_schema='public'
    )
    with context.begin_transaction():
        context.run_migrations()

async def run_migrations_online() -> None:
    connectable = async_engine_from_config(
        config.get_section(config.config_ini_section, {}),
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )
    async with connectable.connect() as connection:
        await connection.run_sync(do_run_migrations)
    await connectable.dispose()

if context.is_offline_mode():
    context.configure(
        url=config.get_main_option("sqlalchemy.url"),
        target_metadata=target_metadata, 
        literal_binds=True,
        include_schemas=True,
        include_object=include_object
    )
    with context.begin_transaction():
        context.run_migrations()
else:
    asyncio.run(run_migrations_online())