"""Alembic 环境。

跟标准模板的差别:
  - 从 app.core.config.settings 读 DATABASE_URL,不再走 alembic.ini 的 sqlalchemy.url
  - import app.db.base 让 Base.metadata 包含所有 model 表(model 文件首次导入时注册到 metadata)
"""
from __future__ import annotations

from logging.config import fileConfig

from alembic import context
from sqlalchemy import engine_from_config, pool

from app.core.config import settings
from app.db.base import Base  # noqa: F401  (触发 model 注册)

config = context.config

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

# 让 alembic 用我们的 DATABASE_URL,不是 alembic.ini 里的(空)
config.set_main_option("sqlalchemy.url", settings.DATABASE_URL)

target_metadata = Base.metadata


def run_migrations_offline() -> None:
    """生成 SQL 但不连库。一般用于 review。"""
    context.configure(
        url=settings.DATABASE_URL,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
        render_as_batch=settings.DATABASE_URL.startswith("sqlite"),
    )
    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online() -> None:
    """常规模式:连库执行 migration。

    render_as_batch=True 让 SQLite 也能做 ALTER COLUMN(SQLite 原生不支持,
    Alembic 用"重建表"的方式模拟)。
    """
    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,
            render_as_batch=settings.DATABASE_URL.startswith("sqlite"),
        )
        with context.begin_transaction():
            context.run_migrations()


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