"""Smoke + integration tests for the lifted-from-mgf-vm domain layer.

Phase A of Phase 0 Stream A: the foundational domain types
(``VMHandle``, ``VMState``, ``VMSpec``, the exception hierarchy,
the ``common/`` utilities) port from the old ``mgf-vm`` umbrella
into ``mgf.vm.core.*``. The new contracts (the four Protocols
in ``contracts.md``) land in a later iteration.
"""

from __future__ import annotations

import mgf.vm.core as core
from mgf.vm.core import IsolationLevel, VMHandle, VMState, VMStatus
from mgf.vm.core.common.atomic_io import atomic_write
from mgf.vm.core.exceptions import (
    DomainNotFoundError,
    ImportExportError,
    OperationError,
    VManagerError,
)


def test_version_set() -> None:
    """``__version__`` exposed and parseable."""
    assert hasattr(core, "__version__")
    parts = core.__version__.split(".")
    assert len(parts) >= 2
    assert all(p.isdigit() for p in parts[:2])


def test_all_lists_versions_and_domain() -> None:
    """AP-01: ``__all__`` enumerates the public surface."""
    assert isinstance(core.__all__, list)
    assert "__version__" in core.__all__
    assert "VMHandle" in core.__all__
    assert "VMState" in core.__all__


def test_vmstate_is_dataclass() -> None:
    """``VMState`` is a frozen dataclass (the live state entry)."""
    import dataclasses

    assert dataclasses.is_dataclass(VMState)


def test_vmstatus_enum_has_running() -> None:
    """``VMStatus`` mirrors libvirt's documented states."""
    # See domain.py — the enum reflects libvirt-domain-state semantics.
    members = {m.name for m in VMStatus}
    # Spot-check: a long-running VM state is present.
    assert any("RUNN" in m.upper() for m in members), f"VMStatus members: {members}"


def test_isolation_level_is_strenum() -> None:
    """``IsolationLevel`` is a StrEnum (engine-neutral policy per D-C6)."""
    # Spot-check that the canonical levels exist.
    members = list(IsolationLevel)
    assert len(members) >= 2


def test_vmhandle_is_frozen_dataclass() -> None:
    """``VMHandle`` is a frozen dataclass (DP-03)."""
    import dataclasses

    assert dataclasses.is_dataclass(VMHandle)


def test_exception_hierarchy_roots_at_vmanager_error() -> None:
    """Every typed VManager exception subclasses ``VManagerError``.

    Mirrors EH-01: every error raised by app code subclasses the
    application's base error.
    """
    assert issubclass(OperationError, VManagerError)
    assert issubclass(DomainNotFoundError, VManagerError)
    assert issubclass(ImportExportError, VManagerError)


def test_atomic_write_lives_in_common(tmp_path) -> None:  # type: ignore[no-untyped-def]
    """``mgf.vm.core.common.atomic_write`` ported and callable."""
    target = tmp_path / "out.txt"
    atomic_write(target, b"hello")
    assert target.read_bytes() == b"hello"
