"""Storage conformance scenarios (CONF-S-* in ``contracts.md`` §10)."""

from __future__ import annotations

from typing import TYPE_CHECKING

from mgf.vm.core.contracts import VolumeSpec
from mgf.vm.core.exceptions import VolumeHasSnapshots, VolumeNotFound

if TYPE_CHECKING:
    from mgf.vm.core.contracts import StorageBackend


def _volume_spec(
    pool: str = "default",
    name: str = "conf-vol",
    size: int = 16 * 1024 * 1024,
) -> VolumeSpec:
    return VolumeSpec(pool=pool, name=name, size_bytes=size, format="qcow2")


def create_list_delete_volume_round_trip(adapter: StorageBackend) -> None:
    """CONF-S-01 — create, list, delete a volume; verify it disappears."""
    v = adapter.create_volume(_volume_spec(name="conf-s-01"))
    listed = [info.volume_id for info in adapter.list_volumes("default")]
    assert v in listed, "newly-created volume must appear in list_volumes"
    adapter.delete_volume(v)
    # After delete, get_volume must raise VolumeNotFound.
    raised = False
    try:
        adapter.get_volume(v)
    except VolumeNotFound:
        raised = True
    assert raised, "deleted volume must raise VolumeNotFound on get_volume"


def volume_with_snapshots_refuses_delete(adapter: StorageBackend) -> None:
    """CONF-S-03 — a volume with derived snapshots cannot be deleted.

    Reference-counted GC per ``contracts.md`` §4.
    """
    v = adapter.create_volume(_volume_spec(name="conf-s-03"))
    try:
        adapter.snapshot_volume(v, "snap1")
        raised = False
        try:
            adapter.delete_volume(v)
        except VolumeHasSnapshots:
            raised = True
        assert raised, "volume with snapshots must raise VolumeHasSnapshots on delete"
    finally:
        # Cleanup: delete snapshots then the volume. Best-effort.
        try:
            for snap in adapter.list_snapshots(v):
                adapter.delete_snapshot(snap.snapshot_id)
            adapter.delete_volume(v)
        except Exception:
            pass


__all__ = [
    "create_list_delete_volume_round_trip",
    "volume_with_snapshots_refuses_delete",
]
