import sqlite3
import subprocess
import tomllib
from datetime import datetime
from pathlib import Path

from typer.testing import CliRunner

from mitch.cli import app
from mitch.project import Project
from mitch.watcher import EventType

runner = CliRunner()


def _write_project_config(project_root, project_id="tests-cli-project"):
    (project_root / "mitch.toml").write_text(f'[project]\nid = "{project_id}"\n', encoding="utf-8")


def _run_git(cwd, *args):
    result = subprocess.run(
        ["git", *args],
        cwd=cwd,
        capture_output=True,
        text=True,
        check=False,
    )
    assert result.returncode == 0, result.stderr or result.stdout
    return result.stdout.strip()


def _init_git_repo(path):
    _run_git(path, "init")
    _run_git(path, "config", "user.email", "test@example.com")
    _run_git(path, "config", "user.name", "Test User")


def _write_status_fixture_migrations(repo_path):
    _write_project_config(repo_path, "status-fixture")
    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;",
        encoding="utf-8",
    )
    (repo_path / "002-next.up.sql").write_text(
        "CREATE TABLE table_two (id int);",
        encoding="utf-8",
    )
    (repo_path / "002-next.down.sql").write_text(
        "DROP TABLE table_two;",
        encoding="utf-8",
    )


def test_add_help():
    result = runner.invoke(app, ["add", "--help"])

    assert result.exit_code == 0
    assert "Apply the specified migrations in the project." in result.output


def test_up_help_includes_watch_options():
    result = runner.invoke(app, ["up", "--help"])

    assert result.exit_code == 0
    assert "--watch" in result.output


def test_down_and_drop_help_have_distinct_descriptions():
    down_help = runner.invoke(app, ["down", "--help"])
    drop_help = runner.invoke(app, ["drop", "--help"])

    assert down_help.exit_code == 0
    assert "Revert all applied migrations in the project." in down_help.output

    assert drop_help.exit_code == 0
    assert "Revert the specified migrations and their dependants in the project." in drop_help.output


def test_stash_help_mentions_stashing_behavior():
    result = runner.invoke(app, ["stash", "--help"])

    assert result.exit_code == 0
    assert "--vcs" in result.output


def test_status_help_mentions_ci_and_strict_options():
    result = runner.invoke(app, ["status", "--help"])

    assert result.exit_code == 0
    assert "--ci" in result.output
    assert "--strict" in result.output


def test_init_creates_mitch_toml_in_current_working_directory():
    with runner.isolated_filesystem():
        result = runner.invoke(app, ["init", "my-project"])

        assert result.exit_code == 0
        config = tomllib.loads(Path("mitch.toml").read_text(encoding="utf-8"))
        assert config["project"]["id"] == "my-project"


def test_init_refuses_to_overwrite_existing_mitch_toml():
    with runner.isolated_filesystem():
        Path("mitch.toml").write_text('[project]\nid = "existing"\n', encoding="utf-8")

        result = runner.invoke(app, ["init", "new-id"])

        assert result.exit_code == 1
        assert "already exists" in result.output


