from __future__ import annotations

import pytest

from pve_vm_setup.services.factory import ProxmoxServiceFactory
from pve_vm_setup.settings import AppSettings


def _load_live_settings_or_skip() -> AppSettings:
    settings = AppSettings.from_env()
    try:
        settings.validate_live_requirements()
    except Exception as exc:  # pragma: no cover - only hit outside configured environments
        pytest.skip(f"Live environment is not configured: {exc}")
    return settings


@pytest.mark.live
def test_live_read_only_reference_loading() -> None:
    settings = _load_live_settings_or_skip()
    service = ProxmoxServiceFactory.create(settings)

    assert service.mode == "live"
    assert service.check_connectivity()
    assert service.check_api_base()

    realms = service.load_realms()
    assert realms

    service.login(
        settings.proxmox_user or "",
        settings.proxmox_password or "",
        settings.proxmox_realm or "",
    )
    nodes = service.load_nodes()
    assert nodes

    pools = service.load_pools()
    assert isinstance(pools, list)

    tags = service.load_existing_tags()
    assert isinstance(tags, list)

    probe_node = settings.safety_policy.test_node or nodes[0].name
    storages = service.load_storages(probe_node)
    assert isinstance(storages, list)
    iso_storages = [storage for storage in storages if "iso" in storage.content]
    if iso_storages:
        isos = service.load_isos(probe_node, iso_storages[0].storage)
        assert isinstance(isos, list)


@pytest.mark.live_create
def test_live_create_path_requires_explicit_opt_in() -> None:
    settings = _load_live_settings_or_skip()
    if not settings.safety_policy.allow_create:
        pytest.skip("Set PROXMOX_PREVENT_CREATE=false to enable live create tests.")
    if settings.safety_policy.enable_test_mode:
        assert settings.safety_policy.test_node
