"""ConfigServer client + syslog logging substrate."""
import os

from andrea_svc_web import config, logging_conf


# ── ConfigServer client (fail-soft by contract) ─────────────────────────────────────────────────
def test_fetch_config_fail_soft(monkeypatch):
    def boom(*a, **k):
        raise OSError("config-service down")
    monkeypatch.setattr(config.urllib.request, "urlopen", boom)
    assert config.fetch_config("svc") == {}                # any error → {}, never raises


def test_config_value_falls_back_to_env_then_default(monkeypatch):
    monkeypatch.setattr(config, "fetch_config", lambda svc, box=None: {})
    monkeypatch.setenv("CFG_FOO", "envval")
    assert config.config_value("svc", "CFG_FOO") == "envval"       # config empty → env
    assert config.config_value("svc", "CFG_MISSING", "d") == "d"   # → default


def test_apply_to_env_overlays(monkeypatch):
    monkeypatch.setattr(config, "fetch_config", lambda svc, box=None: {"CFG_A": "s3cr3t", "CFG_B": "9"})
    for k in ("CFG_A", "CFG_B"):
        os.environ.pop(k, None)
    try:
        assert config.apply_to_env("svc") == 2
        assert os.environ["CFG_A"] == "s3cr3t" and os.environ["CFG_B"] == "9"
    finally:
        for k in ("CFG_A", "CFG_B"):
            os.environ.pop(k, None)


# ── syslog logging ──────────────────────────────────────────────────────────────────────────────
def test_build_logging_console_always_present(monkeypatch):
    monkeypatch.setenv("ANDREA_SYSLOG", "0")
    cfg = logging_conf.build_logging("test-svc")
    assert "console" in cfg["handlers"] and "syslog" not in cfg["handlers"]
    assert cfg["root"]["handlers"] == ["console"]


def test_build_logging_adds_syslog_when_target_exists(monkeypatch, tmp_path):
    sock = tmp_path / "log"
    sock.write_text("")                                    # a path that EXISTS (stands in for /dev/log)
    monkeypatch.setenv("ANDREA_SYSLOG", "1")
    monkeypatch.setenv("SYSLOG_ADDRESS", str(sock))
    cfg = logging_conf.build_logging("test-svc")
    assert "syslog" in cfg["handlers"]
    assert cfg["handlers"]["syslog"]["address"] == str(sock)
    assert cfg["formatters"]["syslog"]["format"].startswith("test-svc[")


def test_syslog_target_resolution():
    assert logging_conf._syslog_target("10.0.0.1:514") == ("10.0.0.1", 514)
    assert logging_conf._syslog_target("/nonexistent/dev/log") is None
    assert logging_conf._syslog_target("") is None
