"""
Alembic environment for SPAPS.

Imports all domain models from spaps_server_quickstart.domains so that
``Base.metadata`` contains every table. Alembic uses this metadata for
autogenerate and schema diffing.
"""

from __future__ import annotations

import os
import sys
from logging.config import fileConfig

from alembic import context
from sqlalchemy import engine_from_config, pool

# Ensure Alembic helper modules are importable, then prefer the active
# quickstart source tree (for local Docker this should be the live /app/src bind
# mount, not the packaged fallback copied into the image).
sys.path.insert(0, os.path.dirname(__file__))

from path_bootstrap import ensure_quickstart_src_path  # noqa: E402

ensure_quickstart_src_path(__file__, sys.path)

from spaps_server_quickstart.domains._db.base import Base  # noqa: E402

# Phase 1+: import domain models here so Base.metadata picks them up
# from spaps_server_quickstart.domains.users.models import User  # noqa: E402, F401
# from spaps_server_quickstart.domains.auth.models import ...  # noqa: E402, F401
from spaps_server_quickstart.domains.approval_authz_prod_hardening.models import GovernanceAuthzAuditEvent  # noqa: E402, F401
from spaps_server_quickstart.domains.support_telemetry_platform.models import SupportCase, SupportCaseEvent  # noqa: E402, F401
from spaps_server_quickstart.domains.issue_reporting_platform.models import IssueReport  # noqa: E402, F401

config = context.config

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

target_metadata = Base.metadata


def get_database_url() -> str:
    """Resolve the database URL from environment or settings."""
    url = os.environ.get("DATABASE_URL", "")
    if url:
        # Alembic runs synchronously — convert asyncpg to psycopg
        if "asyncpg" in url:
            url = url.replace("postgresql+asyncpg", "postgresql+psycopg")
        return url

    # Fallback: try loading from settings
    try:
        from spaps_server_quickstart.spaps_settings import get_spaps_settings

        settings = get_spaps_settings()
        return settings.sync_database_url
    except Exception:
        return "postgresql+psycopg://postgres:postgres@localhost:5432/spaps"


def run_migrations_offline() -> None:
    """Run migrations in 'offline' mode (generate SQL without DB connection)."""
    url = get_database_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:
    """Run migrations with a live database connection."""
    alembic_config = config.get_section(config.config_ini_section, {})
    alembic_config["sqlalchemy.url"] = get_database_url()

    connectable = engine_from_config(
        alembic_config,
        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()
