"""Real-engine conformance for the Wave-B observation surfaces (CONF-M-*).

Drives the OPTIONAL ``mgf.vm.core.conformance`` metrics suite (CONF-M-01)
against a LIVE :class:`mgf.vm.libvirt._metrics.LibvirtMetricsBackend` over the
``test:///default`` fake driver (ships with every libvirt install; no
privileges). Also exercises the richer-snapshot read path end-to-end (a
snapshot description round-trips through ``list_snapshots``).

Marked ``@pytest.mark.conformance`` (Tier 2). SKIPPED gracefully if
``libvirt.open(uri)`` raises (no engine on this host).
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest

if TYPE_CHECKING:
    from collections.abc import Iterator

pytestmark = pytest.mark.conformance

_URI = "test:///default"


def _open_connection() -> object:
    """Open a wrapped connection against the live test driver, or skip."""
    try:
        import libvirt
    except ImportError:
        pytest.skip("libvirt-python not installed")
    try:
        conn = libvirt.open(_URI)
    except Exception as exc:  # any open failure → skip gracefully
        pytest.skip(f"cannot open {_URI!r}: {exc}")
    if conn is None:
        pytest.skip(f"libvirt.open({_URI!r}) returned None")
    conn.close()

    from mgf.vm.libvirt._connection import LibvirtConnection

    return LibvirtConnection.open(_URI)


@pytest.fixture
def connection() -> Iterator[object]:
    conn = _open_connection()
    try:
        yield conn
    finally:
        conn.close()  # type: ignore[attr-defined]


def _known_domain_id(connection: object) -> object:
    """The UUID of the ``test`` domain the live test driver always ships."""
    from mgf.vm.core.ids import DomainId

    with connection.lock:  # type: ignore[attr-defined]
        raw = connection.raw()  # type: ignore[attr-defined]
        dom = raw.lookupByName("test")
        return DomainId(dom.UUIDString())


def test_conf_m_01_sample_metrics_observation(connection: object) -> None:
    """CONF-M-01 — sample_metrics returns a UTC-aware MetricsSample (Wave-B)."""
    from mgf.vm.core.conformance import metrics_conformance_suite

    from mgf.vm.libvirt._metrics import LibvirtMetricsBackend

    backend = LibvirtMetricsBackend(connection)  # type: ignore[arg-type]
    known = _known_domain_id(connection)
    suite = metrics_conformance_suite(backend, known_domain=known)  # type: ignore[arg-type]
    result = suite.run_one("CONF-M-01")
    if result.error is not None:
        raise result.error
    assert result.passed


def test_sample_metrics_live_shape(connection: object) -> None:
    """A live sample of the ``test`` domain carries cumulative counters."""
    from mgf.vm.libvirt._metrics import LibvirtMetricsBackend

    backend = LibvirtMetricsBackend(connection)  # type: ignore[arg-type]
    known = _known_domain_id(connection)
    sample = backend.sample_metrics(known)  # type: ignore[arg-type]
    assert sample.cpu_time_ns >= 0
    assert sample.memory_used_bytes > 0
    assert sample.sampled_at.tzinfo is not None


def test_snapshot_description_round_trips(connection: object) -> None:
    """A snapshot's description round-trips through the richer read path.

    Takes a snapshot with a description directly via the engine, then reads it
    back through :meth:`LibvirtHypervisorBackend.list_snapshots` and asserts
    the Wave-B ``description`` field carries it.
    """
    from mgf.vm.core.ids import DomainId

    from mgf.vm.libvirt._hypervisor import LibvirtHypervisorBackend

    name = "conf-m-desc-snap"
    with connection.lock:  # type: ignore[attr-defined]
        raw = connection.raw()  # type: ignore[attr-defined]
        dom = raw.lookupByName("test")
        domain_id = DomainId(dom.UUIDString())
        dom.snapshotCreateXML(
            f"<domainsnapshot><name>{name}</name>"
            "<description>round-trip me</description></domainsnapshot>",
            0,
        )

    backend = LibvirtHypervisorBackend(connection=connection)  # type: ignore[arg-type]
    snaps = {s.name: s for s in backend.list_snapshots(domain_id)}
    assert name in snaps, "the snapshot we just created should be listed"
    assert snaps[name].description == "round-trip me"
