import pytest

from veritell_langchain.config import resolve_config


def test_c7_reads_veritell_api_key_from_env(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.delenv("VERITELL_ENV", raising=False)
    monkeypatch.delenv("VERITELL_API_KEY_STAGING", raising=False)
    monkeypatch.delenv("VERITELL_API_KEY_PRODUCTION", raising=False)
    monkeypatch.delenv("VERITELL_API_KEY_PROD", raising=False)
    monkeypatch.delenv("VERITELL_API_KEY", raising=False)

    monkeypatch.setenv("VERITELL_API_KEY", "k_common")

    cfg = resolve_config(config_path=None)
    assert cfg.api_key == "k_common"


def test_c17_env_specific_key_beats_fallback_key_staging(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.delenv("VERITELL_API_KEY", raising=False)
    monkeypatch.delenv("VERITELL_API_KEY_STAGING", raising=False)
    monkeypatch.delenv("VERITELL_API_KEY_PRODUCTION", raising=False)
    monkeypatch.delenv("VERITELL_API_KEY_PROD", raising=False)

    monkeypatch.setenv("VERITELL_ENV", "staging")
    monkeypatch.setenv("VERITELL_API_KEY", "k_common")
    monkeypatch.setenv("VERITELL_API_KEY_STAGING", "k_staging")

    cfg = resolve_config(config_path=None)
    assert cfg.env == "staging"
    assert cfg.api_key == "k_staging"


def test_c17_env_specific_key_beats_fallback_key_production(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.delenv("VERITELL_API_KEY", raising=False)
    monkeypatch.delenv("VERITELL_API_KEY_STAGING", raising=False)
    monkeypatch.delenv("VERITELL_API_KEY_PRODUCTION", raising=False)
    monkeypatch.delenv("VERITELL_API_KEY_PROD", raising=False)

    monkeypatch.setenv("VERITELL_ENV", "production")
    monkeypatch.setenv("VERITELL_API_KEY", "k_common")
    monkeypatch.setenv("VERITELL_API_KEY_PRODUCTION", "k_prod")

    cfg = resolve_config(config_path=None)
    assert cfg.env == "production"
    assert cfg.api_key == "k_prod"


def test_constructor_api_key_override_wins(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("VERITELL_ENV", "staging")
    monkeypatch.setenv("VERITELL_API_KEY_STAGING", "k_staging")

    cfg = resolve_config(config_path=None, api_key="k_override")
    assert cfg.api_key == "k_override"


def test_no_key_present_results_in_none(monkeypatch: pytest.MonkeyPatch) -> None:
    for k in [
        "VERITELL_API_KEY",
        "VERITELL_API_KEY_STAGING",
        "VERITELL_API_KEY_PRODUCTION",
        "VERITELL_API_KEY_PROD",
    ]:
        monkeypatch.delenv(k, raising=False)

    cfg = resolve_config(config_path=None, env="staging")
    assert cfg.api_key is None
