from __future__ import annotations

from io import StringIO

from pve_vm_setup.doctor import run_live_doctor
from pve_vm_setup.services.base import AuthenticatedSession, Node, Pool, Realm
from pve_vm_setup.settings import AppSettings


class StubDoctorService:
    mode = "live"

    def check_connectivity(self) -> str:
        return "HTTP 200"

    def check_api_base(self) -> str:
        return "8.2"

    def load_realms(self) -> list[Realm]:
        return [Realm(name="pam", title="Linux PAM standard authentication", default=True)]

    def login(self, username: str, password: str, realm: str) -> AuthenticatedSession:
        return AuthenticatedSession(username=f"{username}@{realm}", ticket="ticket")

    def load_nodes(self) -> list[Node]:
        return [Node(name="pve-test-01")]

    def load_pools(self) -> list[Pool]:
        return [Pool(poolid="sandbox")]

    def load_existing_tags(self) -> list[str]:
        return []

    def load_storages(self, node: str):
        raise AssertionError("not used in doctor")

    def load_isos(self, node: str, storage: str):
        raise AssertionError("not used in doctor")


class StubFactory:
    @staticmethod
    def create(settings: AppSettings) -> StubDoctorService:
        return StubDoctorService()


def test_doctor_succeeds_and_keeps_secrets_out_of_output() -> None:
    settings = AppSettings.from_env(
        {
            "PROXMOX_URL": "https://proxmox.example.invalid:8006",
            "PROXMOX_USER": "root",
            "PROXMOX_PASSWORD": "super-secret",
            "PROXMOX_REALM": "pam",
        },
        load_dotenv_file=False,
    )
    stream = StringIO()

    exit_code = run_live_doctor(settings, stream=stream, service_factory=StubFactory)

    output = stream.getvalue()
    assert exit_code == 0
    assert "Doctor finished successfully." in output
    assert "super-secret" not in output
    assert "root@pam" in output
    assert "host: proxmox.example.invalid:8006" in output


def test_doctor_validates_create_scope_when_enabled() -> None:
    settings = AppSettings.from_env(
        {
            "PROXMOX_URL": "https://proxmox.example.invalid:8006",
            "PROXMOX_USER": "root",
            "PROXMOX_PASSWORD": "super-secret",
            "PROXMOX_REALM": "pam",
            "PROXMOX_PREVENT_CREATE": "false",
            "PROXMOX_ENABLE_TEST_MODE": "true",
            "PROXMOX_TEST_NODE": "pve-test-01",
            "PROXMOX_TEST_POOL": "sandbox",
        },
        load_dotenv_file=False,
    )
    stream = StringIO()

    exit_code = run_live_doctor(settings, stream=stream, service_factory=StubFactory)

    output = stream.getvalue()
    assert exit_code == 0
    assert "prevent_create: False" in output
    assert "enable_test_mode: True" in output
    assert "node=pve-test-01" in output
    assert "pool=sandbox" in output
    assert "tag=codex-e2e" in output
    assert "name_prefix=codex-e2e-" in output
