"""Real-engine conformance for ``LibvirtHypervisorBackend`` (CONF-H-*).

Drives the ``mgf.vm.core.conformance`` hypervisor suite against a LIVE
libvirt connection (the ``test:///default`` fake driver, which ships
with every libvirt install and needs no privileges). Per the task:

* CONF-H-01 — define → start → stop → undefine round-trip
* CONF-H-02 — define idempotency (same spec → same DomainId; conflict)
* CONF-H-03 — start idempotency (already-running is success)

Marked ``@pytest.mark.conformance`` (Tier 2). SKIPPED gracefully if
``libvirt.open(uri)`` raises (no engine on this host). Scenarios are
capability-gated via ``backend.capabilities()`` per contracts.md §10.
"""

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_backend() -> object:
    """Open a backend 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 import LibvirtHypervisorBackend

    return LibvirtHypervisorBackend(_URI)


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


def test_capabilities_reports_engine(backend: object) -> None:
    caps = backend.capabilities()  # type: ignore[attr-defined]
    assert caps.engine.startswith("libvirt")
    assert caps.engine_version


def test_conf_h_01_define_start_stop_undefine(backend: object) -> None:
    from mgf.vm.core.conformance import hypervisor_conformance_suite

    suite = hypervisor_conformance_suite(backend)  # type: ignore[arg-type]
    result = suite.run_one("CONF-H-01")
    if result.error is not None:
        raise result.error
    assert result.passed


def test_conf_h_02_define_idempotency(backend: object) -> None:
    from mgf.vm.core.conformance import hypervisor_conformance_suite

    suite = hypervisor_conformance_suite(backend)  # type: ignore[arg-type]
    result = suite.run_one("CONF-H-02")
    if result.error is not None:
        raise result.error
    assert result.passed


def test_conf_h_03_start_idempotency(backend: object) -> None:
    from mgf.vm.core.conformance import hypervisor_conformance_suite

    suite = hypervisor_conformance_suite(backend)  # type: ignore[arg-type]
    result = suite.run_one("CONF-H-03")
    if result.error is not None:
        raise result.error
    assert result.passed


def test_conf_h_11_network_observation(backend: object) -> None:
    """CONF-H-11 — host-network observation (D-G14) against the live driver.

    ``test:///default`` ships the ``default`` virtual network, so
    ``list_networks`` sees it; ``network_leases`` degrades to ``()`` on the
    test driver (which does not implement ``virNetworkGetDHCPLeases``), which
    the neutral contract treats as "no observed leases."
    """
    from mgf.vm.core.conformance import hypervisor_conformance_suite

    suite = hypervisor_conformance_suite(backend)  # type: ignore[arg-type]
    result = suite.run_one("CONF-H-11")
    if result.error is not None:
        raise result.error
    assert result.passed


def test_list_networks_sees_default_net(backend: object) -> None:
    """The live test driver ships a ``default`` network with a bridge."""
    nets = backend.list_networks()  # type: ignore[attr-defined]
    by_name = {n.name: n for n in nets}
    assert "default" in by_name, "test:///default ships a 'default' network"
    assert by_name["default"].bridge, "the default network reports a bridge"


def test_conf_run_all_hypervisor_catalog(backend: object) -> None:
    """Run the full registered hypervisor catalog; assert all pass."""
    from mgf.vm.core.conformance import hypervisor_conformance_suite

    suite = hypervisor_conformance_suite(backend)  # type: ignore[arg-type]
    suite.run_all()
    assert "passed" in suite.summary()


def test_read_domain_xml_live_round_trip(backend: object) -> None:
    """Live escape-hatch read: ``test:///default`` ships a domain ``test``.

    Exercises :meth:`LibvirtHypervisorBackend.read_domain_xml` end-to-end
    against a real (fake-driver) libvirt connection: the returned string is
    raw libvirt domain XML that parses and contains the domain name. This is
    the libvirt escape hatch (off the neutral Protocol), so it is verified
    only here against a real engine, gated like the other conformance tests.
    """
    from defusedxml import ElementTree as DefusedET

    xml = backend.read_domain_xml("test")  # type: ignore[attr-defined]
    assert isinstance(xml, str)
    root = DefusedET.fromstring(xml)  # parses as well-formed XML
    assert root.findtext("name") == "test"
