"""Tests for the OPTIONAL ``DomainPolicyBackend`` (D-G25) + its fake.

Pins the contract semantics the SDK + app depend on: autostart get/set,
managed-save's running precondition, and ``DomainNotFound`` for unknown
domains. Also confirms ``FakeDomainPolicyBackend`` structurally satisfies the
``DomainPolicyBackend`` Protocol.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest

from mgf.vm.core.exceptions import DomainNotFound, OperationError
from mgf.vm.core.fakes import FakeDomainPolicyBackend
from mgf.vm.core.ids import DomainId

if TYPE_CHECKING:
    from mgf.vm.core.contracts import DomainPolicyBackend

_D = DomainId("vm-1")


def _backend() -> FakeDomainPolicyBackend:
    return FakeDomainPolicyBackend()


def test_fake_satisfies_protocol() -> None:
    backend: DomainPolicyBackend = FakeDomainPolicyBackend()
    assert backend is not None


def test_get_autostart_defaults_false_for_known_domain() -> None:
    b = _backend()
    b._register_domain(_D)
    assert b.get_autostart(_D) is False


def test_set_then_get_autostart_round_trips() -> None:
    b = _backend()
    b._register_domain(_D)
    b.set_autostart(_D, enabled=True)
    assert b.get_autostart(_D) is True
    b.set_autostart(_D, enabled=False)
    assert b.get_autostart(_D) is False


def test_register_with_initial_autostart() -> None:
    b = _backend()
    b._register_domain(_D, autostart=True)
    assert b.get_autostart(_D) is True


def test_get_autostart_unknown_domain_raises() -> None:
    with pytest.raises(DomainNotFound):
        _backend().get_autostart(_D)


def test_set_autostart_unknown_domain_raises() -> None:
    with pytest.raises(DomainNotFound):
        _backend().set_autostart(_D, enabled=True)


def test_managed_save_running_domain_succeeds() -> None:
    b = _backend()
    b._register_domain(_D, running=True)
    b.managed_save(_D)  # no raise


def test_managed_save_stopped_domain_raises_operation_error() -> None:
    b = _backend()
    b._register_domain(_D, running=False)
    with pytest.raises(OperationError):
        b.managed_save(_D)


def test_managed_save_unknown_domain_raises_domain_not_found() -> None:
    with pytest.raises(DomainNotFound):
        _backend().managed_save(_D)
