"""Tests for API key fallback logic in loom.config.load_config."""

from __future__ import annotations

import logging

import pytest

from loom.config import load_config


# Keys used across the env vars we care about.
_SKILLS_KEY = "LOOM_SKILLS_API_KEY"
_ANTHRO_KEY = "ANTHROPIC_API_KEY"

# Also clear any YAML-based config that might leak from the host environment.
_ENV_VARS_TO_CLEAR = (
    _SKILLS_KEY,
    _ANTHRO_KEY,
    "LOOM_DATABASE_URL",
    "LOOM_REDIS_URL",
    "LOOM_PROJECT_ID",
    "LOOM_LOG_LEVEL",
    "LOOM_MCP_PORT",
    "LOOM_HEALTH_PORT",
    "LOOM_SKILLS_MODEL",
    "LOOM_CLAIM_TTL",
    "LOOM_MAX_RETRIES",
    "LOOM_RETRY_BASE_DELAY",
    "LOOM_RETRY_MAX_DELAY",
    "LOOM_SLACK_WEBHOOK_URL",
    "LOOM_OBSIDIAN_VAULT_PATH",
    "LOOM_AUTH_ENABLED",
    "LOOM_DATABASE_POOL_MIN",
    "LOOM_DATABASE_POOL_MAX",
)


@pytest.fixture(autouse=True)
def _clean_env(monkeypatch, tmp_path):
    """Remove all Loom-related env vars and point config away from host YAML."""
    for var in _ENV_VARS_TO_CLEAR:
        monkeypatch.delenv(var, raising=False)
    # Use tmp_path as HOME so that ~/.loom/config.yaml does not exist.
    monkeypatch.setenv("HOME", str(tmp_path))


@pytest.mark.parametrize(
    "env_vars, expected_key, expect_fallback_log",
    [
        pytest.param(
            {_SKILLS_KEY: "sk-primary-1234"},
            "sk-primary-1234",
            False,
            id="only_LOOM_SKILLS_API_KEY",
        ),
        pytest.param(
            {_ANTHRO_KEY: "sk-anthro-5678"},
            "sk-anthro-5678",
            True,
            id="only_ANTHROPIC_API_KEY_with_fallback_log",
        ),
        pytest.param(
            {_SKILLS_KEY: "sk-primary-wins", _ANTHRO_KEY: "sk-anthro-loses"},
            "sk-primary-wins",
            False,
            id="both_set_LOOM_SKILLS_wins",
        ),
        pytest.param(
            {},
            "",
            False,
            id="neither_set_empty_default",
        ),
    ],
)
def test_api_key_fallback(
    monkeypatch, caplog, env_vars, expected_key, expect_fallback_log
):
    """Verify that the API key resolution picks the right env var."""
    for key, value in env_vars.items():
        monkeypatch.setenv(key, value)

    with caplog.at_level(logging.DEBUG, logger="loom.config"):
        config = load_config(project_dir=None)

    assert config.skills.api_key == expected_key

    fallback_msg = "LOOM_SKILLS_API_KEY not set, falling back to ANTHROPIC_API_KEY"
    if expect_fallback_log:
        assert fallback_msg in caplog.text
    else:
        assert fallback_msg not in caplog.text
