from __future__ import annotations

import os

from app.core.config import Settings, get_settings


def test_get_settings_refreshes_when_env_file_changes(tmp_path, monkeypatch) -> None:
    env_file = tmp_path / ".env"
    env_file.write_text("ONLYOFFICE_ENABLED=false\n", encoding="utf-8")

    original_env_file = Settings.model_config.get("env_file")
    monkeypatch.setitem(Settings.model_config, "env_file", (env_file,))
    get_settings.cache_clear()

    try:
        first = get_settings()
        assert first.onlyoffice_enabled is False

        env_file.write_text("ONLYOFFICE_ENABLED=true\n", encoding="utf-8")
        os.utime(env_file, None)

        second = get_settings()
        assert second.onlyoffice_enabled is True
    finally:
        monkeypatch.setitem(Settings.model_config, "env_file", original_env_file)
        get_settings.cache_clear()


def test_onlyoffice_values_prefer_env_file_over_inherited_environment(tmp_path, monkeypatch) -> None:
    env_file = tmp_path / ".env"
    env_file.write_text(
        "\n".join(
            [
                "ONLYOFFICE_ENABLED=true",
                "ONLYOFFICE_PUBLIC_URL=http://10.10.10.122:8082",
                "ONLYOFFICE_BACKEND_URL=http://main:8000",
                "ONLYOFFICE_JWT_SECRET=change-me-onlyoffice",
            ]
        )
        + "\n",
        encoding="utf-8",
    )

    original_env_file = Settings.model_config.get("env_file")
    monkeypatch.setitem(Settings.model_config, "env_file", (env_file,))
    monkeypatch.setenv("ONLYOFFICE_ENABLED", "false")
    monkeypatch.setenv("ONLYOFFICE_PUBLIC_URL", "http://127.0.0.1:8082")
    get_settings.cache_clear()

    try:
        settings = get_settings()

        assert settings.onlyoffice_enabled is True
        assert settings.onlyoffice_public_url == "http://10.10.10.122:8082"
        assert settings.onlyoffice_backend_url == "http://main:8000"
        assert settings.onlyoffice_jwt_secret == "change-me-onlyoffice"
    finally:
        monkeypatch.setitem(Settings.model_config, "env_file", original_env_file)
        get_settings.cache_clear()
