import sys
from logging.config import fileConfig
from pathlib import Path

from alembic import context
from sqlalchemy import engine_from_config, pool
from common_logging import get_logger

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from app.config import settings
from app.db.base import Base

config = context.config
if settings.DATABASE_URL:
    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
logger = get_logger(__name__)


def _sync_tenant_schemas(connection) -> None:
    from sqlalchemy import text

    from app.db.tenant_schema import TenantSchemaManager

    result = connection.execute(
        text(
            "SELECT schema_name FROM information_schema.schemata WHERE schema_name LIKE 'tenant_%'"
        )
    )
    tenant_schemas = [row[0] for row in result]
    tenant_tables = TenantSchemaManager.get_tenant_table_definitions()
    if not tenant_tables:
        return
    for schema_name in tenant_schemas:
        try:
            tenant_bind = connection.execution_options(schema_translate_map={None: schema_name})
            Base.metadata.create_all(bind=tenant_bind, tables=tenant_tables, checkfirst=True)
            connection.execute(text("COMMIT"))
        except Exception as e:
            logger.bind(schema=schema_name).opt(exception=True).error("Failed to sync schema")


def run_migrations_offline() -> None:
    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:
    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()
        _sync_tenant_schemas(connection)


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