import pytest
from cryptography.fernet import Fernet

from backend.bootstrap.settings import ConfigurationError, Settings
from backend.security import SecretCipher, load_or_create_cipher


def test_development_cipher_persists_in_ignored_data_directory(tmp_path) -> None:
    settings = Settings.for_test(tmp_path)
    first = load_or_create_cipher(settings)
    encrypted = first.encrypt("private profile")

    second = load_or_create_cipher(settings)

    assert second.decrypt(encrypted) == "private profile"
    assert (tmp_path / ".encryption.key").exists()
    assert "private profile" not in encrypted


def test_explicit_encryption_key_is_reusable(tmp_path) -> None:
    key = Fernet.generate_key().decode("ascii")
    settings = Settings.for_test(tmp_path)
    configured = Settings(
        environment=settings.environment,
        debug=settings.debug,
        data_directory=settings.data_directory,
        database_path=settings.database_path,
        mentor_skills_directory=settings.mentor_skills_directory,
        private_mentor_skills_directory=settings.private_mentor_skills_directory,
        log_file=settings.log_file,
        log_level=settings.log_level,
        host=settings.host,
        port=settings.port,
        encryption_key=key,
    )

    first = load_or_create_cipher(configured).encrypt("secret")
    second = SecretCipher.from_key(key).decrypt(first)

    assert second == "secret"


def test_invalid_encryption_key_is_rejected() -> None:
    with pytest.raises(ConfigurationError):
        SecretCipher.from_key("invalid")