def test_add_applies_migration_to_sqlite(tmp_path):
    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    result = runner.invoke(
        app,
        [
            "add",
            "001-init",
            "--project",
            "tests/migrations",
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )

    assert result.exit_code == 0
    assert "Deploying:" in result.output

    with sqlite3.connect(db_path) as connection:
        row = connection.execute(
            "SELECT id FROM mitch_migrations WHERE id = ?",
            ("001-init",),
        ).fetchone()

    assert row is not None


def test_create_generates_migration_files(tmp_path):
    _write_project_config(tmp_path, "create-generated")
    result = runner.invoke(
        app,
        [
            "create",
            "001-init",
            "--project",
            str(tmp_path),
        ],
    )

    assert result.exit_code == 0

    up_script = tmp_path / "001-init.up.sql"
    down_script = tmp_path / "001-init.down.sql"
    config_file = tmp_path / "001-init.config.toml"

    assert up_script.exists()
    assert down_script.exists()
    assert config_file.exists()

    config = tomllib.loads(config_file.read_text(encoding="utf-8"))
    assert config["id"] == "001-init"
    assert isinstance(config["created_at"], datetime)
    assert config["created_at"].tzinfo is not None


def test_create_populates_up_script_from_stdin(tmp_path):
    _write_project_config(tmp_path, "create-stdin-up")
    up_sql = "CREATE TABLE stdin_only (id int);\n"
    result = runner.invoke(
        app,
        [
            "create",
            "001-init",
            "--project",
            str(tmp_path),
        ],
        input=up_sql,
    )

    assert result.exit_code == 0
    assert (tmp_path / "001-init.up.sql").read_text(encoding="utf-8") == up_sql
    assert (tmp_path / "001-init.down.sql").read_text(encoding="utf-8") == ""


def test_create_populates_up_and_down_scripts_from_stdin_sections(tmp_path):
    _write_project_config(tmp_path, "create-stdin-sections")
    payload = (
        "-- up.sql\n"
        "CREATE TABLE stdin_split (id int);\n"
        "-- down.sql\n"
        "DROP TABLE stdin_split;\n"
    )
    result = runner.invoke(
        app,
        [
            "create",
            "001-init",
            "--project",
            str(tmp_path),
        ],
        input=payload,
    )

    assert result.exit_code == 0
    assert (tmp_path / "001-init.up.sql").read_text(encoding="utf-8") == "CREATE TABLE stdin_split (id int);\n"
    assert (tmp_path / "001-init.down.sql").read_text(encoding="utf-8") == "DROP TABLE stdin_split;\n"


def test_create_rejects_missing_dependencies(tmp_path):
    _write_project_config(tmp_path, "create-missing-deps")
    result = runner.invoke(
        app,
        [
            "create",
            "001-init",
            "--project",
            str(tmp_path),
            "--dependency",
            "missing-migration",
        ],
    )

    assert result.exit_code == 1
    assert "Missing dependencies" in result.output


def test_create_respects_skip_flags(tmp_path):
    _write_project_config(tmp_path, "create-skip")
    result = runner.invoke(
        app,
        [
            "create",
            "001-init",
            "--project",
            str(tmp_path),
            "--skip-config",
            "--skip-downscript",
        ],
    )

    assert result.exit_code == 0
    assert (tmp_path / "001-init.up.sql").exists()
    assert not (tmp_path / "001-init.down.sql").exists()
    assert not (tmp_path / "001-init.config.toml").exists()


def test_up_watch_applies_new_migration(tmp_path, monkeypatch):
    repo_path = tmp_path / "migrations"
    repo_path.mkdir()
    _write_project_config(repo_path)
    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE some_table (id int);",
        encoding="utf-8",
    )

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    def fake_watch_for_changes(self):
        (repo_path / "002-add.up.sql").write_text(
            "ALTER TABLE some_table ADD COLUMN extra int;",
            encoding="utf-8",
        )
        yield [(EventType.CREATED, repo_path / "002-add.up.sql")]

    monkeypatch.setattr(Project, "watch_for_changes", fake_watch_for_changes)

    result = runner.invoke(
        app,
        [
            "up",
            "--watch",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )

    assert result.exit_code == 0

    with sqlite3.connect(db_path) as connection:
        rows = connection.execute(
            "SELECT id FROM mitch_migrations ORDER BY id",
        ).fetchall()

    assert [row[0] for row in rows] == ["001-init", "002-add"]


def test_up_applies_all_migrations_to_sqlite(tmp_path):
    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    result = runner.invoke(
        app,
        [
            "up",
            "--project",
            "tests/migrations",
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )

    assert result.exit_code == 0
    assert "Deploying:" in result.output

    with sqlite3.connect(db_path) as connection:
        rows = connection.execute(
            "SELECT id FROM mitch_migrations ORDER BY id",
        ).fetchall()

    assert [row[0] for row in rows] == ["001-init", "002-add-column"]


def test_drop_reverts_only_selected_migration(tmp_path):
    repo_path = tmp_path / "migrations"
    repo_path.mkdir()
    _write_project_config(repo_path)

    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE a (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE a;",
        encoding="utf-8",
    )

    (repo_path / "002-next.up.sql").write_text(
        "CREATE TABLE b (id int);",
        encoding="utf-8",
    )
    (repo_path / "002-next.down.sql").write_text(
        "DROP TABLE b;",
        encoding="utf-8",
    )
    (repo_path / "002-next.config.toml").write_text(
        'dependencies = ["001-init"]\n',
        encoding="utf-8",
    )

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    drop_result = runner.invoke(
        app,
        [
            "drop",
            "002-next",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )
    assert drop_result.exit_code == 0

    with sqlite3.connect(db_path) as connection:
        rows = connection.execute(
            "SELECT id FROM mitch_migrations ORDER BY id",
        ).fetchall()
        table_a = connection.execute(
            "SELECT name FROM sqlite_schema WHERE type='table' AND name='a'",
        ).fetchone()
        table_b = connection.execute(
            "SELECT name FROM sqlite_schema WHERE type='table' AND name='b'",
        ).fetchone()

    assert [row[0] for row in rows] == ["001-init"]
    assert table_a is not None
    assert table_b is None


def test_log_lists_applied_migrations_with_timestamp_and_status(tmp_path):
    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            "tests/migrations",
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    log_result = runner.invoke(
        app,
        [
            "log",
            "--project",
            "tests/migrations",
            "--database",
            database_url,
        ],
    )

    assert log_result.exit_code == 0
    assert "MIGRATION_ID" in log_result.output
    assert "APPLIED_AT" in log_result.output
    assert "STATUS" in log_result.output
    assert "001-init" in log_result.output
    assert "002-add-column" in log_result.output
    assert "applied" in log_result.output


def test_log_marks_modified_migrations(tmp_path):
    repo_path = tmp_path / "migrations"
    repo_path.mkdir()
    _write_project_config(repo_path)

    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE some_table (id int primary key, name text not null);",
        encoding="utf-8",
    )

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE some_table (id int primary key, name text not null);\nALTER TABLE some_table ADD COLUMN extra int;",
        encoding="utf-8",
    )

    log_result = runner.invoke(
        app,
        [
            "log",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )

    assert log_result.exit_code == 0
    assert "001-init" in log_result.output
    assert "modified" in log_result.output


def test_stash_reconciles_database_and_stashes_local_changes(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)

    original_down = "DROP TABLE table_one;"
    dirty_down = "DROP TABLE table_one; -- local edit"

    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        original_down,
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "add migration")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    (repo_path / "001-init.down.sql").write_text(dirty_down, encoding="utf-8")

    stash_result = runner.invoke(
        app,
        [
            "stash",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )
    assert stash_result.exit_code == 0

    with sqlite3.connect(db_path) as connection:
        rows = connection.execute("SELECT id FROM mitch_migrations").fetchall()

    assert rows == [("001-init",)]
    assert (repo_path / "001-init.down.sql").read_text(encoding="utf-8") == original_down
    assert _run_git(repo_path, "status", "--porcelain") == ""
    assert "stash before mitch stash" in _run_git(repo_path, "stash", "list")


def test_stash_allows_locally_deleted_unapplied_migration(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)

    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "add migration")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    (repo_path / "001-init.up.sql").unlink()

    stash_result = runner.invoke(
        app,
        [
            "stash",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )
    assert stash_result.exit_code == 0
    assert (repo_path / "001-init.up.sql").exists()
    assert _run_git(repo_path, "status", "--porcelain") == ""
    assert "stash before mitch stash" in _run_git(repo_path, "stash", "list")


def test_status_reports_r_m_a_and_is_informative_by_default(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _write_status_fixture_migrations(repo_path)

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    (repo_path / "001-init.up.sql").unlink()
    (repo_path / "002-next.up.sql").write_text(
        "CREATE TABLE table_two (id int, name text);",
        encoding="utf-8",
    )
    (repo_path / "003-pending.up.sql").write_text(
        "CREATE TABLE table_three (id int);",
        encoding="utf-8",
    )

    status_result = runner.invoke(
        app,
        [
            "status",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )

    assert status_result.exit_code == 0
    assert "R 001-init" in status_result.output
    assert "M 002-next" in status_result.output
    assert "A 003-pending" in status_result.output


def test_status_filters_to_specified_migration_ids(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _write_status_fixture_migrations(repo_path)

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0, "Setup failed: " + up_result.output

    (repo_path / "001-init.up.sql").unlink()
    (repo_path / "002-next.up.sql").write_text(
        "CREATE TABLE table_two (id int, name text);",
        encoding="utf-8",
    )
    (repo_path / "003-pending.up.sql").write_text(
        "CREATE TABLE table_three (id int);",
        encoding="utf-8",
    )

    status_result = runner.invoke(
        app,
        [
            "status",
            "002-next",
            "003-pending",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )

    assert status_result.exit_code == 0, "Status command failed: " + status_result.output
    assert "R 001-init" not in status_result.output
    assert "M 002-next" in status_result.output
    assert "A 003-pending" in status_result.output


def test_status_ci_exit_code_2_for_missing_migrations(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _write_status_fixture_migrations(repo_path)

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    (repo_path / "001-init.up.sql").unlink()

    status_result = runner.invoke(
        app,
        [
            "status",
            "--ci",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )

    assert status_result.exit_code == 2
    assert "R 001-init" in status_result.output


def test_status_ci_exit_code_3_for_modified_migrations_in_strict_mode(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _write_status_fixture_migrations(repo_path)

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    (repo_path / "002-next.up.sql").write_text(
        "CREATE TABLE table_two (id int, name text);",
        encoding="utf-8",
    )

    status_result = runner.invoke(
        app,
        [
            "status",
            "--ci",
            "--strict",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )

    assert status_result.exit_code == 3
    assert "M 002-next" in status_result.output


def test_status_ci_exit_code_4_for_missing_and_modified_in_strict_mode(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _write_status_fixture_migrations(repo_path)

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    (repo_path / "001-init.up.sql").unlink()
    (repo_path / "002-next.up.sql").write_text(
        "CREATE TABLE table_two (id int, name text);",
        encoding="utf-8",
    )

    status_result = runner.invoke(
        app,
        [
            "status",
            "--ci",
            "--strict",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )

    assert status_result.exit_code == 4
    assert "R 001-init" in status_result.output
    assert "M 002-next" in status_result.output


def test_status_uses_ci_environment_when_flag_not_provided(tmp_path, monkeypatch):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _write_status_fixture_migrations(repo_path)

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    (repo_path / "001-init.up.sql").unlink()
    monkeypatch.setenv("CI", "1")

    status_result = runner.invoke(
        app,
        [
            "status",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )

    assert status_result.exit_code == 2


def test_status_no_ci_overrides_ci_environment(tmp_path, monkeypatch):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _write_status_fixture_migrations(repo_path)

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    (repo_path / "001-init.up.sql").unlink()
    monkeypatch.setenv("CI", "1")

    status_result = runner.invoke(
        app,
        [
            "status",
            "--no-ci",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )

    assert status_result.exit_code == 0
    assert "R 001-init" in status_result.output


def test_checkout_reverts_migrations_missing_on_target_branch(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)
    base_branch = _run_git(repo_path, "branch", "--show-current")

    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "add 001")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    _run_git(repo_path, "checkout", "-b", "target")
    _run_git(repo_path, "rm", "001-init.up.sql", "001-init.down.sql")
    _run_git(repo_path, "commit", "-m", "remove migration")
    _run_git(repo_path, "checkout", base_branch)

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )
    assert checkout_result.exit_code == 0

    branch = _run_git(repo_path, "branch", "--show-current")
    assert branch == "target"

    with sqlite3.connect(db_path) as connection:
        rows = connection.execute("SELECT id FROM mitch_migrations").fetchall()
        table = connection.execute(
            "SELECT name FROM sqlite_schema WHERE type='table' AND name='table_one'",
        ).fetchone()

    assert rows == []
    assert table is None


def test_checkout_works_when_project_is_subfolder_of_git_repo(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)
    migrations_path = repo_path / "migrations"
    migrations_path.mkdir()
    _write_project_config(migrations_path)
    base_branch = _run_git(repo_path, "branch", "--show-current")

    (migrations_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (migrations_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "add migration")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(migrations_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    _run_git(repo_path, "checkout", "-b", "target")
    _run_git(repo_path, "rm", "migrations/001-init.up.sql", "migrations/001-init.down.sql")
    _run_git(repo_path, "commit", "-m", "remove migration")
    _run_git(repo_path, "checkout", base_branch)

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(migrations_path),
            "--database",
            database_url,
        ],
    )
    assert checkout_result.exit_code == 0

    branch = _run_git(repo_path, "branch", "--show-current")
    assert branch == "target"

    with sqlite3.connect(db_path) as connection:
        rows = connection.execute("SELECT id FROM mitch_migrations").fetchall()

    assert rows == []


def test_checkout_redeploys_changed_deployed_migrations(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)
    base_branch = _run_git(repo_path, "branch", "--show-current")

    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "add 001")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    with sqlite3.connect(db_path) as connection:
        initial_applied_at = connection.execute(
            "SELECT applied_at FROM mitch_migrations WHERE id = '001-init'",
        ).fetchone()[0]

    _run_git(repo_path, "checkout", "-b", "target")
    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int, name text);",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "change migration")
    _run_git(repo_path, "checkout", base_branch)

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )
    assert checkout_result.exit_code == 0

    branch = _run_git(repo_path, "branch", "--show-current")
    assert branch == "target"

    with sqlite3.connect(db_path) as connection:
        applied_at = connection.execute(
            "SELECT applied_at FROM mitch_migrations WHERE id = '001-init'",
        ).fetchone()[0]
        columns = connection.execute(
            "PRAGMA table_info(table_one)",
        ).fetchall()

    assert applied_at != initial_applied_at
    assert any(column[1] == "name" for column in columns)


def test_checkout_redeploys_renamed_deployed_migrations(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)
    base_branch = _run_git(repo_path, "branch", "--show-current")

    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "add migration")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    _run_git(repo_path, "checkout", "-b", "target")
    _run_git(repo_path, "mv", "001-init.up.sql", "001-renamed.up.sql")
    _run_git(repo_path, "mv", "001-init.down.sql", "001-renamed.down.sql")
    _run_git(repo_path, "commit", "-m", "rename migration")
    _run_git(repo_path, "checkout", base_branch)

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )
    assert checkout_result.exit_code == 0

    with sqlite3.connect(db_path) as connection:
        rows = connection.execute(
            "SELECT id FROM mitch_migrations ORDER BY id",
        ).fetchall()

    assert [row[0] for row in rows] == ["001-renamed"]


def test_checkout_refuses_dirty_worktree_before_db_reverts(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)
    base_branch = _run_git(repo_path, "branch", "--show-current")

    (repo_path / "README.md").write_text("base\n", encoding="utf-8")
    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "base")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    _run_git(repo_path, "checkout", "-b", "target")
    _run_git(repo_path, "rm", "001-init.up.sql", "001-init.down.sql")
    _run_git(repo_path, "commit", "-m", "remove migration")
    _run_git(repo_path, "checkout", base_branch)

    # Dirty tracked file to force checkout refusal before any DB operations.
    (repo_path / "README.md").write_text("dirty\n", encoding="utf-8")

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )
    assert checkout_result.exit_code == 1
    assert "Working tree is not clean" in checkout_result.output

    branch = _run_git(repo_path, "branch", "--show-current")
    assert branch == base_branch

    with sqlite3.connect(db_path) as connection:
        rows = connection.execute(
            "SELECT id FROM mitch_migrations ORDER BY id",
        ).fetchall()
        table = connection.execute(
            "SELECT name FROM sqlite_schema WHERE type='table' AND name='table_one'",
        ).fetchone()

    assert [row[0] for row in rows] == ["001-init"]
    assert table is not None


def test_checkout_allow_dirty_reverts_using_local_migration_files(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)
    base_branch = _run_git(repo_path, "branch", "--show-current")

    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "base migration")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    _run_git(repo_path, "checkout", "-b", "target")
    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int, name text);",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "changed migration on target")
    _run_git(repo_path, "checkout", base_branch)

    # Dirty local down-script change should be used for the pre-checkout revert.
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;\nCREATE TABLE dirty_marker (id int);",
        encoding="utf-8",
    )

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--allow-dirty",
        ],
    )
    assert checkout_result.exit_code == 0

    branch = _run_git(repo_path, "branch", "--show-current")
    assert branch == "target"

    # Stash pop restored local dirty change on top of target branch.
    down_script = (repo_path / "001-init.down.sql").read_text(encoding="utf-8")
    assert "dirty_marker" in down_script

    with sqlite3.connect(db_path) as connection:
        applied_ids = connection.execute(
            "SELECT id FROM mitch_migrations ORDER BY id",
        ).fetchall()
        table_columns = connection.execute(
            "PRAGMA table_info(table_one)",
        ).fetchall()
        marker_table = connection.execute(
            "SELECT name FROM sqlite_schema WHERE type='table' AND name='dirty_marker'",
        ).fetchone()

    assert [row[0] for row in applied_ids] == ["001-init"]
    assert any(column[1] == "name" for column in table_columns)
    assert marker_table is not None


