# tests/test_config.py
"""Tests for the config module."""

import os
from unittest.mock import patch

import pytest

from crashsense.config import (
    DEFAULT_CONFIG,
    SUPPORTED_CHAINS,
    _deep_merge,
    get_api_key,
    get_chain_info,
)


class TestDeepMerge:
    def test_flat_merge(self):
        base = {"a": 1, "b": 2}
        override = {"b": 3, "c": 4}
        result = _deep_merge(base, override)
        assert result == {"a": 1, "b": 3, "c": 4}

    def test_nested_merge(self):
        base = {"a": {"x": 1, "y": 2}, "b": 3}
        override = {"a": {"y": 99, "z": 100}}
        result = _deep_merge(base, override)
        assert result["a"]["x"] == 1
        assert result["a"]["y"] == 99
        assert result["a"]["z"] == 100
        assert result["b"] == 3

    def test_base_unchanged(self):
        base = {"a": 1}
        override = {"a": 2}
        _deep_merge(base, override)
        assert base["a"] == 1


class TestSupportedChains:
    def test_all_chains_have_required_fields(self):
        required = {"chain_id", "rpc_url", "explorer_api", "currency"}
        for name, info in SUPPORTED_CHAINS.items():
            assert required.issubset(info.keys()), f"{name} missing: {required - info.keys()}"

    def test_ethereum_exists(self):
        assert "ethereum" in SUPPORTED_CHAINS

    def test_chain_ids_unique(self):
        ids = [info["chain_id"] for info in SUPPORTED_CHAINS.values()]
        assert len(ids) == len(set(ids))


class TestGetChainInfo:
    def test_default_chain(self):
        cfg = {"chain": {"name": "ethereum", "rpc_url": ""}}
        info = get_chain_info(cfg)
        assert info["chain_id"] == 1

    def test_custom_rpc(self):
        cfg = {"chain": {"name": "ethereum", "rpc_url": "http://custom:8545"}}
        info = get_chain_info(cfg)
        assert info["rpc_url"] == "http://custom:8545"

    def test_unknown_chain_falls_back(self):
        cfg = {"chain": {"name": "unknown_chain", "rpc_url": ""}}
        info = get_chain_info(cfg)
        assert info["chain_id"] == 1


class TestGetApiKey:
    def test_gemini_key(self):
        with patch.dict(os.environ, {"GEMINI_API_KEY": "test_key_123"}):
            assert get_api_key("gemini") == "test_key_123"

    def test_openai_key(self):
        with patch.dict(os.environ, {"OPENAI_API_KEY": "sk-test"}):
            assert get_api_key("openai") == "sk-test"

    def test_missing_key(self):
        with patch.dict(os.environ, {}, clear=True):
            assert get_api_key("gemini") == ""

    def test_unknown_provider(self):
        assert get_api_key("unknown_provider") == ""


class TestDefaultConfig:
    def test_provider_is_gemini(self):
        assert DEFAULT_CONFIG["provider"] == "gemini"

    def test_auto_apply_off(self):
        assert DEFAULT_CONFIG["behaviour"]["auto_apply_fixes"] is False

    def test_memory_config_exists(self):
        assert "path" in DEFAULT_CONFIG["memory"]
        assert "max_entries" in DEFAULT_CONFIG["memory"]
