from pathlib import Path

import pytest

from backend.bootstrap.settings import PROJECT_ROOT, ConfigurationError, Settings


def test_relative_data_directory_is_anchored_to_project(monkeypatch) -> None:
    monkeypatch.setenv("APP_DATA_DIR", "var/test-data")
    monkeypatch.delenv("APP_DATABASE_PATH", raising=False)

    settings = Settings.from_environment()

    assert settings.data_directory == (PROJECT_ROOT / "var/test-data").resolve()
    assert settings.database_path == settings.data_directory / "xiaobai.db"
    assert settings.timezone == "Asia/Shanghai"


@pytest.mark.parametrize(
    ("name", "value"),
    [("APP_PORT", "70000"), ("APP_PORT", "wrong"), ("APP_TIMEZONE", "UTC")],
)
def test_invalid_runtime_configuration_fails_fast(monkeypatch, name: str, value: str) -> None:
    monkeypatch.setenv(name, value)

    with pytest.raises(ConfigurationError):
        Settings.from_environment()


def test_test_settings_do_not_create_log_files(tmp_path: Path) -> None:
    settings = Settings.for_test(tmp_path)

    assert settings.log_file is None
    assert settings.database_path.parent == tmp_path


def test_production_requires_encryption_key(monkeypatch) -> None:
    monkeypatch.setenv("APP_ENV", "production")
    monkeypatch.delenv("APP_ENCRYPTION_KEY", raising=False)

    with pytest.raises(ConfigurationError, match="APP_ENCRYPTION_KEY"):
        Settings.from_environment()