def test_checkout_allow_dirty_reverts_dirty_migration_without_branch_migration_changes(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)
    base_branch = _run_git(repo_path, "branch", "--show-current")

    (repo_path / "README.md").write_text("base\n", encoding="utf-8")
    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "base migration")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    _run_git(repo_path, "checkout", "-b", "target")
    (repo_path / "README.md").write_text("target\n", encoding="utf-8")
    _run_git(repo_path, "add", "README.md")
    _run_git(repo_path, "commit", "-m", "non-migration target change")
    _run_git(repo_path, "checkout", base_branch)

    # Dirty down-script change should still trigger a pre-checkout revert.
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;\nCREATE TABLE dirty_marker (id int);",
        encoding="utf-8",
    )

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--allow-dirty",
        ],
    )
    assert checkout_result.exit_code == 0

    branch = _run_git(repo_path, "branch", "--show-current")
    assert branch == "target"

    down_script = (repo_path / "001-init.down.sql").read_text(encoding="utf-8")
    assert "dirty_marker" in down_script

    with sqlite3.connect(db_path) as connection:
        applied_ids = connection.execute(
            "SELECT id FROM mitch_migrations ORDER BY id",
        ).fetchall()
        table_exists = connection.execute(
            "SELECT name FROM sqlite_schema WHERE type='table' AND name='table_one'",
        ).fetchone()
        marker_table = connection.execute(
            "SELECT name FROM sqlite_schema WHERE type='table' AND name='dirty_marker'",
        ).fetchone()

    assert [row[0] for row in applied_ids] == ["001-init"]
    assert table_exists is not None
    assert marker_table is not None


