#!/usr/bin/env python3
"""
Integration Module Example - Dashboard and API Integration

This example demonstrates integration capabilities including:
- Real-time dashboard integration
- Webhook notifications
- API endpoints
- External service integration
"""

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

# Import integration components
from hyperliquid_monitor_plus.integration import RealTimeDashboard, WebhookManager, APIEndpoints

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


class IntegrationDemo:
    """Demonstration of integration capabilities"""
    
    def __init__(self):
        self.dashboard = RealTimeDashboard()
        self.webhooks = WebhookManager()
        self.api = APIEndpoints()
    
    async def dashboard_integration_demo(self):
        """Demonstrate dashboard integration"""
        print("📊 Real-time Dashboard Integration")
        print("=" * 50)
        
        # Simulate dashboard updates
        dashboard_data = {
            "timestamp": datetime.now().isoformat(),
            "active_whales": 12,
            "total_tracked_value": 175_000_000,
            "alerts_today": 8,
            "top_performers": [
                {"address": "0x010461C14e146ac35Fe42271BDC1134EE31C703a", "pnl": 785765},
                {"address": "0x8eb8a3b98659cce290402893d0123abb75E3ab28", "pnl": 675000}
            ],
            "market_sentiment": 0.72,
            "recent_trades": [
                {"coin": "ETH", "side": "BUY", "size": 150, "price": 2450},
                {"coin": "BTC", "side": "SELL", "size": 25, "price": 45200}
            ]
        }
        
        print("📈 UPDATING DASHBOARD...")
        await self.dashboard.update_dashboard(dashboard_data)
        print("   ✅ Dashboard updated successfully")
        
        # Display dashboard preview
        print("\n📊 DASHBOARD PREVIEW:")
        print(f"   ⏰ Last Update: {dashboard_data['timestamp']}")
        print(f"   👁️  Active Whales: {dashboard_data['active_whales']}")
        print(f"   💰 Tracked Value: ${dashboard_data['total_tracked_value']:,.2f}")
        print(f"   🚨 Alerts Today: {dashboard_data['alerts_today']}")
        print(f"   😊 Market Sentiment: {dashboard_data['market_sentiment']:.2f}")
        
        print("\n🏆 TOP PERFORMERS:")
        for performer in dashboard_data['top_performers']:
            print(f"   {performer['address'][:16]}... ${performer['pnl']:,.2f}")
        
        print("\n📝 RECENT TRADES:")
        for trade in dashboard_data['recent_trades']:
            side_emoji = "📈" if trade['side'] == "BUY" else "📉"
            print(f"   {side_emoji} {trade['side']} {trade['size']} {trade['coin']} @ ${trade['price']:,.2f}")
        
        print("✅ Dashboard integration completed!")
    
    async def webhook_integration_demo(self):
        """Demonstrate webhook integration"""
        print("\n🔗 Webhook Integration")
        print("=" * 50)
        
        # Configure webhooks
        webhook_urls = [
            "https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK",
            "https://discord.com/api/webhooks/YOUR/DISCORD/WEBHOOK",
            "https://your-app.com/api/webhooks/whale-alerts"
        ]
        
        print("🔧 CONFIGURING WEBHOOKS...")
        for i, url in enumerate(webhook_urls, 1):
            success = await self.webhooks.add_webhook(f"webhook_{i}", url)
            print(f"   {'✅' if success else '❌'} Webhook {i}: {url[:50]}...")
        
        # Send sample alerts
        alerts = [
            {
                "type": "whale_detection",
                "severity": "high",
                "data": {
                    "address": "0x010461C14e146ac35Fe42271BDC1134EE31C703a",
                    "coin": "ETH",
                    "size": 150,
                    "price": 2450,
                    "value": 367500
                }
            },
            {
                "type": "position_update",
                "severity": "medium",
                "data": {
                    "address": "0x8eb8a3b98659cce290402893d0123abb75E3ab28",
                    "coin": "BTC",
                    "pnl": 160640,
                    "percentage": 7.8
                }
            }
        ]
        
        print("\n📤 SENDING WEBHOOK ALERTS...")
        for alert in alerts:
            result = await self.webhooks.send_alert(alert)
            status = "✅ SENT" if result else "❌ FAILED"
            print(f"   {status} {alert['type']} ({alert['severity']} priority)")
        
        print("✅ Webhook integration completed!")
    
    async def api_endpoints_demo(self):
        """Demonstrate API endpoints"""
        print("\n🌐 API Endpoints Demo")
        print("=" * 50)
        
        # Simulate API calls
        endpoints = [
            {
                "method": "GET",
                "endpoint": "/api/v1/whales/active",
                "description": "Get active whale addresses",
                "params": {"limit": 10}
            },
            {
                "method": "GET", 
                "endpoint": "/api/v1/whales/{address}/stats",
                "description": "Get whale statistics",
                "params": {"address": "0x010461C14e146ac35Fe42271BDC1134EE31C703a"}
            },
            {
                "method": "GET",
                "endpoint": "/api/v1/market/sentiment",
                "description": "Get market sentiment",
                "params": {}
            },
            {
                "method": "POST",
                "endpoint": "/api/v1/alerts/create",
                "description": "Create custom alert",
                "params": {"type": "whale_detection", "threshold": 1000000}
            }
        ]
        
        print("🔌 API ENDPOINTS AVAILABLE:")
        for endpoint in endpoints:
            print(f"\n   {endpoint['method']:4} {endpoint['endpoint']}")
            print(f"      Description: {endpoint['description']}")
            if endpoint['params']:
                print(f"      Parameters: {json.dumps(endpoint['params'])}")
        
        # Simulate API responses
        print(f"\n📡 SIMULATED API RESPONSES:")
        
        # Active whales response
        active_whales_response = {
            "status": "success",
            "data": {
                "whales": [
                    {"address": "0x010461C14e146ac35Fe42271BDC1134EE31C703a", "total_value": 15000000},
                    {"address": "0x8eb8a3b98659cce290402893d0123abb75E3ab28", "total_value": 8500000}
                ],
                "total": 2,
                "timestamp": datetime.now().isoformat()
            }
        }
        
        print(f"   GET /api/v1/whales/active:")
        print(f"   Status: {active_whales_response['status']}")
        print(f"   Total Whales: {active_whales_response['data']['total']}")
        
        # Market sentiment response
        sentiment_response = {
            "status": "success",
            "data": {
                "overall_sentiment": 0.72,
                "fear_greed_index": 68,
                "social_sentiment": 0.65,
                "technical_sentiment": 0.78,
                "timestamp": datetime.now().isoformat()
            }
        }
        
        print(f"\n   GET /api/v1/market/sentiment:")
        print(f"   Status: {sentiment_response['status']}")
        print(f"   Overall Sentiment: {sentiment_response['data']['overall_sentiment']}")
        print(f"   Fear & Greed Index: {sentiment_response['data']['fear_greed_index']}")
        
        print("✅ API endpoints demo completed!")
    
    async def external_services_demo(self):
        """Demonstrate external service integration"""
        print("\n🔌 External Services Integration")
        print("=" * 50)
        
        # Supported external services
        services = [
            {
                "name": "TradingView",
                "type": "Chart Integration",
                "description": "Send whale activity to TradingView charts"
            },
            {
                "name": "Telegram",
                "type": "Notification Service", 
                "description": "Send alerts via Telegram bot"
            },
            {
                "name": "Discord",
                "type": "Community Platform",
                "description": "Share whale activity in Discord channels"
            },
            {
                "name": "Zapier",
                "type": "Automation Platform",
                "description": "Connect whale alerts to 1000+ apps"
            },
            {
                "name": "Google Sheets",
                "type": "Data Export",
                "description": "Export whale data to spreadsheets"
            }
        ]
        
        print("🔗 SUPPORTED EXTERNAL SERVICES:")
        for service in services:
            print(f"\n   📋 {service['name']}")
            print(f"      Type: {service['type']}")
            print(f"      Description: {service['description']}")
        
        # Example integrations
        print(f"\n📤 EXAMPLE INTEGRATIONS:")
        
        # Telegram integration example
        telegram_config = {
            "bot_token": "your-telegram-bot-token",
            "chat_id": "your-chat-id",
            "whale_addresses": ["0x010461C14e146ac35Fe42271BDC1134EE31C703a"],
            "min_alert_value": 1000000
        }
        
        print(f"\n   📱 TELEGRAM INTEGRATION:")
        print(f"      Bot Token: {telegram_config['bot_token'][:20]}...")
        print(f"      Chat ID: {telegram_config['chat_id']}")
        print(f"      Monitored Addresses: {len(telegram_config['whale_addresses'])}")
        print(f"      Min Alert Value: ${telegram_config['min_alert_value']:,.2f}")
        
        # TradingView integration example
        tv_config = {
            "chart_url": "https://tradingview.com/charts",
            "symbols": ["BTCUSD", "ETHUSD", "SOLUSD"],
            "whale_trades_overlay": True,
            "volume_profile": True
        }
        
        print(f"\n   📊 TRADINGVIEW INTEGRATION:")
        print(f"      Chart URL: {tv_config['chart_url']}")
        print(f"      Symbols: {', '.join(tv_config['symbols'])}")
        print(f"      Whale Overlay: {tv_config['whale_trades_overlay']}")
        
        print("✅ External services demo completed!")
    
    async def real_time_updates_demo(self):
        """Demonstrate real-time updates"""
        print("\n⚡ Real-time Updates Demo")
        print("=" * 50)
        
        # Simulate real-time whale activities
        activities = [
            {
                "timestamp": datetime.now().isoformat(),
                "type": "large_trade",
                "data": {
                    "address": "0x010461C14e146ac35Fe42271BDC1134EE31C703a",
                    "coin": "ETH",
                    "side": "BUY",
                    "size": 200,
                    "price": 2455,
                    "value": 491000
                }
            },
            {
                "timestamp": datetime.now().isoformat(),
                "type": "position_update",
                "data": {
                    "address": "0x8eb8a3b98659cce290402893d0123abb75E3ab28", 
                    "coin": "BTC",
                    "current_value": 1140000,
                    "pnl": 64000,
                    "pnl_percentage": 5.95
                }
            },
            {
                "timestamp": datetime.now().isoformat(),
                "type": "sentiment_change",
                "data": {
                    "coin": "SOL",
                    "sentiment_change": +0.15,
                    "mentions_increase": 45,
                    "new_sentiment": 0.78
                }
            }
        ]
        
        print("⚡ REAL-TIME ACTIVITIES:")
        for activity in activities:
            print(f"\n   📡 {activity['type'].replace('_', ' ').title()}")
            print(f"      Time: {activity['timestamp']}")
            
            if activity['type'] == 'large_trade':
                data = activity['data']
                side_emoji = "📈" if data['side'] == "BUY" else "📉"
                print(f"      {side_emoji} {data['side']} {data['size']} {data['coin']} @ ${data['price']:,.2f}")
                print(f"      💰 Value: ${data['value']:,.2f}")
                print(f"      🐋 Whale: {data['address'][:16]}...")
                
            elif activity['type'] == 'position_update':
                data = activity['data']
                print(f"      🐋 Whale: {data['address'][:16]}...")
                print(f"      💼 Position Value: ${data['current_value']:,.2f}")
                print(f"      💎 P&L: ${data['pnl']:,.2f} ({data['pnl_percentage']:+.2f}%)")
                
            elif activity['type'] == 'sentiment_change':
                data = activity['data']
                print(f"      🪙 Coin: {data['coin']}")
                print(f"      😊 Sentiment Change: {data['sentiment_change']:+.2f}")
                print(f"      📱 Mentions: +{data['mentions_increase']}")
                print(f"      🎯 New Sentiment: {data['new_sentiment']:.2f}")
        
        print("✅ Real-time updates demo completed!")
    
    async def run_all_demos(self):
        """Run all integration demonstrations"""
        print("🎯 HYPERLIQUID MONITOR PLUS - INTEGRATION MODULE EXAMPLES")
        print("=" * 70)
        
        await self.dashboard_integration_demo()
        await self.webhook_integration_demo()
        await self.api_endpoints_demo()
        await self.external_services_demo()
        await self.real_time_updates_demo()
        
        print("\n" + "=" * 70)
        print("🎉 All integration demos completed successfully!")
        print("💡 Integration capabilities demonstrated:")
        print("   📊 Real-time dashboard integration")
        print("   🔗 Webhook notifications")
        print("   🌐 RESTful API endpoints")
        print("   🔌 External service integration")
        print("   ⚡ Real-time updates")


async def main():
    """Main demonstration function"""
    
    # Run integration demos
    integration_demo = IntegrationDemo()
    await integration_demo.run_all_demos()


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