import pytest

from pve_vm_setup.errors import SettingsError
from pve_vm_setup.settings import AppSettings


def test_settings_load_defaults_and_normalize_api_base() -> None:
    settings = AppSettings.from_env(
        {
            "PROXMOX_URL": "https://proxmox.example.invalid:8006/",
            "PROXMOX_USER": "root",
            "PROXMOX_PASSWORD": "secret",
            "PROXMOX_REALM": "pam",
            "PROXMOX_API_BASE": "api2/json",
        },
        load_dotenv_file=False,
    )

    assert settings.proxmox_url == "https://proxmox.example.invalid:8006"
    assert settings.proxmox_api_base == "/api2/json"
    assert settings.proxmox_verify_tls is False
    assert settings.request_timeout_seconds == 15
    assert settings.default_iso_selector is None
    assert settings.effective_username == "root@pam"
    assert settings.safety_policy.prevent_create is False
    assert settings.safety_policy.enable_test_mode is False
    assert settings.safety_policy.test_tag == "codex-e2e"
    assert settings.safety_policy.test_vm_name_prefix == "codex-e2e-"


def test_settings_reject_test_mode_without_required_scope() -> None:
    with pytest.raises(SettingsError):
        AppSettings.from_env(
            {
                "PROXMOX_ENABLE_TEST_MODE": "true",
            },
            load_dotenv_file=False,
        )


def test_settings_allow_create_without_test_scope_when_test_mode_disabled() -> None:
    settings = AppSettings.from_env(
        {
            "PROXMOX_PREVENT_CREATE": "false",
        },
        load_dotenv_file=False,
    )

    assert settings.safety_policy.allow_create is True
    assert settings.safety_policy.enable_test_mode is False


def test_settings_allow_create_by_default_when_prevent_flag_is_unset() -> None:
    settings = AppSettings.from_env({}, load_dotenv_file=False)

    assert settings.safety_policy.prevent_create is False
    assert settings.safety_policy.allow_create is True


def test_settings_reject_invalid_default_iso_regex_selector() -> None:
    with pytest.raises(SettingsError):
        AppSettings.from_env(
            {
                "PROXMOX_DEFAULT_ISO_SELECTOR": "regex:[unterminated",
            },
            load_dotenv_file=False,
        )
