from pathlib import Path

from rights_filter.server.env_file import load_env_file


def test_load_env_file_reads_local_key_values_without_overriding_existing(tmp_path: Path):
    env_path = tmp_path / ".env"
    env_path.write_text(
        """
        # Copyrighter API keys
        NAVER_CLIENT_ID=from-file
        NAVER_CLIENT_SECRET="secret value"
        export OLLAMA_MODEL=qwen2.5:0.5b-instruct
        EMPTY_VALUE=
        """,
        encoding="utf-8",
    )
    environ = {"NAVER_CLIENT_ID": "already-set"}

    load_env_file(env_path, environ)

    assert environ["NAVER_CLIENT_ID"] == "already-set"
    assert environ["NAVER_CLIENT_SECRET"] == "secret value"
    assert environ["OLLAMA_MODEL"] == "qwen2.5:0.5b-instruct"
    assert environ["EMPTY_VALUE"] == ""


def test_load_env_file_ignores_missing_file(tmp_path: Path):
    environ = {}

    load_env_file(tmp_path / ".env", environ)

    assert environ == {}


def test_env_example_documents_all_search_provider_keys():
    example = Path(".env.example").read_text(encoding="utf-8")

    for key in [
        "NAVER_CLIENT_ID",
        "NAVER_CLIENT_SECRET",
        "NAVER_SEARCH_PAGES",
        "NAVER_BLOG_SEARCH_PAGES",
        "NAVER_WEB_SEARCH_PAGES",
        "GOOGLE_CLOUD_VISION_API_KEY",
        "GOOGLE_CUSTOM_SEARCH_API_KEY",
        "GOOGLE_CUSTOM_SEARCH_CX",
        "GOOGLE_CUSTOM_SEARCH_IMAGE_RESULTS",
        "GOOGLE_CUSTOM_SEARCH_WEB_RESULTS",
        "GOOGLE_CUSTOM_SEARCH_IMAGE_PAGES",
        "GOOGLE_CUSTOM_SEARCH_WEB_PAGES",
        "COPYRIGHTER_AUTO_GOOGLE_CUSTOM_QUERY_LIMIT",
        "COPYRIGHTER_SEARCH_RESULT_COMPARE_LIMIT",
        "COPYRIGHTER_SEARCH_RESULT_PAGE_IMAGE_LIMIT",
        "COPYRIGHTER_SEARCH_RESULT_SIMILARITY_THRESHOLD",
    ]:
        assert f"{key}=" in example
