"""Unit tests for Alembic migration structure/import.

Actual upgrade/downgrade round-trips require a PostgreSQL database, so these
tests verify that migrations are importable, have the expected identifiers,
and declare the expected dependencies.
"""

import importlib.util
from pathlib import Path

import pytest


@pytest.mark.unit
def test_home_directory_migration_imports_and_rewrites() -> None:
    migration_path = Path(__file__).parent.parent.parent / (
        "alembic/versions/2026_06_14_104415_add_tool_type_home_directory.py"
    )
    assert migration_path.exists()

    spec = importlib.util.spec_from_file_location("home_dir_migration", migration_path)
    assert spec is not None and spec.loader is not None
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)

    assert module.revision == "2026_06_14_104415"
    assert module.down_revision == "f3d2dc90ba3a"
    assert callable(module.upgrade)
    assert callable(module.downgrade)
    assert module.OLD_WORKSPACE == "/workspace"
    assert module.NEW_WORKSPACE == "/home/user/{{WORKSPACE_NAME}}"


@pytest.mark.unit
def test_merge_migration_resolves_heads() -> None:
    migration_path = Path(__file__).parent.parent.parent / (
        "alembic/versions/fc8f1a20cbf6_merge_home_directory_and_pi_agent_mount_.py"
    )
    assert migration_path.exists()

    spec = importlib.util.spec_from_file_location("merge_migration", migration_path)
    assert spec is not None and spec.loader is not None
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)

    assert module.revision == "fc8f1a20cbf6"
    assert "2026_06_14_104415" in module.down_revision
    assert "8c6d1dbd4798" in module.down_revision
    assert callable(module.upgrade)


@pytest.mark.unit
def test_remove_pi_agent_repo_mount_migration_imports() -> None:
    migration_path = Path(__file__).parent.parent.parent / (
        "alembic/versions/2026_06_15_090500_remove_pi_agent_explicit_repo_mount.py"
    )
    assert migration_path.exists()

    spec = importlib.util.spec_from_file_location(
        "remove_repo_mount_migration", migration_path
    )
    assert spec is not None and spec.loader is not None
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)

    assert module.revision == "2026_06_15_090500"
    assert module.down_revision == "2026_06_14_182955"
    assert callable(module.upgrade)
    assert callable(module.downgrade)