def test_checkout_allow_dirty_redeploys_migration_locally_edited_to_match_target(tmp_path):
    # The current branch has v2 of a migration applied, the target branch has v1, and the file is
    # edited locally back to v1. A diff of the target against the working tree shows no migration
    # change, so a working-tree-based plan would skip the redeploy and leave the DB at v2.
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)

    v1 = "CREATE TABLE table_one (id int);"
    v2 = "CREATE TABLE table_one (id int, name text);"

    (repo_path / "001-init.up.sql").write_text(v1, encoding="utf-8")
    (repo_path / "001-init.down.sql").write_text("DROP TABLE table_one;", encoding="utf-8")
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "add 001 v1")
    _run_git(repo_path, "branch", "target")

    (repo_path / "001-init.up.sql").write_text(v2, encoding="utf-8")
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "change 001 to v2")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        ["up", "--project", str(repo_path), "--database", database_url, "--if-modified", "ignore"],
    )
    assert up_result.exit_code == 0

    # Edit the migration locally back to what the target branch has.
    (repo_path / "001-init.up.sql").write_text(v1, encoding="utf-8")
    assert _run_git(repo_path, "diff", "--name-only", "target", "--", "001-init.up.sql") == ""

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--allow-dirty",
        ],
    )
    assert checkout_result.exit_code == 0, checkout_result.output

    assert _run_git(repo_path, "branch", "--show-current") == "target"
    assert (repo_path / "001-init.up.sql").read_text(encoding="utf-8") == v1

    with sqlite3.connect(db_path) as connection:
        applied_ids = connection.execute("SELECT id FROM mitch_migrations").fetchall()
        columns = connection.execute("PRAGMA table_info(table_one)").fetchall()

    assert [row[0] for row in applied_ids] == ["001-init"]
    assert [column[1] for column in columns] == ["id"]


