#!/usr/bin/env python3
"""
Intelligence Module Example - AI-Powered Market Intelligence

This example demonstrates the intelligence system including:
- Social sentiment analysis
- Pattern recognition with ML
- Intelligence signals and insights
- Predictive analytics
- Behavioral analysis
"""

import asyncio
import json
import random
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional

# Import intelligence components
from hyperliquid_monitor_plus.intelligence import (
    SocialSentimentAnalyzer, SentimentScore, SentimentAnomaly,
    IntelligenceSignal, IntelligenceSummary, PredictiveInsight,
    IntelligenceEnhancements, ModelEnsemble
)

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


class IntelligenceSystemDemo:
    """Demonstration of AI-powered market intelligence"""
    
    def __init__(self):
        self.sentiment_analyzer = SocialSentimentAnalyzer()
        self.intelligence_enhancements = IntelligenceEnhancements()
        self.model_ensemble = ModelEnsemble()
    
    async def sentiment_analysis_demo(self):
        """Demonstrate social sentiment analysis"""
        print("🧠 Social Sentiment Analysis Demo")
        print("=" * 50)
        
        # Sample social media data
        social_data = [
            {"platform": "Twitter", "coin": "BTC", "mentions": 1250, "sentiment_score": 0.75, "volume": 5600},
            {"platform": "Reddit", "coin": "ETH", "mentions": 890, "sentiment_score": 0.62, "volume": 3400},
            {"platform": "Telegram", "coin": "SOL", "mentions": 450, "sentiment_score": 0.45, "volume": 1200},
            {"platform": "Discord", "coin": "AVAX", "mentions": 320, "sentiment_score": 0.82, "volume": 890},
            {"platform": "Twitter", "coin": "LINK", "mentions": 180, "sentiment_score": 0.35, "volume": 450}
        ]
        
        print("📱 Social Media Sentiment Analysis:")
        
        for data in social_data:
            sentiment = self.sentiment_analyzer.analyze_sentiment(
                platform=data["platform"],
                coin=data["coin"],
                mentions=data["mentions"],
                sentiment_score=data["sentiment_score"],
                volume=data["volume"]
            )
            
            # Determine sentiment category
            if sentiment.score >= 0.7:
                category = "🟢 VERY BULLISH"
            elif sentiment.score >= 0.6:
                category = "🟡 BULLISH"
            elif sentiment.score >= 0.4:
                category = "⚪ NEUTRAL"
            elif sentiment.score >= 0.2:
                category = "🟠 BEARISH"
            else:
                category = "🔴 VERY BEARISH"
            
            print(f"\n   {data['platform']:8} | {data['coin']:6} | {category}")
            print(f"      Mentions: {data['mentions']:>4} | Score: {sentiment.score:.2f} | Volume: {data['volume']}")
            print(f"      Confidence: {sentiment.confidence:.2f} | Anomaly: {sentiment.is_anomaly}")
        
        print("\n🚨 Sentiment Anomalies Detected:")
        anomalies = self.sentiment_analyzer.detect_sentiment_anomalies(social_data)
        for anomaly in anomalies:
            print(f"   ⚡ {anomaly.coin}: {anomaly.platform} - "
                  f"Score: {anomaly.score:.2f} (Deviation: {anomaly.deviation:+.2f})")
        
        print("✅ Sentiment analysis completed!")
    
    async def pattern_recognition_demo(self):
        """Demonstrate AI pattern recognition"""
        print("\n🔍 AI Pattern Recognition Demo")
        print("=" * 50)
        
        # Sample whale trading patterns
        trading_patterns = [
            {
                "pattern_type": "Accumulation",
                "coins": ["BTC", "ETH"],
                "timeframe": "2-3 weeks",
                "characteristics": ["Gradual buying", "Low volatility", "Volume increasing"],
                "confidence": 0.85
            },
            {
                "pattern_type": "Distribution", 
                "coins": ["SOL", "AVAX"],
                "timeframe": "1-2 weeks",
                "characteristics": ["Steady selling", "High volume", "Price declining"],
                "confidence": 0.92
            },
            {
                "pattern_type": "Rotation",
                "coins": ["LINK", "UNI"],
                "timeframe": "3-5 days", 
                "characteristics": ["Quick moves", "High volatility", "Profit taking"],
                "confidence": 0.78
            }
        ]
        
        print("🤖 AI Pattern Recognition Results:")
        
        for pattern in trading_patterns:
            # Analyze pattern with ML models
            analysis = self.model_ensemble.analyze_pattern(
                pattern_type=pattern["pattern_type"],
                coins=pattern["coins"],
                timeframe=pattern["timeframe"],
                characteristics=pattern["characteristics"]
            )
            
            # Determine action recommendation
            if pattern["pattern_type"] == "Accumulation":
                recommendation = "🟢 FOLLOW - Accumulate positions"
            elif pattern["pattern_type"] == "Distribution":
                recommendation = "🔴 EXIT - Avoid following"
            else:
                recommendation = "🟡 CAUTIOUS - Monitor closely"
            
            print(f"\n   🎯 Pattern: {pattern['pattern_type']}")
            print(f"      Coins: {', '.join(pattern['coins'])}")
            print(f"      Timeframe: {pattern['timeframe']}")
            print(f"      Confidence: {pattern['confidence']:.2f}")
            print(f"      Characteristics: {', '.join(pattern['characteristics'])}")
            print(f"      🤖 AI Recommendation: {recommendation}")
        
        print("✅ Pattern recognition completed!")
    
    async def intelligence_signals_demo(self):
        """Demonstrate intelligence signal generation"""
        print("\n📡 Intelligence Signal Generation")
        print("=" * 50)
        
        # Sample market signals
        signals = [
            {
                "signal_type": "Whale Accumulation",
                "strength": 0.85,
                "coins": ["BTC", "ETH"],
                "timeframe": "24 hours",
                "data": {"volume_surge": "2.5x", "large_buys": 15, "price_impact": "+2.3%"}
            },
            {
                "signal_type": "Market Momentum",
                "strength": 0.72,
                "coins": ["SOL", "AVAX"],
                "timeframe": "12 hours", 
                "data": {"momentum_score": 0.68, "correlation": 0.89, "volatility": "increasing"}
            },
            {
                "signal_type": "Social Hype",
                "strength": 0.63,
                "coins": ["LINK"],
                "timeframe": "6 hours",
                "data": {"mentions_increase": "150%", "sentiment_shift": "positive", "viral_score": 0.78}
            },
            {
                "signal_type": "Technical Breakout",
                "strength": 0.91,
                "coins": ["BTC"],
                "timeframe": "8 hours",
                "data": {"breakout_level": "$45,500", "volume_confirmation": True, "rsi": 72}
            }
        ]
        
        print("🎯 Intelligence Signals:")
        
        for signal in signals:
            # Generate signal object
            intelligence_signal = IntelligenceSignal(
                signal_type=signal["signal_type"],
                strength=signal["strength"],
                coins=signal["coins"],
                timeframe=signal["timeframe"],
                data=signal["data"]
            )
            
            # Determine signal quality
            if signal["strength"] >= 0.8:
                quality = "🟢 STRONG"
            elif signal["strength"] >= 0.6:
                quality = "🟡 MODERATE"
            else:
                quality = "🟠 WEAK"
            
            print(f"\n   📡 {signal['signal_type']} | {quality}")
            print(f"      Strength: {signal['strength']:.2f} | Timeframe: {signal['timeframe']}")
            print(f"      Coins: {', '.join(signal['coins'])}")
            print(f"      📊 Data: {json.dumps(signal['data'], indent=8)}")
        
        print("✅ Intelligence signals completed!")
    
    async def predictive_analytics_demo(self):
        """Demonstrate predictive analytics"""
        print("\n🔮 Predictive Analytics Demo")
        print("=" * 50)
        
        # Sample predictions
        predictions = [
            {
                "prediction_type": "Price Movement",
                "coin": "BTC",
                "forecast": "Bullish",
                "timeframe": "48 hours",
                "confidence": 0.75,
                "target_price": 47000,
                "probability": 0.68
            },
            {
                "prediction_type": "Volume Spike",
                "coin": "ETH",
                "forecast": "High Volume Expected",
                "timeframe": "24 hours",
                "confidence": 0.82,
                "expected_multiplier": 2.1,
                "probability": 0.73
            },
            {
                "prediction_type": "Correlation Shift",
                "coin": "SOL",
                "forecast": "Decoupling from BTC",
                "timeframe": "12 hours",
                "confidence": 0.65,
                "expected_correlation": 0.45,
                "probability": 0.59
            }
        ]
        
        print("🔮 Predictive Insights:")
        
        for pred in predictions:
            insight = PredictiveInsight(
                prediction_type=pred["prediction_type"],
                coin=pred["coin"],
                forecast=pred["forecast"],
                timeframe=pred["timeframe"],
                confidence=pred["confidence"],
                data={
                    "target_price" if "target_price" in pred else "expected_multiplier": 
                    pred.get("target_price") or pred.get("expected_multiplier"),
                    "probability": pred["probability"]
                }
            )
            
            # Determine insight reliability
            if pred["confidence"] >= 0.8:
                reliability = "🟢 HIGH"
            elif pred["confidence"] >= 0.6:
                reliability = "🟡 MEDIUM"
            else:
                reliability = "🟠 LOW"
            
            print(f"\n   🔮 {pred['prediction_type']} - {pred['coin']}")
            print(f"      Forecast: {pred['forecast']}")
            print(f"      Timeframe: {pred['timeframe']}")
            print(f"      Confidence: {pred['confidence']:.2f} | Reliability: {reliability}")
            
            # Show specific data
            if "target_price" in pred:
                print(f"      🎯 Target Price: ${pred['target_price']:,.2f}")
            if "expected_multiplier" in pred:
                print(f"      📊 Expected Multiplier: {pred['expected_multiplier']:.1f}x")
            if "expected_correlation" in pred:
                print(f"      🔗 Expected Correlation: {pred['expected_correlation']:.2f}")
            
            print(f"      📈 Probability: {pred['probability']:.2f}")
        
        print("✅ Predictive analytics completed!")
    
    async def behavioral_analysis_demo(self):
        """Demonstrate whale behavioral analysis"""
        print("\n🐋 Whale Behavioral Analysis")
        print("=" * 50)
        
        # Sample whale behaviors
        behaviors = [
            {
                "address": "0x010461C14e146ac35Fe42271BDC1134EE31C703a",
                "behavior_type": "Conservative Accumulator",
                "characteristics": ["Gradual position building", "Low leverage", "Long-term holding"],
                "success_rate": 0.78,
                "avg_holding_period": "45 days"
            },
            {
                "address": "0x8eb8a3b98659Cce290402893d0123abb75E3ab28",
                "behavior_type": "Momentum Trader", 
                "characteristics": ["Quick entries/exits", "High frequency", "Technical analysis"],
                "success_rate": 0.65,
                "avg_holding_period": "3 days"
            },
            {
                "address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
                "behavior_type": "Market Maker",
                "characteristics": ["Providing liquidity", "Spread capture", "Neutral positioning"],
                "success_rate": 0.72,
                "avg_holding_period": "1 day"
            }
        ]
        
        print("🧠 Behavioral Profiles:")
        
        for behavior in behaviors:
            profile = self.intelligence_enhancements.analyze_behavior(
                address=behavior["address"],
                behavior_type=behavior["behavior_type"],
                characteristics=behavior["characteristics"],
                success_rate=behavior["success_rate"],
                avg_holding_period=behavior["avg_holding_period"]
            )
            
            # Determine follow strategy
            if behavior["behavior_type"] == "Conservative Accumulator":
                strategy = "🟢 HIGHLY FOLLOWABLE - Proven track record"
            elif behavior["behavior_type"] == "Momentum Trader":
                strategy = "🟡 FOLLOW CAREFULLY - High risk/reward"
            else:
                strategy = "⚪ INFORMATIONAL - Learn patterns"
            
            print(f"\n   🐋 {behavior['behavior_type']}")
            print(f"      Address: {behavior['address'][:16]}...")
            print(f"      Characteristics: {', '.join(behavior['characteristics'])}")
            print(f"      Success Rate: {behavior['success_rate']:.2f}")
            print(f"      Avg Holding: {behavior['avg_holding_period']}")
            print(f"      🤖 Strategy: {strategy}")
            
            # Generate behavioral insights
            insights = self.intelligence_enhancements.generate_behavioral_insights(profile)
            print(f"      💡 Key Insights: {insights['key_insight']}")
        
        print("✅ Behavioral analysis completed!")
    
    async def comprehensive_intelligence_demo(self):
        """Demonstrate comprehensive intelligence gathering"""
        print("\n🎯 Comprehensive Intelligence Dashboard")
        print("=" * 50)
        
        # Create comprehensive intelligence summary
        intelligence_summary = IntelligenceSummary(
            timestamp=datetime.now(),
            market_sentiment=0.72,
            dominant_pattern="Accumulation",
            key_signals=[
                "Strong whale accumulation in BTC/ETH",
                "Increasing social sentiment for SOL",
                "Technical breakout signals in LINK"
            ],
            predictions=[
                "BTC target: $47,000 (68% probability)",
                "ETH volume spike expected (73% probability)",
                "SOL correlation shift likely (59% probability)"
            ],
            whale_behaviors=[
                "Conservative accumulators active",
                "Market makers expanding liquidity",
                "Momentum traders taking profits"
            ],
            risk_assessment="Moderate - High conviction opportunities",
            recommendation="Bullish stance with selective entries"
        )
        
        print("📊 INTELLIGENCE SUMMARY")
        print(f"⏰ Timestamp: {intelligence_summary.timestamp}")
        print(f"😊 Market Sentiment: {intelligence_summary.market_sentiment:.2f} (Bullish)")
        print(f"🎯 Dominant Pattern: {intelligence_summary.dominant_pattern}")
        
        print(f"\n🔔 KEY SIGNALS:")
        for i, signal in enumerate(intelligence_summary.key_signals, 1):
            print(f"   {i}. {signal}")
        
        print(f"\n🔮 PREDICTIONS:")
        for i, prediction in enumerate(intelligence_summary.predictions, 1):
            print(f"   {i}. {prediction}")
        
        print(f"\n🐋 WHALE BEHAVIORS:")
        for i, behavior in enumerate(intelligence_summary.whale_behaviors, 1):
            print(f"   {i}. {behavior}")
        
        print(f"\n⚠️  Risk Assessment: {intelligence_summary.risk_assessment}")
        print(f"💡 Recommendation: {intelligence_summary.recommendation}")
        
        print("✅ Comprehensive intelligence completed!")
    
    async def run_all_demos(self):
        """Run all intelligence demonstrations"""
        print("🎯 HYPERLIQUID MONITOR PLUS - INTELLIGENCE MODULE EXAMPLES")
        print("=" * 70)
        
        await self.sentiment_analysis_demo()
        await self.pattern_recognition_demo()
        await self.intelligence_signals_demo()
        await self.predictive_analytics_demo()
        await self.behavioral_analysis_demo()
        await self.comprehensive_intelligence_demo()
        
        print("\n" + "=" * 70)
        print("🎉 All intelligence demos completed successfully!")
        print("💡 AI capabilities demonstrated:")
        print("   🧠 Social sentiment analysis")
        print("   🤖 AI pattern recognition")
        print("   📡 Intelligence signal generation")
        print("   🔮 Predictive analytics")
        print("   🐋 Behavioral analysis")
        print("   📊 Comprehensive intelligence dashboard")


async def main():
    """Main demonstration function"""
    
    # Run intelligence demos
    intelligence_demo = IntelligenceSystemDemo()
    await intelligence_demo.run_all_demos()


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