"""SSH key PEM validation (RSA / OPENSSH)."""

from pathlib import Path

import pytest

from server.utils.ssh_key_pem import prepare_ssh_key_preset_fields

NZ_ADMIN_PEM = Path("/home/r/下载/Telegram Desktop/nz-admin.pem")


def test_prepare_openssh_generated_key():
    import asyncssh

    key = asyncssh.generate_private_key("ssh-rsa")
    pem = key.export_private_key("openssh").decode()
    priv, pub = prepare_ssh_key_preset_fields(pem, None)
    assert priv.startswith("-----BEGIN OPENSSH PRIVATE KEY-----")
    assert pub.startswith("ssh-rsa ")


@pytest.mark.skipif(not NZ_ADMIN_PEM.is_file(), reason="local nz-admin.pem not present")
def test_prepare_rsa_pem_like_nz_admin():
    pem = NZ_ADMIN_PEM.read_text()
    priv, pub = prepare_ssh_key_preset_fields(pem, None)
    assert "BEGIN RSA PRIVATE KEY" in priv
    assert pub.startswith("ssh-rsa ")


def test_invalid_pem_rejected():
    with pytest.raises(ValueError, match="私钥格式无效"):
        prepare_ssh_key_preset_fields(
            "-----BEGIN RSA PRIVATE KEY-----\ninvalid\n-----END RSA PRIVATE KEY-----",
            None,
        )
