"""Alembic async env（CLAUDE.md：checkpointer.setup 在迁移/CI；此处仅领域表）。"""

from __future__ import annotations

import asyncio
from logging.config import fileConfig

import ww_db.models  # noqa: F401  注册所有表到 metadata
from alembic import context
from sqlalchemy import Connection, pool
from sqlalchemy.ext.asyncio import async_engine_from_config
from ww_config import get_settings
from ww_db.base import Base

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

# 用 async URL（asyncpg）运行迁移
config.set_main_option("sqlalchemy.url", get_settings().database_url)
target_metadata = Base.metadata

# langgraph 检查点表由 langgraph 自管 schema（迁移 d3e4f5a6b7c8 调其 setup() 建表），
# 不在 Base.metadata。autogenerate/check 须忽略它们，否则会误报"待 drop"漂移。
_LANGGRAPH_TABLES = frozenset(
    {"checkpoints", "checkpoint_blobs", "checkpoint_writes", "checkpoint_migrations"}
)


def include_object(
    obj: object, name: str | None, type_: str, reflected: bool, compare_to: object
) -> bool:
    if type_ == "table" and name in _LANGGRAPH_TABLES:
        return False
    return True


def do_run_migrations(connection: Connection) -> None:
    context.configure(
        connection=connection,
        target_metadata=target_metadata,
        include_object=include_object,
    )
    with context.begin_transaction():
        context.run_migrations()


async def run_async_migrations() -> None:
    connectable = async_engine_from_config(
        config.get_section(config.config_ini_section, {}),
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )
    async with connectable.connect() as connection:
        await connection.run_sync(do_run_migrations)
    await connectable.dispose()


def run_migrations_offline() -> None:
    context.configure(
        url=config.get_main_option("sqlalchemy.url"),
        target_metadata=target_metadata,
        literal_binds=True,
    )
    with context.begin_transaction():
        context.run_migrations()


if context.is_offline_mode():
    run_migrations_offline()
else:
    asyncio.run(run_async_migrations())
