"""
Integration tests - requires running backend.

Skip these in CI if backend is not available.

Run with:
    export SILICO_API_KEY="sk_xxx"
    pytest tests/test_integration.py -v
"""
import os
import pytest
from silico import SilicoBot, AuthenticationError


# Skip all tests if API key not provided
pytestmark = pytest.mark.skipif(
    not os.getenv("SILICO_API_KEY"),
    reason="SILICO_API_KEY not set - skipping integration tests"
)


@pytest.fixture
def bot():
    """Create bot with real API key."""
    api_key = os.getenv("SILICO_API_KEY")
    base_url = os.getenv("SILICO_BASE_URL")
    return SilicoBot(api_key=api_key, base_url=base_url)


def test_get_price_integration(bot):
    """Integration test: Fetch real price."""
    price = bot.get_price("SOL/USDC")

    # Price should be reasonable for SOL
    assert isinstance(price, float)
    assert 10 < price < 1000  # Sanity check


def test_buy_trade_integration(bot):
    """Integration test: Execute small buy trade."""
    result = bot.buy("SOL/USDC", amount_usdc=1)  # $1 trade

    # Should succeed or fail gracefully
    assert result.success is True or result.error_message is not None

    if result.success:
        assert result.trade_id is not None
        assert result.executed_price > 0


def test_invalid_api_key_integration():
    """Integration test: Invalid API key should fail."""
    bot = SilicoBot(api_key="sk_invalid_key")

    with pytest.raises(AuthenticationError):
        bot.get_price("SOL/USDC")


def test_market_data_caching(bot):
    """Integration test: Market data should cache."""
    # First call fetches from API
    price1 = bot.get_price("SOL/USDC")

    # Should be cached in market data
    cached_price = bot.market.get_price("SOL/USDC")

    assert cached_price == price1
