from __future__ import annotations

from logging.config import fileConfig

from alembic import context
from sqlalchemy import engine_from_config, pool
from sqlalchemy.engine import URL

from app.core.settings import get_settings
from app.core.db.common import CommonBase

# -----------------------------------------------------------------------------
# IMPORTANT FOR ALEMBIC AUTOGENERATE
# -----------------------------------------------------------------------------
# Alembic only sees tables that are registered in CommonBase.metadata.
# A model is registered only after its module is imported. Keep every SQLAlchemy
# model module here so a fresh baseline migration can generate all tables.
# Do not remove these imports even if they look unused.
# -----------------------------------------------------------------------------

# Core / tenancy models
from app.modules.core.tenancy import models as tenancy_models  # noqa: F401
from app.modules.core.tenancy import settings_models as tenancy_settings_models  # noqa: F401

# IAM / RBAC / token / password-flow models
from app.modules.core.iam import models as iam_models  # noqa: F401
from app.modules.core.iam import tokens_models as iam_tokens_models  # noqa: F401
from app.modules.core.iam import password_flows_models as iam_password_flows_models  # noqa: F401
from app.modules.core.rbac import models as rbac_models  # noqa: F401

# Audit log models
from app.modules.core.audit import models as audit_models  # noqa: F401

# Business module models
from app.modules.clients import models as client_models  # noqa: F401
from app.modules.client_groups import models as client_group_models  # noqa: F401
from app.modules.clients import association_models as client_association_models  # noqa: F401
from app.modules.services import models as service_models  # noqa: F401
from app.modules.consultants import models as consultant_models  # noqa: F401
from app.modules.employees import models as employee_models  # noqa: F401
from app.modules.billing import models as billing_models  # noqa: F401
from app.modules.platform_billing import models as platform_billing_models  # noqa: F401
from app.modules.marketplace import models as marketplace_models  # noqa: F401
from app.modules.documents import models as documents_models  # noqa: F401
from app.modules.alerts import models as alerts_models  # noqa: F401
from app.modules.email_integration import models as email_integration_models  # noqa: F401
from app.modules.domain_management import models as domain_management_models  # noqa: F401
from app.modules.notice_cases import models as notice_cases_models  # noqa: F401
from app.modules.registrations import models as registration_models  # noqa: F401
from app.modules.credential_vault import models as credential_vault_models  # noqa: F401
from app.modules.client_identity import models as client_identity_models  # noqa: F401

config = context.config

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

target_metadata = CommonBase.metadata


def get_url() -> str:
    s = get_settings()
    if (s.DB_BACKEND or "sqlite").lower() == "sqlite":
        return f"sqlite:///{s.SQLITE_COMMON_PATH}"
    return URL.create(
        drivername="postgresql+psycopg",
        username=s.PG_USER,
        password=s.PG_PASSWORD,
        host=s.PG_HOST,
        port=s.PG_PORT,
        database=s.PG_DB_COMMON,
    ).render_as_string(hide_password=False)


def run_migrations_offline() -> None:
    context.configure(
        url=get_url(),
        target_metadata=target_metadata,
        literal_binds=True,
        compare_type=True,
        compare_server_default=True,
        dialect_opts={"paramstyle": "named"},
    )
    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online() -> None:
    configuration = config.get_section(config.config_ini_section) or {}
    configuration["sqlalchemy.url"] = get_url()
    connectable = engine_from_config(
        configuration,
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
        future=True,
    )
    with connectable.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=target_metadata,
            compare_type=True,
            compare_server_default=True,
            render_as_batch=("sqlite" in get_url()),
        )
        with context.begin_transaction():
            context.run_migrations()


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