from __future__ import annotations

from logging.config import fileConfig

from alembic import context
from sqlalchemy import engine_from_config, pool

try:
    from govoplan_access.backend.db import models as access_models  # noqa: F401 - populate optional access metadata
except ModuleNotFoundError as exc:
    if exc.name != "govoplan_access":
        raise
from govoplan_core.admin import models as core_admin_models  # noqa: F401 - populate core admin metadata
from govoplan_core.core import change_sequence as core_change_sequence_models  # noqa: F401 - populate core metadata
from govoplan_core.core import ownership as core_ownership_models  # noqa: F401 - populate core metadata
from govoplan_core.security import credential_envelopes as core_credential_models  # noqa: F401 - populate core metadata
from govoplan_core.core.migrations import migration_metadata_plan
from govoplan_core.db.base import Base
from govoplan_core.server.default_config import get_server_config
from govoplan_core.server.registry import build_platform_registry
from govoplan_core.settings import settings
from govoplan_core.tenancy.scope import scope_registry

config = context.config
database_url = config.attributes.get("database_url") or settings.database_url
config.set_main_option("sqlalchemy.url", database_url)

if config.config_file_name is not None:
    # Migrations can run inside the long-lived application process when module
    # state changes. Do not let Alembic's logging setup disable loggers that the
    # server already created (for example slow-request diagnostics).
    fileConfig(config.config_file_name, disable_existing_loggers=False)


def _target_metadata():
    server_config = get_server_config()
    enabled_modules = config.attributes.get("enabled_modules", server_config.enabled_modules)
    manifest_factories = config.attributes.get("manifest_factories", server_config.manifest_factories)
    registry = build_platform_registry(
        enabled_modules,
        manifest_factories=manifest_factories,
    )
    plan = migration_metadata_plan(registry, extra_metadata=(scope_registry.metadata, Base.metadata))
    return tuple(dict.fromkeys(plan.metadata))


target_metadata = _target_metadata()


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"})

    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)
        with context.begin_transaction():
            context.run_migrations()


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