"""Tests for client factory functions."""
import os
import pytest
from cache_core.clients.factory import (
    _resolve_redis_url,
    create_redis_cache_client,
    create_memory_cache_client,
)
from cache_core.clients.redis import RedisCacheClient
from cache_core.clients.memory import MemoryCacheClient


class TestResolveRedisURL:
    def test_explicit_url_keys(self, monkeypatch):
        # Clear all env vars
        for key in ["REDIS_URL", "REDIS_DSN", "CACHE_URL", "REDIS_HOST"]:
            monkeypatch.delenv(key, raising=False)
        monkeypatch.setenv("REDIS_URL", "redis://explicit:6379/1")
        assert _resolve_redis_url() == "redis://explicit:6379/1"

    def test_cache_url_fallback(self, monkeypatch):
        for key in ["REDIS_URL", "REDIS_DSN", "CACHE_URL", "REDIS_HOST"]:
            monkeypatch.delenv(key, raising=False)
        monkeypatch.setenv("CACHE_URL", "redis://cache:6380/2")
        assert _resolve_redis_url() == "redis://cache:6380/2"

    def test_component_parts(self, monkeypatch):
        for key in ["REDIS_URL", "REDIS_DSN", "CACHE_URL"]:
            monkeypatch.delenv(key, raising=False)
        monkeypatch.setenv("REDIS_HOST", "myhost")
        monkeypatch.setenv("REDIS_PORT", "6380")
        monkeypatch.setenv("REDIS_DB", "3")
        monkeypatch.setenv("REDIS_PASSWORD", "secret")
        url = _resolve_redis_url()
        assert url == "redis://:secret@myhost:6380/3"

    def test_defaults(self, monkeypatch):
        for key in ["REDIS_URL", "REDIS_DSN", "CACHE_URL", "REDIS_HOST",
                     "REDIS_PORT", "REDIS_DB", "REDIS_PASSWORD"]:
            monkeypatch.delenv(key, raising=False)
        url = _resolve_redis_url()
        assert url == "redis://localhost:6379/0"


class TestCreateMemoryCacheClient:
    def test_creates_memory_client(self):
        client = create_memory_cache_client()
        assert isinstance(client, MemoryCacheClient)

    def test_accepts_serializer(self):
        from cache_core.serializer import SmartSerializer
        s = SmartSerializer()
        client = create_memory_cache_client(serializer=s)
        assert client._serializer is s


class TestCreateRedisCacheClient:
    def test_explicit_url(self):
        client = create_redis_cache_client(url="redis://localhost:6379/0")
        assert isinstance(client, RedisCacheClient)
        assert client._url == "redis://localhost:6379/0"

    def test_defaults_when_no_env(self, monkeypatch):
        """When no env vars are set, factory returns a client with defaults."""
        for key in ["REDIS_URL", "REDIS_DSN", "CACHE_URL", "REDIS_HOST",
                     "REDIS_PORT", "REDIS_DB", "REDIS_PASSWORD"]:
            monkeypatch.delenv(key, raising=False)
        client = create_redis_cache_client()
        assert isinstance(client, RedisCacheClient)