def test_checkout_allow_dirty_restores_locally_added_applied_migration_without_and_up(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)
    base_branch = _run_git(repo_path, "branch", "--show-current")

    (repo_path / "README.md").write_text("base\n", encoding="utf-8")
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "base commit")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    # Local-only migration (uncommitted) that is already applied.
    (repo_path / "001-local.up.sql").write_text(
        "CREATE TABLE local_table (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-local.down.sql").write_text(
        "DROP TABLE local_table;",
        encoding="utf-8",
    )
    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    _run_git(repo_path, "checkout", "-b", "target")
    (repo_path / "README.md").write_text("target\n", encoding="utf-8")
    _run_git(repo_path, "add", "README.md")
    _run_git(repo_path, "commit", "-m", "non-migration target change")
    _run_git(repo_path, "checkout", base_branch)

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--allow-dirty",
        ],
    )
    assert checkout_result.exit_code == 0

    with sqlite3.connect(db_path) as connection:
        applied_ids = connection.execute(
            "SELECT id FROM mitch_migrations ORDER BY id",
        ).fetchall()
        local_table = connection.execute(
            "SELECT name FROM sqlite_schema WHERE type='table' AND name='local_table'",
        ).fetchone()

    assert [row[0] for row in applied_ids] == ["001-local"]
    assert local_table is not None
    assert (repo_path / "001-local.up.sql").exists()


