#!/usr/bin/env python3
"""
Eden Trading Simulation - Real-Time Market Data
Tests strategy profitability before live execution
"""
import sys
import json
import time
from datetime import datetime
import random

sys.path.append('/Eden/CORE')
from eden_sage_financial_engine_v1 import SageFinancialEngine

try:
    from coinbase.rest import RESTClient
except ImportError:
    print("❌ ERROR: coinbase-advanced-py not found")
    sys.exit(1)

# Load real credentials for market data
SECRETS_FILE = "/Eden/SECRETS/coinbase_api_key.json"
SIMULATION_LOG = "/Eden/DATA/trading_simulation_results.txt"

class TradingSimulator:
    def __init__(self, initial_capital: float = 1000.0):
        self.sage = SageFinancialEngine()
        self.capital = initial_capital
        self.starting_capital = initial_capital
        self.total_trades = 0
        self.winning_trades = 0
        self.losing_trades = 0
        self.total_profit = 0.0
        self.trade_history = []
        
        # Load credentials for real market data
        with open(SECRETS_FILE, 'r') as f:
            creds = json.load(f)
            self.api_key = creds.get('api_key') or creds.get('name')
            self.api_secret = creds.get('api_secret') or creds.get('privateKey')
        
        self.client = RESTClient(api_key=self.api_key, api_secret=self.api_secret)
        
        print("\n" + "="*60)
        print("🧪 EDEN TRADING SIMULATION - REAL MARKET DATA")
        print("="*60)
        print(f"Starting Capital: ${self.capital:,.2f}")
        print(f"Strategy: Sage-Validated Opportunities")
        print("="*60 + "\n")
    
    def get_real_market_data(self, symbol: str):
        """Fetch real-time market data from Coinbase"""
        try:
            # Get current product data
            product = self.client.get_product(symbol)
            
            # Extract price from the product object
            if hasattr(product, 'price'):
                price = float(product.price)
            elif isinstance(product, dict):
                price = float(product.get('price', 0))
            else:
                print(f"⚠️  Unexpected product format for {symbol}")
                return None
            
            # Get candles for volatility estimation (last 24 hours)
            try:
                candles = self.client.get_candles(
                    product_id=symbol,
                    start=int(time.time() - 86400),
                    end=int(time.time()),
                    granularity="ONE_HOUR"
                )
                
                if candles and len(candles.candles) > 0:
                    highs = [float(c.high) for c in candles.candles]
                    lows = [float(c.low) for c in candles.candles]
                    volumes = [float(c.volume) for c in candles.candles]
                    
                    high_24h = max(highs)
                    low_24h = min(lows)
                    volume_24h = sum(volumes)
                    spread_pct = ((high_24h - low_24h) / price) * 100
                else:
                    high_24h = price * 1.05
                    low_24h = price * 0.95
                    volume_24h = 1000000
                    spread_pct = 5.0
            except:
                high_24h = price * 1.05
                low_24h = price * 0.95
                volume_24h = 1000000
                spread_pct = 5.0
            
            return {
                'symbol': symbol,
                'price': price,
                'high_24h': high_24h,
                'low_24h': low_24h,
                'volume_24h': volume_24h,
                'spread_pct': spread_pct,
                'timestamp': datetime.now()
            }
        except Exception as e:
            print(f"❌ Error fetching data for {symbol}: {e}")
            return None
    
    def simulate_trade(self, market_data):
        """Simulate a single trade based on real market conditions"""
        symbol = market_data['symbol']
        entry_price = market_data['price']
        
        # Sage risk analysis
        is_safe, confidence, projected_return = self.sage.analyze_trade_opportunity(
            symbol, entry_price
        )
        
        if not is_safe:
            print(f"⛔ Sage REJECTED trade - Risk too high")
            return None
        
        position_size = self.capital * 0.01
        shares = position_size / entry_price
        
        slippage = random.uniform(0.0001, 0.0005)
        actual_entry = entry_price * (1 + slippage)
        
        volatility = market_data['spread_pct'] / 100
        expected_return = projected_return * confidence * 0.1
        price_change_pct = random.gauss(expected_return, volatility * 0.3)
        exit_price = actual_entry * (1 + price_change_pct)
        
        pnl = (exit_price - actual_entry) * shares
        pnl_pct = ((exit_price - actual_entry) / actual_entry) * 100
        
        fees = position_size * 0.01
        net_pnl = pnl - fees
        
        self.capital += net_pnl
        self.total_profit += net_pnl
        self.total_trades += 1
        
        if net_pnl > 0:
            self.winning_trades += 1
            result = "✅ WIN"
        else:
            self.losing_trades += 1
            result = "❌ LOSS"
        
        trade_record = {
            'timestamp': datetime.now(),
            'symbol': symbol,
            'confidence': confidence,
            'entry_price': actual_entry,
            'exit_price': exit_price,
            'position_size': position_size,
            'pnl': net_pnl,
            'pnl_pct': pnl_pct,
            'fees': fees,
            'result': result,
            'capital_after': self.capital
        }
        
        self.trade_history.append(trade_record)
        
        print(f"📊 Trade #{self.total_trades:2d} | {symbol:8s} | Sage: {confidence:5.1%} | Entry: ${actual_entry:8,.2f} | P&L: ${net_pnl:+7.2f} | {result} | Capital: ${self.capital:,.2f}")
        
        return trade_record
    
    def run_simulation(self, num_trades: int = 50, symbols: list = None):
        """Run multiple simulated trades"""
        if symbols is None:
            symbols = ["BTC-USD", "ETH-USD", "SOL-USD"]
        
        print(f"🚀 Starting simulation: {num_trades} trades\n")
        
        for i in range(num_trades):
            symbol = symbols[i % len(symbols)]
            market_data = self.get_real_market_data(symbol)
            
            if market_data:
                self.simulate_trade(market_data)
            
            time.sleep(0.3)
        
        self.print_summary()
        self.save_results()
    
    def print_summary(self):
        """Print simulation summary"""
        win_rate = (self.winning_trades / self.total_trades * 100) if self.total_trades > 0 else 0
        roi = ((self.capital - self.starting_capital) / self.starting_capital * 100)
        avg_win = sum(t['pnl'] for t in self.trade_history if t['pnl'] > 0) / max(self.winning_trades, 1)
        avg_loss = sum(t['pnl'] for t in self.trade_history if t['pnl'] < 0) / max(self.losing_trades, 1)
        
        print("\n" + "="*60)
        print("📈 SIMULATION RESULTS")
        print("="*60)
        print(f"Starting Capital:    ${self.starting_capital:,.2f}")
        print(f"Ending Capital:      ${self.capital:,.2f}")
        print(f"Total P&L:           ${self.total_profit:,.2f}")
        print(f"ROI:                 {roi:+.2f}%")
        print(f"\nTotal Trades:        {self.total_trades}")
        print(f"Winning Trades:      {self.winning_trades} ({win_rate:.1f}%)")
        print(f"Losing Trades:       {self.losing_trades}")
        print(f"Avg Win:             ${avg_win:,.2f}")
        print(f"Avg Loss:            ${avg_loss:,.2f}")
        print("="*60)
        
        if self.total_profit > 0 and win_rate >= 50:
            print("\n✅ STRATEGY APPEARS PROFITABLE")
            print("   Sage validation shows positive edge")
            print("   Consider activating live trading with small positions")
        elif self.total_profit > 0:
            print("\n⚠️  MARGINALLY PROFITABLE")
            print("   Win rate below 50% but net positive")
            print("   Consider refining entry/exit criteria")
        else:
            print("\n❌ STRATEGY NOT PROFITABLE")
            print("   DO NOT activate live trading with current parameters")
            print("   Sage validation needs improvement")
    
    def save_results(self):
        """Save detailed results to file"""
        with open(SIMULATION_LOG, 'w') as f:
            f.write("="*80 + "\n")
            f.write("EDEN TRADING SIMULATION RESULTS\n")
            f.write(f"Completed: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write("="*80 + "\n\n")
            
            win_rate = (self.winning_trades / self.total_trades * 100) if self.total_trades > 0 else 0
            roi = ((self.capital - self.starting_capital) / self.starting_capital * 100)
            
            f.write(f"Starting Capital: ${self.starting_capital:,.2f}\n")
            f.write(f"Ending Capital:   ${self.capital:,.2f}\n")
            f.write(f"Total P&L:        ${self.total_profit:,.2f}\n")
            f.write(f"ROI:              {roi:+.2f}%\n\n")
            f.write(f"Total Trades:     {self.total_trades}\n")
            f.write(f"Win Rate:         {win_rate:.1f}%\n\n")
            
            f.write("="*80 + "\n")
            f.write("TRADE LOG\n")
            f.write("="*80 + "\n")
            
            for trade in self.trade_history:
                f.write(f"\n{trade['timestamp'].strftime('%Y-%m-%d %H:%M:%S')}\n")
                f.write(f"  {trade['symbol']} | Confidence: {trade['confidence']:.2%}\n")
                f.write(f"  Entry: ${trade['entry_price']:,.2f} | Exit: ${trade['exit_price']:,.2f}\n")
                f.write(f"  P&L: ${trade['pnl']:,.2f} ({trade['pnl_pct']:+.2f}%) | {trade['result']}\n")
        
        print(f"\n💾 Detailed results saved to: {SIMULATION_LOG}")

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument('--trades', type=int, default=50, help='Number of trades to simulate')
    parser.add_argument('--capital', type=float, default=1000.0, help='Starting capital')
    args = parser.parse_args()
    
    simulator = TradingSimulator(initial_capital=args.capital)
    simulator.run_simulation(num_trades=args.trades)
