"""D-G25 tests — autostart get/set + managed_save through the SDK.

Round-trips ``client.get_autostart`` / ``set_autostart`` / ``managed_save`` over
an injected ``FakeDomainPolicyBackend``, and pins the no-backend
``TransportError`` (mirroring the metrics-read path).
"""

from __future__ import annotations

import pytest
from mgf.vm.core.contracts import VmSpec
from mgf.vm.core.exceptions import OperationError, TransportError
from mgf.vm.core.fakes.domain_policy import FakeDomainPolicyBackend
from mgf.vm.core.fakes.hypervisor import FakeHypervisorBackend
from mgf.vm.core.ids import DomainId

from mgf.vm.sdk.client import VmManagerClient
from mgf.vm.sdk.transport.inprocess import InProcessTransport


def _spec(name: str = "policy-vm") -> VmSpec:
    return VmSpec(name=name, cpu=2, memory_bytes=2 << 30)


def _client(policy: FakeDomainPolicyBackend | None) -> VmManagerClient:
    hv = FakeHypervisorBackend()
    return VmManagerClient(InProcessTransport.from_adapters(hv, policy=policy))


def test_set_then_get_autostart_round_trip() -> None:
    policy = FakeDomainPolicyBackend()
    client = _client(policy)
    vm_id = client.create_vm(_spec()).vm_id
    policy._register_domain(DomainId(vm_id.value))

    assert client.get_autostart(vm_id) is False
    client.set_autostart(vm_id, enabled=True)
    assert client.get_autostart(vm_id) is True
    client.set_autostart(vm_id, enabled=False)
    assert client.get_autostart(vm_id) is False


def test_managed_save_running_domain_succeeds() -> None:
    policy = FakeDomainPolicyBackend()
    client = _client(policy)
    vm_id = client.create_vm(_spec()).vm_id
    policy._register_domain(DomainId(vm_id.value), running=True)

    client.managed_save(vm_id)  # no raise


def test_managed_save_stopped_domain_raises_operation_error() -> None:
    policy = FakeDomainPolicyBackend()
    client = _client(policy)
    vm_id = client.create_vm(_spec()).vm_id
    policy._register_domain(DomainId(vm_id.value), running=False)

    with pytest.raises(OperationError):
        client.managed_save(vm_id)


def test_get_autostart_without_policy_backend_raises_transport_error() -> None:
    client = _client(None)
    vm_id = client.create_vm(_spec()).vm_id
    with pytest.raises(TransportError):
        client.get_autostart(vm_id)


def test_set_autostart_without_policy_backend_raises_transport_error() -> None:
    client = _client(None)
    vm_id = client.create_vm(_spec()).vm_id
    with pytest.raises(TransportError):
        client.set_autostart(vm_id, enabled=True)
