# -*- coding: utf-8 -*-
"""test_crypto.py — 凭据加密测试"""

import os

from service_monitor.utils import crypto


def test_roundtrip(monkeypatch):
    monkeypatch.setenv("MONITOR_ENC_KEY", "abcdefghijklmnopabcdefghijklmnop")
    plain = "mySSHpw@123!"
    token = crypto.encrypt_password(plain)
    assert token.startswith("enc:")
    assert crypto.decrypt_password(token) == plain


def test_empty():
    assert crypto.encrypt_password("") == ""
    assert crypto.decrypt_password("") == ""


def test_derive_from_secret_key(monkeypatch):
    monkeypatch.delenv("MONITOR_ENC_KEY", raising=False)
    monkeypatch.setenv("SECRET_KEY", "flask-secret-abc")
    token = crypto.encrypt_password("pw")
    assert crypto.decrypt_password(token) == "pw"


def test_plaintext_compatibility():
    # 未加前缀视为历史明文
    assert crypto.decrypt_password("rawpassword") == "rawpassword"
    assert not crypto.is_encrypted("rawpassword")
    assert crypto.is_encrypted("enc:abc")


def test_wrong_key_fails(monkeypatch):
    monkeypatch.setenv("MONITOR_ENC_KEY", "abcdefghijklmnopabcdefghijklmnop")
    token = crypto.encrypt_password("secret")
    monkeypatch.setenv("MONITOR_ENC_KEY", "zyxwvutsrqponmlkjihgfedcba")
    try:
        crypto.decrypt_password(token)
        assert False, "应抛 ValueError"
    except ValueError:
        pass
