"""Tests for XccyClient initialization behavior."""

from unittest.mock import Mock, patch

import pytest

from xccy.client import XccyClient
from xccy.exceptions import NetworkError


def _mock_web3(chain_id: int, connected: bool = True) -> Mock:
    web3_instance = Mock()
    web3_instance.is_connected.return_value = connected
    web3_instance.eth.chain_id = chain_id
    web3_instance.middleware_onion = Mock()
    return web3_instance


def test_auto_detects_polygon_when_network_omitted() -> None:
    with patch("xccy.client.Web3") as web3_cls:
        web3_cls.HTTPProvider.return_value = object()
        web3_cls.return_value = _mock_web3(137)

        client = XccyClient(rpc_url="https://example-rpc", backend_url=None)

    assert client.config.chain_id == 137
    assert client.config.slug == "polygon"


def test_auto_detects_arbitrum_when_network_omitted() -> None:
    with patch("xccy.client.Web3") as web3_cls:
        web3_cls.HTTPProvider.return_value = object()
        web3_cls.return_value = _mock_web3(42161)

        client = XccyClient(rpc_url="https://example-rpc", backend_url=None)

    assert client.config.chain_id == 42161
    assert client.config.slug == "arbitrum"


def test_raises_on_unsupported_chain_when_network_omitted() -> None:
    with patch("xccy.client.Web3") as web3_cls:
        web3_cls.HTTPProvider.return_value = object()
        web3_cls.return_value = _mock_web3(1)

        with pytest.raises(NetworkError, match="Unsupported chain ID"):
            XccyClient(rpc_url="https://example-rpc", backend_url=None)


def test_keeps_explicit_network_mismatch_guard() -> None:
    with patch("xccy.client.Web3") as web3_cls:
        web3_cls.HTTPProvider.return_value = object()
        web3_cls.return_value = _mock_web3(42161)

        with pytest.raises(NetworkError, match="Chain ID mismatch"):
            XccyClient(
                rpc_url="https://example-rpc",
                network="polygon",
                backend_url=None,
            )
