"""Verify the analysis-default migration backfills existing configurations."""

import importlib

import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations


def test_analysis_default_migration_backfills_false(tmp_path, monkeypatch):
    engine = sa.create_engine(f"sqlite:///{tmp_path / 'analysis_default.db'}")
    metadata = sa.MetaData()
    legacy_table = sa.Table(
        "model_configs",
        metadata,
        sa.Column("id", sa.String(), primary_key=True),
        sa.Column("name", sa.String(), nullable=False),
    )
    metadata.create_all(engine)

    with engine.begin() as connection:
        connection.execute(legacy_table.insert().values(id="existing", name="现有模型"))
        operations = Operations(MigrationContext.configure(connection))
        migration = importlib.import_module("migrations.versions.a3f9c2e71b48_add_analysis_default_to_model_configs")
        monkeypatch.setattr(migration, "op", operations)
        migration.upgrade()

        columns = {column["name"] for column in sa.inspect(connection).get_columns("model_configs")}
        assert "is_analysis_default" in columns

        value = connection.execute(
            sa.text("SELECT is_analysis_default FROM model_configs WHERE id = :id"),
            {"id": "existing"},
        ).scalar_one()
        assert value == 0
