"""Tests for :mod:`mgf.vm.core.configurator.firmware` (pure planner)."""

from __future__ import annotations

import xml.etree.ElementTree as ET

import pytest

from mgf.vm.core.configurator import firmware
from mgf.vm.core.exceptions import SpecValidationError


def _bios_dom() -> ET.Element:
    return ET.fromstring("<domain><name>web</name><uuid>u</uuid><os><type>hvm</type></os></domain>")


def _uefi_dom(secure: bool = False) -> ET.Element:
    secure_attr = " secure='yes'" if secure else ""
    return ET.fromstring(
        f"<domain><name>web</name><uuid>u</uuid>"
        f"<os><type>hvm</type>"
        f"<loader readonly='yes' type='pflash'{secure_attr}>/usr/share/OVMF/OVMF_CODE.fd</loader>"
        f"</os></domain>"
    )


class TestPlan:
    def test_bios_to_uefi_requires_shutdown(self) -> None:
        change = firmware.plan(_bios_dom(), firmware="uefi")
        assert "bios -> uefi" in change.summary
        assert change.requires_shutdown is True
        assert "OVMF" in change.new_xml

    def test_uefi_to_bios_drops_loader(self) -> None:
        change = firmware.plan(_uefi_dom(), firmware="bios")
        assert "uefi -> bios" in change.summary
        assert change.requires_shutdown is True
        assert "OVMF" not in change.new_xml

    def test_enable_secure_boot_on_uefi(self) -> None:
        change = firmware.plan(_uefi_dom(), secure_boot=True)
        assert "secure_boot -> on" in change.summary
        assert change.requires_shutdown is True
        assert "secure='yes'" in change.new_xml or 'secure="yes"' in change.new_xml

    def test_disable_secure_boot_on_uefi(self) -> None:
        change = firmware.plan(_uefi_dom(secure=True), secure_boot=False)
        assert "secure_boot -> off" in change.summary
        assert "secure=" not in change.new_xml

    def test_noop_plan(self) -> None:
        change = firmware.plan(_bios_dom(), firmware="bios")
        assert change.summary == "no change"
        assert change.requires_shutdown is False

    def test_invalid_firmware_value(self) -> None:
        with pytest.raises(SpecValidationError):
            firmware.plan(_bios_dom(), firmware="coreboot")
