"""Tests for client factory functions and environment variable resolution."""

import os
import pytest
from broker_core import (
    create_kafka_client,
    get_kafka_client,
    KafkaClient,
    KafkaConfig,
)
from broker_core.clients.factory import (
    _resolve_kafka_bootstrap_servers,
    create_nats_client,
    create_rabbitmq_client,
)


class TestResolveBootstrapServers:
    def test_returns_none_when_not_set(self, monkeypatch):
        """Returns None when no env vars are configured."""
        monkeypatch.delenv("KAFKA_BOOTSTRAP_SERVERS", raising=False)
        monkeypatch.delenv("KAFKA_URL", raising=False)
        monkeypatch.delenv("KAFKA_HOST", raising=False)
        monkeypatch.delenv("KAFKA_PORT", raising=False)
        assert _resolve_kafka_bootstrap_servers() is None

    def test_resolves_bootstrap_servers(self, monkeypatch):
        """KAFKA_BOOTSTRAP_SERVERS takes priority."""
        monkeypatch.setenv("KAFKA_BOOTSTRAP_SERVERS", "broker1:9092,broker2:9092")
        assert _resolve_kafka_bootstrap_servers() == "broker1:9092,broker2:9092"

    def test_resolves_kafka_url(self, monkeypatch):
        """KAFKA_URL is checked second."""
        monkeypatch.delenv("KAFKA_BOOTSTRAP_SERVERS", raising=False)
        monkeypatch.setenv("KAFKA_URL", "kafka.internal:9092")
        assert _resolve_kafka_bootstrap_servers() == "kafka.internal:9092"

    def test_resolves_host_port(self, monkeypatch):
        """KAFKA_HOST + KAFKA_PORT is checked third."""
        monkeypatch.delenv("KAFKA_BOOTSTRAP_SERVERS", raising=False)
        monkeypatch.delenv("KAFKA_URL", raising=False)
        monkeypatch.setenv("KAFKA_HOST", "localhost")
        monkeypatch.setenv("KAFKA_PORT", "9093")
        assert _resolve_kafka_bootstrap_servers() == "localhost:9093"

    def test_default_port(self, monkeypatch):
        """Default port is 9092 when only KAFKA_HOST is set."""
        monkeypatch.delenv("KAFKA_BOOTSTRAP_SERVERS", raising=False)
        monkeypatch.delenv("KAFKA_URL", raising=False)
        monkeypatch.setenv("KAFKA_HOST", "kafka")
        monkeypatch.delenv("KAFKA_PORT", raising=False)
        assert _resolve_kafka_bootstrap_servers() == "kafka:9092"


class TestCreateKafkaClient:
    def test_explicit_bootstrap_servers(self):
        """create_kafka_client with explicit bootstrap_servers returns a KafkaClient."""
        client = create_kafka_client(bootstrap_servers="localhost:9092")
        assert isinstance(client, KafkaClient)
        assert client.config.bootstrap_servers == "localhost:9092"

    def test_get_kafka_client_is_alias(self):
        """get_kafka_client is an alias for create_kafka_client."""
        client = get_kafka_client(bootstrap_servers="localhost:9092")
        assert isinstance(client, KafkaClient)

    def test_from_full_config(self):
        """Passing a KafkaConfig uses it directly."""
        config = KafkaConfig(
            bootstrap_servers="broker:9093",
            client_id="my-app",
            acks="all",
        )
        client = create_kafka_client(config=config)
        assert client.config is config
        assert client.config.client_id == "my-app"
        assert client.config.acks == "all"

    def test_kwargs_override_env(self, monkeypatch):
        """Keyword arguments override environment variables."""
        monkeypatch.setenv("KAFKA_BOOTSTRAP_SERVERS", "wrong:9092")
        monkeypatch.setenv("KAFKA_CLIENT_ID", "env-client")
        client = create_kafka_client(
            bootstrap_servers="right:9092",
            client_id="override-client",
        )
        assert client.config.bootstrap_servers == "right:9092"
        assert client.config.client_id == "override-client"

    def test_raises_when_no_bootstrap_servers(self, monkeypatch):
        """ValueError when bootstrap_servers cannot be resolved."""
        monkeypatch.delenv("KAFKA_BOOTSTRAP_SERVERS", raising=False)
        monkeypatch.delenv("KAFKA_URL", raising=False)
        monkeypatch.delenv("KAFKA_HOST", raising=False)
        monkeypatch.delenv("KAFKA_PORT", raising=False)
        with pytest.raises(ValueError, match="bootstrap_servers"):
            create_kafka_client()


class TestKafkaConfig:
    def test_defaults(self):
        config = KafkaConfig(bootstrap_servers="localhost:9092")
        assert config.acks == "all"
        assert config.auto_offset_reset == "latest"
        assert config.enable_auto_commit is True
        assert config.security_protocol == "PLAINTEXT"

    def test_custom_values(self):
        config = KafkaConfig(
            bootstrap_servers="kafka:9092",
            client_id="svc-1",
            group_id="g-1",
            acks=1,
            auto_offset_reset="earliest",
        )
        assert config.client_id == "svc-1"
        assert config.group_id == "g-1"
        assert config.acks == 1
        assert config.auto_offset_reset == "earliest"


class TestFutureBackendStubs:
    def test_nats_raises_not_implemented(self):
        with pytest.raises(NotImplementedError, match="NATS"):
            create_nats_client()

    def test_rabbitmq_raises_not_implemented(self):
        with pytest.raises(NotImplementedError, match="RabbitMQ"):
            create_rabbitmq_client()
