import pytest

from grayloghelper import EnvGELFUDPHandler


def test_reads_host_and_port_from_env(monkeypatch):
    monkeypatch.setenv("GRAYLOG_HOST", "graylog.example.com")
    monkeypatch.setenv("GRAYLOG_PORT", "12201")
    handler = EnvGELFUDPHandler()
    try:
        assert handler.host == "graylog.example.com"
        assert handler.port == 12201
    finally:
        handler.close()


def test_explicit_args_override_env(monkeypatch):
    monkeypatch.setenv("GRAYLOG_HOST", "from-env")
    monkeypatch.setenv("GRAYLOG_PORT", "1111")
    handler = EnvGELFUDPHandler(host="explicit", port=2222)
    try:
        assert handler.host == "explicit"
        assert handler.port == 2222
    finally:
        handler.close()


def test_port_is_cast_to_int(monkeypatch):
    monkeypatch.setenv("GRAYLOG_HOST", "h")
    monkeypatch.setenv("GRAYLOG_PORT", "12201")
    handler = EnvGELFUDPHandler()
    try:
        assert isinstance(handler.port, int)
    finally:
        handler.close()


def test_missing_host_raises(monkeypatch):
    monkeypatch.delenv("GRAYLOG_HOST", raising=False)
    monkeypatch.setenv("GRAYLOG_PORT", "12201")
    with pytest.raises(KeyError):
        EnvGELFUDPHandler()


def test_missing_port_raises(monkeypatch):
    monkeypatch.setenv("GRAYLOG_HOST", "h")
    monkeypatch.delenv("GRAYLOG_PORT", raising=False)
    with pytest.raises(KeyError):
        EnvGELFUDPHandler()


def test_invalid_port_raises(monkeypatch):
    monkeypatch.setenv("GRAYLOG_HOST", "h")
    monkeypatch.setenv("GRAYLOG_PORT", "not-a-number")
    with pytest.raises(ValueError):
        EnvGELFUDPHandler()
