#!/usr/bin/env python3
"""
RSI Strategy Example - Buy oversold, sell overbought.

This implements a classic RSI mean-reversion strategy:
- Buy when RSI < 30 (oversold)
- Sell when RSI > 70 (overbought)

Usage:
    export SILICO_API_KEY="sk_xxx"
    python rsi_strategy.py
"""
import os
import time
from collections import deque
from silico import SilicoBot


def calculate_rsi(prices, period=14):
    """Calculate RSI from price history."""
    if len(prices) < period + 1:
        return 50  # Neutral if not enough data

    # Calculate price changes
    deltas = [prices[i] - prices[i-1] for i in range(1, len(prices))]

    # Separate gains and losses
    gains = [d if d > 0 else 0 for d in deltas]
    losses = [-d if d < 0 else 0 for d in deltas]

    # Calculate average gain and loss
    avg_gain = sum(gains[-period:]) / period
    avg_loss = sum(losses[-period:]) / period

    if avg_loss == 0:
        return 100

    # Calculate RSI
    rs = avg_gain / avg_loss
    rsi = 100 - (100 / (1 + rs))

    return rsi


def main():
    # Initialize bot
    api_key = os.getenv("SILICO_API_KEY")
    if not api_key:
        print("❌ Set SILICO_API_KEY environment variable")
        exit(1)

    bot = SilicoBot(api_key=api_key)
    print(f"✓ RSI Bot connected to {bot.base_url}")

    # Track price history
    price_history = deque(maxlen=50)  # Keep last 50 prices
    position = None  # Track if we're holding SOL

    # Strategy parameters
    SYMBOL = "SOL/USDC"
    RSI_PERIOD = 14
    OVERSOLD = 30
    OVERBOUGHT = 70
    TRADE_AMOUNT = 100  # USDC per trade

    print(f"\n📊 Strategy: RSI Mean Reversion")
    print(f"   Symbol: {SYMBOL}")
    print(f"   Buy when RSI < {OVERSOLD}")
    print(f"   Sell when RSI > {OVERBOUGHT}\n")

    while True:
        try:
            # Fetch current price
            price = bot.get_price(SYMBOL)
            price_history.append(price)

            # Calculate RSI
            rsi = calculate_rsi(list(price_history), RSI_PERIOD)

            print(f"💰 Price: ${price:.2f} | RSI: {rsi:.1f} | Position: {position or 'None'}")

            # Trading logic
            if rsi < OVERSOLD and position is None:
                print(f"📈 RSI {rsi:.1f} is OVERSOLD - Buying!")
                result = bot.buy(
                    SYMBOL,
                    amount_usdc=TRADE_AMOUNT,
                    strategy_tag="RSI_CONTRARIAN"
                )
                if result.success:
                    position = "LONG"
                    print(f"   ✓ Bought at ${result.executed_price:.2f}")

            elif rsi > OVERBOUGHT and position == "LONG":
                print(f"📉 RSI {rsi:.1f} is OVERBOUGHT - Selling!")
                result = bot.sell(
                    SYMBOL,
                    amount_usdc=TRADE_AMOUNT,
                    strategy_tag="RSI_CONTRARIAN"
                )
                if result.success:
                    position = None
                    print(f"   ✓ Sold at ${result.executed_price:.2f}")

            # Wait 10 seconds
            time.sleep(10)

        except KeyboardInterrupt:
            print("\n👋 Shutting down RSI bot...")
            break

        except Exception as e:
            print(f"⚠️  Error: {e}")
            time.sleep(5)


if __name__ == "__main__":
    main()
