#!/usr/bin/env python3
"""
Advanced Example - All SDK features.

Demonstrates:
- Error handling
- Rate limit retry
- Custom base URL
- Market data caching
- Trade history

Usage:
    export SILICO_API_KEY="sk_xxx"
    python advanced.py
"""
import os
import time
from silico import (
    SilicoBot,
    AuthenticationError,
    RateLimitError,
    InsufficientBalanceError,
    NetworkError,
)


def main():
    # Get API key
    api_key = os.getenv("SILICO_API_KEY")
    if not api_key:
        print("❌ Error: SILICO_API_KEY not set")
        return

    # Initialize with explicit base URL (optional)
    base_url = os.getenv("SILICO_BASE_URL")  # Or None for auto-detect

    try:
        bot = SilicoBot(
            api_key=api_key,
            base_url=base_url,
            timeout=30
        )
        print(f"✓ Connected to {bot.base_url}\n")

    except AuthenticationError as e:
        print(f"❌ Authentication failed: {e}")
        print("   Check your API key at https://silico.fun/dashboard")
        return

    except NetworkError as e:
        print(f"❌ Connection failed: {e}")
        return

    # Example: Fetch prices for multiple symbols
    print("📊 Fetching market data...")
    symbols = ["SOL/USDC", "BONK/USDC"]

    for symbol in symbols:
        try:
            price = bot.get_price(symbol)
            print(f"   {symbol}: ${price:.4f}")
        except Exception as e:
            print(f"   {symbol}: Error - {e}")

    print()

    # Example: Execute trade with error handling
    print("💸 Executing trade...")

    try:
        result = bot.buy(
            symbol="SOL/USDC",
            amount_usdc=10,
            strategy_tag="EXAMPLE",
            max_slippage_bps=100
        )

        if result.success:
            print(f"   ✓ Trade successful!")
            print(f"   Trade ID: {result.trade_id}")
            print(f"   Price: ${result.executed_price:.2f}")
        else:
            print(f"   ❌ Trade failed: {result.error_message}")

    except RateLimitError as e:
        print(f"   ⏳ Rate limit exceeded")
        print(f"      Retry after {e.retry_after} seconds")

        # Optionally wait and retry
        if e.retry_after:
            print(f"      Waiting {e.retry_after}s...")
            time.sleep(e.retry_after)
            # Retry trade here

    except InsufficientBalanceError as e:
        print(f"   💰 Insufficient balance")
        print(f"      Have: ${e.current_balance:.2f}")
        print(f"      Need: ${e.required_balance:.2f}")

    except AuthenticationError:
        print(f"   🔑 Invalid API key")

    except NetworkError as e:
        print(f"   🌐 Network error: {e}")

    except Exception as e:
        print(f"   ⚠️  Unexpected error: {e}")

    print("\n✅ Example complete!")


if __name__ == "__main__":
    main()