def test_checkout_allow_dirty_does_not_apply_locally_added_pending_migration_without_and_up(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)
    base_branch = _run_git(repo_path, "branch", "--show-current")

    (repo_path / "README.md").write_text("base\n", encoding="utf-8")
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "base commit")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    _run_git(repo_path, "checkout", "-b", "target")
    (repo_path / "README.md").write_text("target\n", encoding="utf-8")
    _run_git(repo_path, "add", "README.md")
    _run_git(repo_path, "commit", "-m", "non-migration target change")
    _run_git(repo_path, "checkout", base_branch)

    # Local-only migration (uncommitted) that was never applied.
    (repo_path / "001-local.up.sql").write_text(
        "CREATE TABLE local_table (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-local.down.sql").write_text(
        "DROP TABLE local_table;",
        encoding="utf-8",
    )

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--allow-dirty",
        ],
    )
    assert checkout_result.exit_code == 0

    with sqlite3.connect(db_path) as connection:
        applied_ids = connection.execute(
            "SELECT id FROM mitch_migrations ORDER BY id",
        ).fetchall()
        local_table = connection.execute(
            "SELECT name FROM sqlite_schema WHERE type='table' AND name='local_table'",
        ).fetchone()

    assert applied_ids == []
    assert local_table is None
    assert (repo_path / "001-local.up.sql").exists()


