"""Tests for :mod:`mgf.vm.core.security.isolation.checks.runtime` (MA-A3.1)."""

from __future__ import annotations

from typing import Any

from _isolation_xml import domain_with, parsed

from mgf.vm.core.security.isolation.checks.runtime import (
    runtime_apparmor_enforcing,
    runtime_libvirt_uri_system,
    runtime_network_active_isolated,
    runtime_no_open_host_paths,
)
from mgf.vm.core.security.isolation.context import AnalysisContext
from mgf.vm.core.security.isolation.types import (
    FixKind,
    IsolationCategory,
)


def _ctx(**facts: Any) -> AnalysisContext:
    return AnalysisContext(
        domain_xml=parsed(domain_with()),
        vm_name="t",
        runtime_audit=True,
        host_facts=dict(facts),
    )


# ---------------------------------------------------------------------------
# runtime.libvirt_uri_system
# ---------------------------------------------------------------------------


class TestLibvirtUriSystem:
    def test_passes_for_system_uri(self) -> None:
        f = runtime_libvirt_uri_system(_ctx(**{"libvirt.uri": "qemu:///system"}))
        assert f.passing is True
        assert f.category is IsolationCategory.BLOCKING

    def test_fails_for_session_uri(self) -> None:
        f = runtime_libvirt_uri_system(_ctx(**{"libvirt.uri": "qemu:///session"}))
        assert f.passing is False
        assert f.fix_kind is FixKind.MANUAL
        assert "session mode" in f.summary

    def test_fails_for_remote_uri(self) -> None:
        f = runtime_libvirt_uri_system(
            _ctx(**{"libvirt.uri": "qemu+ssh://other-host/system"}),
        )
        assert f.passing is False

    def test_fails_when_uri_missing(self) -> None:
        # Empty / missing host_facts → fails (we can't confirm system).
        f = runtime_libvirt_uri_system(_ctx())
        assert f.passing is False


# ---------------------------------------------------------------------------
# runtime.apparmor_enforcing
# ---------------------------------------------------------------------------


class TestApparmorEnforcing:
    def test_passes_when_enforce(self) -> None:
        f = runtime_apparmor_enforcing(
            _ctx(
                **{
                    "apparmor.profile_state": "enforce",
                    "apparmor.profile_name": "libvirt-qemu",
                },
            )
        )
        assert f.passing is True

    def test_fails_when_complain(self) -> None:
        f = runtime_apparmor_enforcing(
            _ctx(
                **{
                    "apparmor.profile_state": "complain",
                    "apparmor.profile_name": "libvirt-qemu",
                },
            )
        )
        assert f.passing is False
        assert f.fix_kind is FixKind.HOST_LEVEL

    def test_fails_when_unconfined(self) -> None:
        f = runtime_apparmor_enforcing(
            _ctx(
                **{"apparmor.profile_state": "", "apparmor.profile_name": "unconfined"},
            )
        )
        assert f.passing is False

    def test_fails_when_no_facts(self) -> None:
        f = runtime_apparmor_enforcing(_ctx())
        assert f.passing is False


# ---------------------------------------------------------------------------
# runtime.no_open_host_paths
# ---------------------------------------------------------------------------


class TestNoOpenHostPaths:
    def test_passes_when_no_suspect_paths(self) -> None:
        f = runtime_no_open_host_paths(_ctx(**{"qemu.open_paths": []}))
        assert f.passing is True

    def test_fails_when_suspect_paths_present(self) -> None:
        f = runtime_no_open_host_paths(
            _ctx(
                **{"qemu.open_paths": ["/etc/passwd", "/srv/data"]},
            )
        )
        assert f.passing is False
        assert "/etc/passwd" in str(f.details["suspect_paths"])

    def test_passes_when_facts_missing(self) -> None:
        # No data → assume passing (the analyzer logs the missing fact).
        f = runtime_no_open_host_paths(_ctx())
        assert f.passing is True


# ---------------------------------------------------------------------------
# runtime.network_active_isolated
# ---------------------------------------------------------------------------


class TestNetworkActiveIsolated:
    def test_passes_when_all_isolated(self) -> None:
        f = runtime_network_active_isolated(
            _ctx(
                **{"network.active_state": [("vmanager-quarantine", True)]},
            )
        )
        assert f.passing is True

    def test_passes_when_no_networks(self) -> None:
        f = runtime_network_active_isolated(
            _ctx(
                **{"network.active_state": []},
            )
        )
        assert f.passing is True

    def test_fails_when_one_drifted(self) -> None:
        f = runtime_network_active_isolated(
            _ctx(
                **{
                    "network.active_state": [
                        ("vmanager-quarantine", True),
                        ("default", False),
                    ],
                },
            )
        )
        assert f.passing is False
        assert "default" in str(f.details["drifted"])
        assert f.fix_executor == "network.swap_to_quarantine"
