"""Tests for :mod:`mgf.vm.core.security.isolation.checks.display` (MA-A2.5)."""

from __future__ import annotations

from _isolation_xml import domain_with, parsed

from mgf.vm.core.security.isolation.checks.display import (
    display_local_only,
    display_password_set,
)
from mgf.vm.core.security.isolation.context import AnalysisContext
from mgf.vm.core.security.isolation.types import FixKind, IsolationCategory


def _ctx(*body: str) -> AnalysisContext:
    return AnalysisContext(
        domain_xml=parsed(domain_with(*body)),
        vm_name="t",
    )


class TestDisplayLocalOnly:
    def test_passes_when_no_graphics(self) -> None:
        f = display_local_only(_ctx())
        assert f.passing is True

    def test_passes_for_loopback_listen(self) -> None:
        body = "<graphics type='spice' listen='127.0.0.1' autoport='yes'/>"
        f = display_local_only(_ctx(body))
        assert f.passing is True

    def test_passes_for_ipv6_loopback(self) -> None:
        body = "<graphics type='vnc' listen='::1' autoport='yes'/>"
        f = display_local_only(_ctx(body))
        assert f.passing is True

    def test_fails_for_wildcard_listen(self) -> None:
        body = "<graphics type='spice' listen='0.0.0.0' autoport='yes'/>"
        f = display_local_only(_ctx(body))
        assert f.passing is False
        assert f.category is IsolationCategory.BLOCKING
        assert f.fix_kind is FixKind.AUTO_FIX
        assert f.fix_executor == "graphics.localhost_listen"

    def test_fails_for_specific_lan_address(self) -> None:
        body = "<graphics type='spice' listen='192.168.1.10' autoport='yes'/>"
        f = display_local_only(_ctx(body))
        assert f.passing is False

    def test_fails_when_listen_unset(self) -> None:
        body = "<graphics type='spice' autoport='yes'/>"
        f = display_local_only(_ctx(body))
        assert f.passing is False

    def test_handles_listen_child_element(self) -> None:
        # libvirt also accepts <listen address='X'/> as a child element.
        body = "<graphics type='spice' autoport='yes'><listen type='address' address='127.0.0.1'/></graphics>"
        f = display_local_only(_ctx(body))
        assert f.passing is True


class TestDisplayPasswordSet:
    def test_passes_when_no_graphics(self) -> None:
        f = display_password_set(_ctx())
        assert f.passing is True

    def test_passes_when_password_set(self) -> None:
        body = "<graphics type='spice' listen='127.0.0.1' passwd='secret123' autoport='yes'/>"
        f = display_password_set(_ctx(body))
        assert f.passing is True
        assert f.category is IsolationCategory.ADVISORY

    def test_fails_when_password_missing(self) -> None:
        body = "<graphics type='spice' listen='127.0.0.1' autoport='yes'/>"
        f = display_password_set(_ctx(body))
        assert f.passing is False
        assert f.fix_executor == "graphics.set_password"