def test_checkout_does_not_deploy_migrations_added_on_target_branch_without_and_up(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)
    base_branch = _run_git(repo_path, "branch", "--show-current")

    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "base migration")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    _run_git(repo_path, "checkout", "-b", "target")
    (repo_path / "002-add.up.sql").write_text(
        "CREATE TABLE table_two (id int);",
        encoding="utf-8",
    )
    (repo_path / "002-add.down.sql").write_text(
        "DROP TABLE table_two;",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "add migration")
    _run_git(repo_path, "checkout", base_branch)

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )
    assert checkout_result.exit_code == 0

    with sqlite3.connect(db_path) as connection:
        applied_ids = connection.execute(
            "SELECT id FROM mitch_migrations ORDER BY id",
        ).fetchall()
        second_table = connection.execute(
            "SELECT name FROM sqlite_schema WHERE type='table' AND name='table_two'",
        ).fetchone()

    assert [row[0] for row in applied_ids] == ["001-init"]
    assert second_table is None


def test_checkout_deploys_migrations_added_on_target_branch_with_and_up(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)
    base_branch = _run_git(repo_path, "branch", "--show-current")

    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "base migration")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    _run_git(repo_path, "checkout", "-b", "target")
    (repo_path / "002-add.up.sql").write_text(
        "CREATE TABLE table_two (id int);",
        encoding="utf-8",
    )
    (repo_path / "002-add.down.sql").write_text(
        "DROP TABLE table_two;",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "add migration")
    _run_git(repo_path, "checkout", base_branch)

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--and-up",
        ],
    )
    assert checkout_result.exit_code == 0

    with sqlite3.connect(db_path) as connection:
        applied_ids = connection.execute(
            "SELECT id FROM mitch_migrations ORDER BY id",
        ).fetchall()
        second_table = connection.execute(
            "SELECT name FROM sqlite_schema WHERE type='table' AND name='table_two'",
        ).fetchone()

    assert [row[0] for row in applied_ids] == ["001-init", "002-add"]
    assert second_table is not None


def test_checkout_redeploys_dependants_of_changed_migration(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)
    base_branch = _run_git(repo_path, "branch", "--show-current")

    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;",
        encoding="utf-8",
    )
    (repo_path / "002-child.up.sql").write_text(
        "CREATE TABLE table_two (id int);",
        encoding="utf-8",
    )
    (repo_path / "002-child.down.sql").write_text(
        "DROP TABLE table_two;",
        encoding="utf-8",
    )
    (repo_path / "002-child.config.toml").write_text(
        'dependencies = ["001-init"]',
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "base chain")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    _run_git(repo_path, "checkout", "-b", "target")
    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int, name text);",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "change parent migration")
    _run_git(repo_path, "checkout", base_branch)

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )
    assert checkout_result.exit_code == 0

    with sqlite3.connect(db_path) as connection:
        applied_ids = connection.execute(
            "SELECT id FROM mitch_migrations ORDER BY id",
        ).fetchall()
        parent_columns = connection.execute(
            "PRAGMA table_info(table_one)",
        ).fetchall()
        child_table = connection.execute(
            "SELECT name FROM sqlite_schema WHERE type='table' AND name='table_two'",
        ).fetchone()

    assert [row[0] for row in applied_ids] == ["001-init", "002-child"]
    assert any(column[1] == "name" for column in parent_columns)
    assert child_table is not None


def test_checkout_handles_migration_id_changed_in_config(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)
    base_branch = _run_git(repo_path, "branch", "--show-current")

    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;",
        encoding="utf-8",
    )
    (repo_path / "001-init.config.toml").write_text(
        'id = "001-init"',
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "base id")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    _run_git(repo_path, "checkout", "-b", "target")
    (repo_path / "001-init.config.toml").write_text(
        'id = "001-renamed"',
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "rename migration id")
    _run_git(repo_path, "checkout", base_branch)

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )
    assert checkout_result.exit_code == 0
    assert checkout_result.exception is None

    with sqlite3.connect(db_path) as connection:
        applied_ids = connection.execute(
            "SELECT id FROM mitch_migrations ORDER BY id",
        ).fetchall()

    assert [row[0] for row in applied_ids] == ["001-renamed"]


