#!/usr/bin/env python3
"""
Strategy Module Example - Whale Trading Strategy Analysis

This example demonstrates strategy analysis capabilities including:
- Whale behavior pattern analysis
- Strategy performance metrics
- Strategy comparison and optimization
- AI-powered strategy insights
"""

import asyncio
import numpy as np
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional

# Import strategy components
from hyperliquid_monitor_plus.strategy import (
    StrategyAnalyzer, StrategyMetrics, TradePattern,
    StrategyComparison, AIStrategyInsight
)

# Set up logging
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


class StrategyAnalysisDemo:
    """Demonstration of strategy analysis capabilities"""
    
    def __init__(self):
        self.analyzer = StrategyAnalyzer()
    
    async def whale_behavior_analysis_demo(self):
        """Demonstrate whale behavior pattern analysis"""
        print("🐋 Whale Behavior Pattern Analysis")
        print("=" * 50)
        
        # Sample whale addresses and their behaviors
        whale_behaviors = [
            {
                "address": "0x010461C14e146ac35Fe42271BDC1134EE31C703a",
                "behavior_type": "Conservative Accumulator",
                "trading_frequency": "Daily",
                "avg_trade_size": 750000,
                "success_rate": 0.78,
                "holding_period": "45 days",
                "preferred_coins": ["ETH", "BTC"],
                "risk_level": "Low"
            },
            {
                "address": "0x8eb8a3b98659cce290402893d0123abb75E3ab28",
                "behavior_type": "Momentum Trader",
                "trading_frequency": "Multiple times daily",
                "avg_trade_size": 450000,
                "success_rate": 0.65,
                "holding_period": "3 days",
                "preferred_coins": ["SOL", "AVAX", "LINK"],
                "risk_level": "High"
            },
            {
                "address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
                "behavior_type": "Market Maker",
                "trading_frequency": "Continuous",
                "avg_trade_size": 250000,
                "success_rate": 0.72,
                "holding_period": "1 day",
                "preferred_coins": ["BTC", "ETH", "USDC"],
                "risk_level": "Medium"
            }
        ]
        
        print("🧠 BEHAVIOR PATTERN ANALYSIS:")
        for whale in whale_behaviors:
            # Analyze behavior patterns
            pattern = TradePattern(
                address=whale["address"],
                pattern_type=whale["behavior_type"],
                frequency=whale["trading_frequency"],
                characteristics={
                    "avg_trade_size": whale["avg_trade_size"],
                    "success_rate": whale["success_rate"],
                    "holding_period": whale["holding_period"],
                    "preferred_coins": whale["preferred_coins"],
                    "risk_level": whale["risk_level"]
                }
            )
            
            print(f"\n   🐋 {whale['address'][:16]}... - {whale['behavior_type']}")
            print(f"      📊 Trading Frequency: {whale['trading_frequency']}")
            print(f"      💰 Average Trade Size: ${whale['avg_trade_size']:,.2f}")
            print(f"      🎯 Success Rate: {whale['success_rate']:.2f}")
            print(f"      ⏱️  Holding Period: {whale['holding_period']}")
            print(f"      🪙 Preferred Coins: {', '.join(whale['preferred_coins'])}")
            print(f"      ⚠️  Risk Level: {whale['risk_level']}")
            
            # Generate insights
            if whale["behavior_type"] == "Conservative Accumulator":
                insights = "High conviction entries, proven long-term strategy, suitable for following"
            elif whale["behavior_type"] == "Momentum Trader":
                insights = "Quick profits, high risk/reward, requires careful timing"
            else:
                insights = "Stable income generation, low risk, good for portfolio diversification"
            
            print(f"      💡 AI Insight: {insights}")
        
        print("✅ Whale behavior analysis completed!")
    
    async def strategy_performance_demo(self):
        """Demonstrate strategy performance metrics"""
        print("\n📊 Strategy Performance Metrics")
        print("=" * 50)
        
        # Sample strategy performance data
        strategies = [
            {
                "name": "Conservative Whale Follow",
                "trades": 45,
                "win_rate": 0.78,
                "avg_return": 0.12,
                "max_drawdown": -0.08,
                "sharpe_ratio": 1.85,
                "total_return": 0.68,
                "volatility": 0.15
            },
            {
                "name": "Aggressive Momentum",
                "trades": 120,
                "win_rate": 0.58,
                "avg_return": 0.25,
                "max_drawdown": -0.22,
                "sharpe_ratio": 1.12,
                "total_return": 1.35,
                "volatility": 0.35
            },
            {
                "name": "Market Maker Strategy",
                "trades": 300,
                "win_rate": 0.72,
                "avg_return": 0.08,
                "max_drawdown": -0.05,
                "sharpe_ratio": 2.10,
                "total_return": 0.95,
                "volatility": 0.08
            }
        ]
        
        print("📈 STRATEGY PERFORMANCE COMPARISON:")
        print(f"{'Strategy':<25} {'Trades':<7} {'Win%':<6} {'Return%':<8} {'Max DD%':<8} {'Sharpe':<7} {'Total%':<8}")
        print("-" * 80)
        
        for strategy in strategies:
            metrics = StrategyMetrics(
                strategy_name=strategy["name"],
                total_trades=strategy["trades"],
                win_rate=strategy["win_rate"],
                avg_return=strategy["avg_return"],
                max_drawdown=strategy["max_drawdown"],
                sharpe_ratio=strategy["sharpe_ratio"],
                total_return=strategy["total_return"],
                volatility=strategy["volatility"]
            )
            
            print(f"{strategy['name']:<25} {strategy['trades']:<7} "
                  f"{strategy['win_rate']*100:<5.1f} {strategy['avg_return']*100:<7.1f} "
                  f"{strategy['max_drawdown']*100:<7.1f} {strategy['sharpe_ratio']:<6.2f} "
                  f"{strategy['total_return']*100:<7.1f}")
        
        # Strategy rankings
        print(f"\n🏆 STRATEGY RANKINGS:")
        
        # Rank by different metrics
        by_return = sorted(strategies, key=lambda x: x["total_return"], reverse=True)
        by_sharpe = sorted(strategies, key=lambda x: x["sharpe_ratio"], reverse=True)
        by_consistency = sorted(strategies, key=lambda x: x["win_rate"], reverse=True)
        
        print(f"\n   📈 By Total Return:")
        for i, strategy in enumerate(by_return, 1):
            print(f"      {i}. {strategy['name']} ({strategy['total_return']*100:+.1f}%)")
        
        print(f"\n   📊 By Sharpe Ratio:")
        for i, strategy in enumerate(by_sharpe, 1):
            print(f"      {i}. {strategy['name']} ({strategy['sharpe_ratio']:.2f})")
        
        print(f"\n   🎯 By Consistency:")
        for i, strategy in enumerate(by_consistency, 1):
            print(f"      {i}. {strategy['name']} ({strategy['win_rate']*100:.1f}%)")
        
        print("✅ Strategy performance analysis completed!")
    
    async def strategy_comparison_demo(self):
        """Demonstrate strategy comparison analysis"""
        print("\n🔍 Strategy Comparison Analysis")
        print("=" * 50)
        
        # Compare two specific strategies
        strategy_a = {
            "name": "Conservative Whale Follow",
            "metrics": {
                "total_trades": 45,
                "win_rate": 0.78,
                "avg_return": 0.12,
                "max_drawdown": -0.08,
                "sharpe_ratio": 1.85
            }
        }
        
        strategy_b = {
            "name": "Aggressive Momentum",
            "metrics": {
                "total_trades": 120,
                "win_rate": 0.58,
                "avg_return": 0.25,
                "max_drawdown": -0.22,
                "sharpe_ratio": 1.12
            }
        }
        
        comparison = StrategyComparison(
            strategy_a=strategy_a["name"],
            strategy_b=strategy_b["name"],
            metrics_a=strategy_a["metrics"],
            metrics_b=strategy_b["metrics"]
        )
        
        print(f"⚔️  HEAD-TO-HEAD COMPARISON:")
        print(f"   Strategy A: {strategy_a['name']}")
        print(f"   Strategy B: {strategy_b['name']}")
        
        print(f"\n📊 METRIC COMPARISON:")
        metrics_comparison = [
            ("Total Trades", strategy_a["metrics"]["total_trades"], strategy_b["metrics"]["total_trades"], "Higher is better"),
            ("Win Rate", f"{strategy_a['metrics']['win_rate']*100:.1f}%", f"{strategy_b['metrics']['win_rate']*100:.1f}%", "Higher is better"),
            ("Avg Return", f"{strategy_a['metrics']['avg_return']*100:.1f}%", f"{strategy_b['metrics']['avg_return']*100:.1f}%", "Higher is better"),
            ("Max Drawdown", f"{strategy_a['metrics']['max_drawdown']*100:.1f}%", f"{strategy_b['metrics']['max_drawdown']*100:.1f}%", "Less negative is better"),
            ("Sharpe Ratio", f"{strategy_a['metrics']['sharpe_ratio']:.2f}", f"{strategy_b['metrics']['sharpe_ratio']:.2f}", "Higher is better")
        ]
        
        print(f"{'Metric':<15} {'Strategy A':<12} {'Strategy B':<12} {'Better':<20}")
        print("-" * 65)
        
        for metric, value_a, value_b, preference in metrics_comparison:
            # Determine which is better (simplified logic)
            if "Higher is better" in preference:
                if metric == "Total Trades":
                    better = "A" if strategy_a["metrics"]["total_trades"] > strategy_b["metrics"]["total_trades"] else "B"
                elif metric == "Win Rate":
                    better = "A" if strategy_a["metrics"]["win_rate"] > strategy_b["metrics"]["win_rate"] else "B"
                elif metric == "Avg Return":
                    better = "A" if strategy_a["metrics"]["avg_return"] > strategy_b["metrics"]["avg_return"] else "B"
                elif metric == "Sharpe Ratio":
                    better = "A" if strategy_a["metrics"]["sharpe_ratio"] > strategy_b["metrics"]["sharpe_ratio"] else "B"
                else:
                    better = "?"
            else:
                # For drawdown (less negative is better)
                better = "A" if strategy_a["metrics"]["max_drawdown"] > strategy_b["metrics"]["max_drawdown"] else "B"
            
            winner_icon = "🏆" if better in ["A", "B"] else "🤝"
            print(f"{metric:<15} {value_a:<12} {value_b:<12} {winner_icon} Strategy {better}")
        
        # Overall recommendation
        print(f"\n💡 AI RECOMMENDATION:")
        if strategy_a["metrics"]["sharpe_ratio"] > strategy_b["metrics"]["sharpe_ratio"]:
            recommendation = f"{strategy_a['name']} has better risk-adjusted returns (Sharpe: {strategy_a['metrics']['sharpe_ratio']:.2f})"
        else:
            recommendation = f"{strategy_b['name']} has better risk-adjusted returns (Sharpe: {strategy_b['metrics']['sharpe_ratio']:.2f})"
        
        print(f"   {recommendation}")
        
        print("✅ Strategy comparison completed!")
    
    async def ai_strategy_insights_demo(self):
        """Demonstrate AI-powered strategy insights"""
        print("\n🤖 AI-Powered Strategy Insights")
        print("=" * 50)
        
        # Sample AI insights
        ai_insights = [
            {
                "insight_type": "Pattern Recognition",
                "title": "Successful Accumulation Pattern Detected",
                "description": "Whales show 78% success rate when accumulating over 2-3 weeks",
                "confidence": 0.89,
                "actionable": True,
                "recommendation": "Follow accumulator patterns during low volatility periods"
            },
            {
                "insight_type": "Market Timing",
                "title": "Optimal Entry Timing Identified",
                "description": "Best performance when entering 2-4 hours after large whale activity",
                "confidence": 0.76,
                "actionable": True,
                "recommendation": "Set alerts for whale activity and time entries accordingly"
            },
            {
                "insight_type": "Risk Management",
                "title": "Position Sizing Optimization",
                "description": "Risk-adjusted returns improve by 23% with dynamic position sizing",
                "confidence": 0.82,
                "actionable": True,
                "recommendation": "Implement position sizing based on whale confidence scores"
            },
            {
                "insight_type": "Correlation Analysis",
                "title": "Cross-Chain Opportunity Detected",
                "description": "Strong correlation between Ethereum and Solana whale movements",
                "confidence": 0.71,
                "actionable": False,
                "recommendation": "Monitor both chains simultaneously for early signals"
            }
        ]
        
        print("🧠 AI STRATEGY INSIGHTS:")
        for insight in ai_insights:
            ai_insight = AIStrategyInsight(
                insight_type=insight["insight_type"],
                title=insight["title"],
                description=insight["description"],
                confidence=insight["confidence"],
                actionable=insight["actionable"],
                recommendation=insight["recommendation"]
            )
            
            actionable_icon = "✅" if insight["actionable"] else "ℹ️"
            confidence_bar = "█" * int(insight["confidence"] * 10) + "░" * (10 - int(insight["confidence"] * 10))
            
            print(f"\n   {actionable_icon} {insight['insight_type']}")
            print(f"      {insight['title']}")
            print(f"      {insight['description']}")
            print(f"      Confidence: {confidence_bar} {insight['confidence']:.2f}")
            print(f"      💡 {insight['recommendation']}")
        
        # Generate composite insight
        print(f"\n🎯 COMPOSITE STRATEGY RECOMMENDATION:")
        print(f"   Based on AI analysis of {len(ai_insights)} insights:")
        print(f"   1. Focus on accumulation patterns (89% confidence)")
        print(f"   2. Implement dynamic position sizing (82% confidence)")
        print(f"   3. Optimize entry timing (76% confidence)")
        print(f"   4. Monitor cross-chain correlations (71% confidence)")
        
        print("✅ AI strategy insights completed!")
    
    async def strategy_optimization_demo(self):
        """Demonstrate strategy optimization recommendations"""
        print("\n⚡ Strategy Optimization Demo")
        print("=" * 50)
        
        # Current strategy analysis
        current_strategy = {
            "name": "Basic Whale Follow",
            "performance": {
                "total_return": 0.45,
                "max_drawdown": -0.15,
                "win_rate": 0.68,
                "sharpe_ratio": 1.25
            }
        }
        
        # Optimization recommendations
        optimizations = [
            {
                "category": "Entry Timing",
                "current_performance": "68% success rate",
                "optimization": "Add 2-4 hour delay after whale activity",
                "expected_improvement": "+8% win rate",
                "implementation_difficulty": "Medium",
                "risk_impact": "Low"
            },
            {
                "category": "Position Sizing",
                "current_performance": "Fixed 10% allocation",
                "optimization": "Dynamic sizing based on whale confidence",
                "expected_improvement": "+15% risk-adjusted returns",
                "implementation_difficulty": "High",
                "risk_impact": "Medium"
            },
            {
                "category": "Coin Selection",
                "current_performance": "All major coins",
                "optimization": "Focus on ETH, BTC with momentum indicators",
                "expected_improvement": "+12% success rate",
                "implementation_difficulty": "Low",
                "risk_impact": "Low"
            },
            {
                "category": "Exit Strategy",
                "current_performance": "Fixed stop loss",
                "optimization": "Trailing stops based on whale exit patterns",
                "expected_improvement": "+6% average returns",
                "implementation_difficulty": "Medium",
                "risk_impact": "Low"
            }
        ]
        
        print(f"⚡ CURRENT STRATEGY: {current_strategy['name']}")
        print(f"   Total Return: {current_strategy['performance']['total_return']*100:.1f}%")
        print(f"   Max Drawdown: {current_strategy['performance']['max_drawdown']*100:.1f}%")
        print(f"   Win Rate: {current_strategy['performance']['win_rate']*100:.1f}%")
        print(f"   Sharpe Ratio: {current_strategy['performance']['sharpe_ratio']:.2f}")
        
        print(f"\n🚀 OPTIMIZATION RECOMMENDATIONS:")
        for opt in optimizations:
            difficulty_icon = {"Low": "🟢", "Medium": "🟡", "High": "🔴"}.get(opt["implementation_difficulty"], "⚪")
            risk_icon = {"Low": "🟢", "Medium": "🟡", "High": "🔴"}.get(opt["risk_impact"], "⚪")
            
            print(f"\n   📊 {opt['category']}")
            print(f"      Current: {opt['current_performance']}")
            print(f"      Optimized: {opt['optimization']}")
            print(f"      Expected: {opt['expected_improvement']}")
            print(f"      {difficulty_icon} Difficulty: {opt['implementation_difficulty']}")
            print(f"      {risk_icon} Risk Impact: {opt['risk_impact']}")
        
        # Optimization roadmap
        print(f"\n🗺️  OPTIMIZATION ROADMAP:")
        print(f"   Phase 1 (Week 1-2): Coin Selection Optimization (Easy wins)")
        print(f"   Phase 2 (Week 3-4): Entry Timing Improvements (Medium effort)")
        print(f"   Phase 3 (Week 5-6): Exit Strategy Enhancement (Medium effort)")
        print(f"   Phase 4 (Week 7-8): Position Sizing System (High effort)")
        
        # Expected results
        expected_results = {
            "win_rate": "68% → 78% (+10%)",
            "total_return": "45% → 65% (+20%)",
            "max_drawdown": "-15% → -12% (Better)",
            "sharpe_ratio": "1.25 → 1.85 (+48%)"
        }
        
        print(f"\n📈 EXPECTED RESULTS AFTER OPTIMIZATION:")
        for metric, improvement in expected_results.items():
            print(f"   {metric.replace('_', ' ').title()}: {improvement}")
        
        print("✅ Strategy optimization completed!")
    
    async def run_all_demos(self):
        """Run all strategy demonstrations"""
        print("🎯 HYPERLIQUID MONITOR PLUS - STRATEGY MODULE EXAMPLES")
        print("=" * 70)
        
        await self.whale_behavior_analysis_demo()
        await self.strategy_performance_demo()
        await self.strategy_comparison_demo()
        await self.ai_strategy_insights_demo()
        await self.strategy_optimization_demo()
        
        print("\n" + "=" * 70)
        print("🎉 All strategy demos completed successfully!")
        print("💡 Strategy capabilities demonstrated:")
        print("   🐋 Whale behavior pattern analysis")
        print("   📊 Strategy performance metrics")
        print("   🔍 Strategy comparison analysis")
        print("   🤖 AI-powered strategy insights")
        print("   ⚡ Strategy optimization recommendations")


async def main():
    """Main demonstration function"""
    
    # Run strategy demos
    strategy_demo = StrategyAnalysisDemo()
    await strategy_demo.run_all_demos()


if __name__ == "__main__":
    asyncio.run(main())