"""测试：配置加载与命令分析，不依赖真实 Redis。"""
import pytest


def test_parse_command():
    from redis_client_mcp.command_analysis import parse_command, analyze_command
    assert parse_command("GET foo") == ("GET", ["foo"])
    assert parse_command("  SET   k   v  ") == ("SET", ["k", "v"])
    assert parse_command("INFO server") == ("INFO", ["server"])
    assert parse_command("") == ("", [])


def test_analyze_command_read():
    from redis_client_mcp.command_analysis import analyze_command
    a = analyze_command("GET mykey", read_only=False)
    assert a.command == "GET"
    assert a.is_read is True
    assert a.is_write is False
    assert a.need_confirm is False
    a2 = analyze_command("INFO memory", read_only=False)
    assert a2.is_read is True


def test_analyze_command_write():
    from redis_client_mcp.command_analysis import analyze_command
    a = analyze_command("SET k v", read_only=False)
    assert a.command == "SET"
    assert a.is_write is True
    assert a.need_confirm is True
    a_ro = analyze_command("SET k v", read_only=True)
    assert "只读" in a_ro.message


def test_analyze_command_dangerous():
    from redis_client_mcp.command_analysis import analyze_command
    a = analyze_command("FLUSHALL", read_only=False)
    assert a.is_dangerous is True
    assert "禁止" in a.message or "危险" in a.message


def test_config_single(monkeypatch):
    monkeypatch.setenv("REDIS_HOST", "localhost")
    monkeypatch.setenv("REDIS_PORT", "6379")
    from redis_client_mcp.config import load_connection_map
    default, cmap, name = load_connection_map()
    assert default.host == "localhost"
    assert default.port == 6379
    assert default.mode == "standalone"
    assert "default" in cmap
    assert name == "default"


def test_config_profiles(monkeypatch):
    monkeypatch.setenv(
        "TEST_REDIS_PROFILES",
        '[{"mode":"standalone","host":"r1","port":6379,"password":"p"},{"mode":"cluster","hosts":["c1:6379","c2:6379"],"name":"cache"}]',
    )
    monkeypatch.setenv("PROD_REDIS_PROFILES", '[{"host":"prod","port":6379}]')
    from redis_client_mcp.config import load_connection_map
    default, cmap, name = load_connection_map()
    assert "test_0" in cmap
    assert cmap["test_0"].mode == "standalone"
    assert "test_cache" in cmap
    assert cmap["test_cache"].mode == "cluster"
    assert name == "prod_0"
    assert default.host == "prod"