def test_checkout_handles_config_added_for_existing_migration(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)
    base_branch = _run_git(repo_path, "branch", "--show-current")

    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "base without config")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    _run_git(repo_path, "checkout", "-b", "target")
    (repo_path / "001-init.config.toml").write_text(
        'id = "001-renamed"',
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "add config and rename id")
    _run_git(repo_path, "checkout", base_branch)

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )
    assert checkout_result.exit_code == 0
    assert checkout_result.exception is None

    with sqlite3.connect(db_path) as connection:
        applied_ids = connection.execute(
            "SELECT id FROM mitch_migrations ORDER BY id",
        ).fetchall()

    assert [row[0] for row in applied_ids] == ["001-renamed"]


def test_checkout_handles_config_removed_for_existing_migration(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)
    base_branch = _run_git(repo_path, "branch", "--show-current")

    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;",
        encoding="utf-8",
    )
    (repo_path / "001-init.config.toml").write_text(
        'id = "001-custom"',
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "base with config")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    _run_git(repo_path, "checkout", "-b", "target")
    _run_git(repo_path, "rm", "001-init.config.toml")
    _run_git(repo_path, "commit", "-m", "remove config")
    _run_git(repo_path, "checkout", base_branch)

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )
    assert checkout_result.exit_code == 0
    assert checkout_result.exception is None

    with sqlite3.connect(db_path) as connection:
        applied_ids = connection.execute(
            "SELECT id FROM mitch_migrations ORDER BY id",
        ).fetchall()
        table_exists = connection.execute(
            "SELECT name FROM sqlite_schema WHERE type='table' AND name='table_one'",
        ).fetchone()

    assert [row[0] for row in applied_ids] == ["001-init"]
    assert table_exists is not None


def test_checkout_handles_config_and_scripts_deleted_together(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)
    base_branch = _run_git(repo_path, "branch", "--show-current")

    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;",
        encoding="utf-8",
    )
    (repo_path / "001-init.config.toml").write_text(
        'id = "001-custom"',
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "base with migration config")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    _run_git(repo_path, "checkout", "-b", "target")
    _run_git(
        repo_path,
        "rm",
        "001-init.config.toml",
        "001-init.up.sql",
        "001-init.down.sql",
    )
    _run_git(repo_path, "commit", "-m", "remove migration and config")
    _run_git(repo_path, "checkout", base_branch)

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
        ],
    )
    assert checkout_result.exit_code == 0
    assert checkout_result.exception is None

    with sqlite3.connect(db_path) as connection:
        applied_ids = connection.execute(
            "SELECT id FROM mitch_migrations ORDER BY id",
        ).fetchall()
        table_exists = connection.execute(
            "SELECT name FROM sqlite_schema WHERE type='table' AND name='table_one'",
        ).fetchone()

    assert applied_ids == []
    assert table_exists is None


def test_checkout_allow_dirty_restores_stashed_changes_after_failure(tmp_path):
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    _write_project_config(repo_path)
    _init_git_repo(repo_path)
    base_branch = _run_git(repo_path, "branch", "--show-current")

    (repo_path / "README.md").write_text("base\n", encoding="utf-8")
    (repo_path / "001-init.up.sql").write_text(
        "CREATE TABLE table_one (id int);",
        encoding="utf-8",
    )
    (repo_path / "001-init.down.sql").write_text(
        "DROP TABLE table_one;",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "base migration")

    db_path = tmp_path / "test.db"
    database_url = f"sqlite:///{db_path}"

    up_result = runner.invoke(
        app,
        [
            "up",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--if-modified",
            "ignore",
        ],
    )
    assert up_result.exit_code == 0

    _run_git(repo_path, "checkout", "-b", "target")
    (repo_path / "002-broken.up.sql").write_text(
        "THIS IS NOT VALID SQL;",
        encoding="utf-8",
    )
    (repo_path / "002-broken.down.sql").write_text(
        "-- noop",
        encoding="utf-8",
    )
    _run_git(repo_path, "add", ".")
    _run_git(repo_path, "commit", "-m", "broken migration")
    _run_git(repo_path, "checkout", base_branch)

    (repo_path / "README.md").write_text("dirty local change\n", encoding="utf-8")

    checkout_result = runner.invoke(
        app,
        [
            "checkout",
            "target",
            "--project",
            str(repo_path),
            "--database",
            database_url,
            "--allow-dirty",
            "--and-up",
        ],
    )
    assert checkout_result.exit_code == 1

    restored_readme = (repo_path / "README.md").read_text(encoding="utf-8")
    stash_list = _run_git(repo_path, "stash", "list")

    assert restored_readme == "dirty local change\n"
    assert stash_list == ""
