import json
from aegro.config import Settings


def test_settings_loads_farms_from_env(monkeypatch):
    farms = {"Fazenda Joao": "key-123", "Fazenda Maria": "key-456"}
    monkeypatch.setenv("AEGRO_FARMS", json.dumps(farms))
    settings = Settings()
    assert settings.farms == farms


def test_settings_default_values(monkeypatch):
    farms = {"Test Farm": "key-abc"}
    monkeypatch.setenv("AEGRO_FARMS", json.dumps(farms))
    settings = Settings()
    assert settings.aegro_api_base_url == "https://app.aegro.com.br"
    assert settings.api_timeout == 30.0
    assert settings.api_max_retries == 3
    assert settings.log_level == "INFO"


def test_settings_masks_api_keys():
    farms = {"Fazenda Joao": "abcdefghijklmnop"}
    settings = Settings(farms=farms)
    masked = settings.masked_farms()
    assert masked["Fazenda Joao"] == "***...nop"


def test_settings_farm_names():
    farms = {"Fazenda A": "key1", "Fazenda B": "key2"}
    settings = Settings(farms=farms)
    assert settings.farm_names() == ["Fazenda A", "Fazenda B"]


def test_settings_get_api_key():
    farms = {"Fazenda A": "key1", "Fazenda B": "key2"}
    settings = Settings(farms=farms)
    assert settings.get_api_key("Fazenda A") == "key1"
    assert settings.get_api_key("Unknown") is None


def test_settings_no_farms_defaults_empty(monkeypatch):
    monkeypatch.delenv("AEGRO_FARMS", raising=False)
    monkeypatch.delenv("AEGRO_FARMS_FILE", raising=False)
    s = Settings()
    assert s.farms == {}
    assert s.farm_names() == []
    assert s.get_api_key("anything") is None


def test_settings_env_prefix(monkeypatch):
    monkeypatch.setenv("AEGRO_API_TIMEOUT", "60.0")
    settings = Settings(farms={"test": "key"})
    assert settings.api_timeout == 60.0
