# Familiar - Self-Hosted AI Companion Platform
# Copyright (c) 2026 George Scott Foley
# ORCID: 0009-0006-4957-0540
# Licensed under the MIT License - see LICENSE file for details

"""Tests: DistributedSkillBus wiring — config defaults and factory functions.

Note: create_distributed_bus() connects to Redis on construction, so tests
that instantiate a bus are skipped when Redis is not available.
"""

import os

import pytest

from familiar.core.config import AgentConfig
from familiar.core.distributed import RedisConfig, create_distributed_bus


def _redis_available() -> bool:
    """Check whether we can create a bus (Redis is reachable)."""
    try:
        create_distributed_bus(redis_url="redis://localhost:6379")
        return True
    except Exception:
        return False


_skip_no_redis = pytest.mark.skipif(
    not _redis_available(), reason="Redis not available"
)


class TestDistributedBusConfig:
    """Config field defaults for distributed bus."""

    def test_distributed_bus_disabled_by_default(self):
        assert AgentConfig().distributed_bus_enabled is False


class TestRedisConfigFromEnv:
    """RedisConfig.from_env() reads REDIS_URL."""

    def test_default_url(self):
        cfg = RedisConfig.from_env()
        assert cfg.url == os.getenv("REDIS_URL", "redis://localhost:6379")

    def test_custom_url(self, monkeypatch):
        monkeypatch.setenv("REDIS_URL", "redis://custom:1234")
        cfg = RedisConfig.from_env()
        assert cfg.url == "redis://custom:1234"


class TestCreateDistributedBusParams:
    """create_distributed_bus accepts the expected parameters (signature check)."""

    def test_accepts_redis_url_kwarg(self):
        """Verify the factory function accepts redis_url without TypeError."""
        import inspect

        sig = inspect.signature(create_distributed_bus)
        assert "redis_url" in sig.parameters

    def test_accepts_node_id_kwarg(self):
        """Verify the factory function accepts node_id without TypeError."""
        import inspect

        sig = inspect.signature(create_distributed_bus)
        assert "node_id" in sig.parameters


class TestSingleton:
    """get/set_distributed_bus singleton works."""

    def test_get_set_roundtrip(self):
        from familiar.core.distributed import get_distributed_bus, set_distributed_bus

        sentinel = object()
        set_distributed_bus(sentinel)
        assert get_distributed_bus() is sentinel
        # Clean up global state
        set_distributed_bus(None)
