#!/usr/bin/env python3
"""
Notifications Module Example - Alert System

This example demonstrates the notification system including:
- Multi-channel alerts (Telegram, Discord, Email)
- Custom alert rules and filters
- Real-time notifications
- Alert history and management
"""

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

# Import notification components
from hyperliquid_monitor_plus.notifications import (
    NotificationManager, AlertRule, AlertChannel, AlertPriority
)

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


class NotificationsDemo:
    """Demonstration of notification system"""
    
    def __init__(self):
        self.notification_manager = NotificationManager()
    
    async def basic_alerts_demo(self):
        """Demonstrate basic alert functionality"""
        print("🚨 Basic Alert System Demo")
        print("=" * 50)
        
        # Sample alert rules
        alert_rules = [
            {
                "name": "Large Whale Trade",
                "type": "whale_trade",
                "threshold": 1000000,
                "priority": "HIGH",
                "channels": ["telegram", "discord"]
            },
            {
                "name": "ETH Position Update",
                "type": "position_change",
                "coin": "ETH",
                "threshold": 500000,
                "priority": "MEDIUM", 
                "channels": ["telegram"]
            },
            {
                "name": "High P&L Alert",
                "type": "pnl_threshold",
                "threshold": 100000,
                "priority": "HIGH",
                "channels": ["email", "dashboard"]
            }
        ]
        
        print("⚙️  CONFIGURING ALERT RULES:")
        for rule in alert_rules:
            alert = AlertRule(
                name=rule["name"],
                alert_type=rule["type"],
                threshold=rule["threshold"],
                priority=AlertPriority[rule["priority"].upper()],
                channels=[AlertChannel[ch.upper()] for ch in rule["channels"]]
            )
            
            self.notification_manager.add_rule(alert)
            status_icon = {"HIGH": "🔴", "MEDIUM": "🟡", "LOW": "🟢"}.get(rule["priority"], "⚪")
            print(f"   {status_icon} {rule['name']} ({rule['priority']} priority)")
        
        print("✅ Alert rules configured!")
    
    async def telegram_notifications_demo(self):
        """Demonstrate Telegram notifications"""
        print("\n📱 Telegram Notifications Demo")
        print("=" * 50)
        
        # Configure Telegram
        telegram_config = {
            "bot_token": "your-telegram-bot-token",
            "chat_id": "your-telegram-chat-id",
            "bot_name": "WhaleMonitorBot"
        }
        
        print("🤖 TELEGRAM BOT CONFIGURATION:")
        print(f"   Bot Token: {telegram_config['bot_token'][:20]}...")
        print(f"   Chat ID: {telegram_config['chat_id']}")
        print(f"   Bot Name: {telegram_config['bot_name']}")
        
        # Send sample messages
        sample_messages = [
            {
                "type": "whale_alert",
                "message": "🐋 LARGE WHALE DETECTED!\nAddress: 0x01046...03a\nTrade: BUY 150 ETH @ $2,450\nValue: $367,500",
                "priority": "HIGH"
            },
            {
                "type": "position_update", 
                "message": "💼 Position Update\nETH Position: +$25,000 (15.2% gain)\nBTC Position: +$8,500 (3.8% gain)",
                "priority": "MEDIUM"
            },
            {
                "type": "market_sentiment",
                "message": "📊 Market Sentiment Update\nOverall: Bullish (0.72)\nFear & Greed: 68 (Greed)\nSocial Mentions: +25%",
                "priority": "LOW"
            }
        ]
        
        print("\n📤 SAMPLE TELEGRAM MESSAGES:")
        for msg in sample_messages:
            print(f"\n   📱 {msg['type'].replace('_', ' ').title()}")
            print(f"      {msg['message']}")
            priority_icon = {"HIGH": "🔴", "MEDIUM": "🟡", "LOW": "🟢"}.get(msg["priority"], "⚪")
            print(f"      Priority: {priority_icon} {msg['priority']}")
        
        print("✅ Telegram notifications demo completed!")
    
    async def discord_notifications_demo(self):
        """Demonstrate Discord notifications"""
        print("\n🎮 Discord Notifications Demo")
        print("=" * 50)
        
        # Configure Discord
        discord_config = {
            "webhook_url": "https://discord.com/api/webhooks/your/webhook/url",
            "channel_name": "#whale-alerts",
            "bot_name": "WhaleMonitor",
            "embed_color": 0x00ff00
        }
        
        print("🎮 DISCORD WEBHOOK CONFIGURATION:")
        print(f"   Webhook URL: {discord_config['webhook_url'][:50]}...")
        print(f"   Channel: {discord_config['channel_name']}")
        print(f"   Bot Name: {discord_config['bot_name']}")
        
        # Send embedded messages
        embed_examples = [
            {
                "title": "🐋 Whale Alert - Large Trade Detected",
                "description": "A significant whale trade has been detected",
                "fields": [
                    {"name": "Address", "value": "0x01046...03a", "inline": True},
                    {"name": "Trade", "value": "BUY 150 ETH", "inline": True},
                    {"name": "Price", "value": "$2,450", "inline": True},
                    {"name": "Value", "value": "$367,500", "inline": False}
                ],
                "color": 0xff0000,
                "timestamp": datetime.now().isoformat()
            },
            {
                "title": "📊 Market Intelligence Update",
                "description": "Market sentiment and whale behavior analysis",
                "fields": [
                    {"name": "Market Sentiment", "value": "Bullish (0.72)", "inline": True},
                    {"name": "Active Whales", "value": "12", "inline": True},
                    {"name": "Tracked Value", "value": "$175M", "inline": False}
                ],
                "color": 0x00ff00,
                "timestamp": datetime.now().isoformat()
            }
        ]
        
        print("\n📤 SAMPLE DISCORD EMBEDS:")
        for embed in embed_examples:
            print(f"\n   📋 {embed['title']}")
            print(f"      {embed['description']}")
            for field in embed['fields']:
                print(f"      {field['name']}: {field['value']}")
        
        print("✅ Discord notifications demo completed!")
    
    async def custom_alerts_demo(self):
        """Demonstrate custom alert creation"""
        print("\n⚙️  Custom Alert Creation Demo")
        print("=" * 50)
        
        # Custom alert conditions
        custom_conditions = [
            {
                "name": "Multi-Chain Whale Alert",
                "conditions": [
                    {"field": "trade_value", "operator": ">=", "value": 2000000},
                    {"field": "chain_count", "operator": ">=", "value": 2}
                ],
                "actions": ["telegram", "discord", "email"],
                "cooldown_minutes": 15
            },
            {
                "name": "High Frequency Trading Alert",
                "conditions": [
                    {"field": "trade_frequency", "operator": ">=", "value": 5},
                    {"field": "time_window_minutes", "operator": "<=", "value": 60}
                ],
                "actions": ["dashboard"],
                "cooldown_minutes": 30
            },
            {
                "name": "Loss Protection Alert",
                "conditions": [
                    {"field": "position_pnl", "operator": "<=", "value": -100000},
                    {"field": "position_size", "operator": ">=", "value": 1000000}
                ],
                "actions": ["telegram", "email"],
                "cooldown_minutes": 5
            }
        ]
        
        print("🔧 CUSTOM ALERT CONDITIONS:")
        for condition in custom_conditions:
            print(f"\n   📋 {condition['name']}")
            print(f"      Conditions: {len(condition['conditions'])} rules")
            print(f"      Actions: {', '.join(condition['actions'])}")
            print(f"      Cooldown: {condition['cooldown_minutes']} minutes")
            
            for rule in condition['conditions']:
                print(f"      - {rule['field']} {rule['operator']} {rule['value']}")
        
        print("✅ Custom alerts demo completed!")
    
    async def alert_history_demo(self):
        """Demonstrate alert history and management"""
        print("\n📋 Alert History Demo")
        print("=" * 50)
        
        # Sample alert history
        alert_history = [
            {
                "timestamp": datetime.now() - timedelta(minutes=5),
                "type": "whale_trade",
                "priority": "HIGH",
                "address": "0x010461C14e146ac35Fe42271BDC1134EE31C703a",
                "coin": "ETH",
                "value": 367500,
                "channels": ["telegram", "discord"],
                "status": "delivered"
            },
            {
                "timestamp": datetime.now() - timedelta(minutes=12),
                "type": "position_update",
                "priority": "MEDIUM",
                "address": "0x8eb8a3b98659cce290402893d0123abb75E3ab28",
                "coin": "BTC",
                "value": 1140000,
                "channels": ["telegram"],
                "status": "delivered"
            },
            {
                "timestamp": datetime.now() - timedelta(minutes=18),
                "type": "sentiment_change",
                "priority": "LOW",
                "address": None,
                "coin": "SOL",
                "value": None,
                "channels": ["dashboard"],
                "status": "delivered"
            }
        ]
        
        print("📊 ALERT HISTORY (Last 20 minutes):")
        print(f"{'Time':<12} {'Type':<16} {'Priority':<8} {'Target':<20} {'Status':<10}")
        print("-" * 75)
        
        for alert in alert_history:
            timestamp = alert["timestamp"].strftime("%H:%M:%S")
            alert_type = alert["type"].replace("_", " ").title()
            priority = alert["priority"]
            target = alert["coin"] if alert["coin"] else "Market"
            status = alert["status"]
            
            priority_icon = {"HIGH": "🔴", "MEDIUM": "🟡", "LOW": "🟢"}.get(priority, "⚪")
            status_icon = "✅" if status == "delivered" else "❌"
            
            print(f"{timestamp:<12} {alert_type:<16} {priority_icon}{priority:<7} {target:<20} {status_icon} {status}")
        
        # Alert statistics
        total_alerts = len(alert_history)
        successful_alerts = sum(1 for alert in alert_history if alert["status"] == "delivered")
        success_rate = (successful_alerts / total_alerts) * 100 if total_alerts > 0 else 0
        
        print(f"\n📈 ALERT STATISTICS:")
        print(f"   Total Alerts: {total_alerts}")
        print(f"   Successful: {successful_alerts}")
        print(f"   Success Rate: {success_rate:.1f}%")
        
        priority_breakdown = {}
        for alert in alert_history:
            priority = alert["priority"]
            priority_breakdown[priority] = priority_breakdown.get(priority, 0) + 1
        
        print(f"\n🎯 PRIORITY BREAKDOWN:")
        for priority, count in priority_breakdown.items():
            percentage = (count / total_alerts) * 100
            print(f"   {priority}: {count} ({percentage:.1f}%)")
        
        print("✅ Alert history demo completed!")
    
    async def alert_filters_demo(self):
        """Demonstrate alert filtering and management"""
        print("\n🔍 Alert Filters Demo")
        print("=" * 50)
        
        # Filter options
        filter_options = {
            "Time Range": ["Last Hour", "Last 24 Hours", "Last 7 Days", "Custom"],
            "Priority Levels": ["HIGH", "MEDIUM", "LOW"],
            "Alert Types": ["Whale Trade", "Position Update", "Sentiment Change", "System Alert"],
            "Channels": ["Telegram", "Discord", "Email", "Dashboard"],
            "Status": ["Delivered", "Failed", "Pending", "Filtered"]
        }
        
        print("🔍 AVAILABLE FILTERS:")
        for category, options in filter_options.items():
            print(f"\n   {category}:")
            for option in options:
                print(f"      • {option}")
        
        # Sample filtered results
        print(f"\n📊 FILTERED RESULTS:")
        print(f"   Time Range: Last 24 Hours")
        print(f"   Priority: HIGH")
        print(f"   Alert Type: Whale Trade")
        print(f"   Results: 8 alerts found")
        
        filtered_alerts = [
            {"time": "14:30:15", "coin": "ETH", "value": 367500, "channels": "Telegram, Discord"},
            {"time": "13:45:22", "coin": "BTC", "value": 1140000, "channels": "Telegram"},
            {"time": "12:15:08", "coin": "SOL", "value": 475000, "channels": "Discord"}
        ]
        
        print(f"\n   📋 FILTERED ALERTS:")
        for alert in filtered_alerts:
            print(f"      {alert['time']} | {alert['coin']} | ${alert['value']:,.0f} | {alert['channels']}")
        
        print("✅ Alert filters demo completed!")
    
    async def notification_settings_demo(self):
        """Demonstrate notification settings and preferences"""
        print("\n⚙️  Notification Settings Demo")
        print("=" * 50)
        
        # Global settings
        global_settings = {
            "quiet_hours": {
                "enabled": True,
                "start_time": "22:00",
                "end_time": "08:00",
                "timezone": "UTC"
            },
            "rate_limiting": {
                "max_alerts_per_hour": 10,
                "cooldown_seconds": 60,
                "burst_limit": 3
            },
            "delivery_options": {
                "retry_failed": True,
                "max_retries": 3,
                "timeout_seconds": 30
            }
        }
        
        print("🔧 GLOBAL NOTIFICATION SETTINGS:")
        print(f"\n   🌙 QUIET HOURS:")
        print(f"      Enabled: {global_settings['quiet_hours']['enabled']}")
        print(f"      Time: {global_settings['quiet_hours']['start_time']} - {global_settings['quiet_hours']['end_time']}")
        print(f"      Timezone: {global_settings['quiet_hours']['timezone']}")
        
        print(f"\n   ⚡ RATE LIMITING:")
        print(f"      Max Alerts/Hour: {global_settings['rate_limiting']['max_alerts_per_hour']}")
        print(f"      Cooldown: {global_settings['rate_limiting']['cooldown_seconds']}s")
        print(f"      Burst Limit: {global_settings['rate_limiting']['burst_limit']}")
        
        print(f"\n   📤 DELIVERY OPTIONS:")
        print(f"      Retry Failed: {global_settings['delivery_options']['retry_failed']}")
        print(f"      Max Retries: {global_settings['delivery_options']['max_retries']}")
        print(f"      Timeout: {global_settings['delivery_options']['timeout_seconds']}s")
        
        # User preferences
        user_preferences = {
            "priority_threshold": "MEDIUM",
            "favorite_coins": ["ETH", "BTC", "SOL"],
            "minimum_trade_value": 500000,
            "notification_methods": ["telegram", "discord"],
            "digest_frequency": "daily"
        }
        
        print(f"\n👤 USER PREFERENCES:")
        print(f"   Priority Threshold: {user_preferences['priority_threshold']}")
        print(f"   Favorite Coins: {', '.join(user_preferences['favorite_coins'])}")
        print(f"   Min Trade Value: ${user_preferences['minimum_trade_value']:,.2f}")
        print(f"   Methods: {', '.join(user_preferences['notification_methods'])}")
        print(f"   Digest: {user_preferences['digest_frequency']}")
        
        print("✅ Notification settings demo completed!")
    
    async def run_all_demos(self):
        """Run all notification demonstrations"""
        print("🎯 HYPERLIQUID MONITOR PLUS - NOTIFICATIONS MODULE EXAMPLES")
        print("=" * 70)
        
        await self.basic_alerts_demo()
        await self.telegram_notifications_demo()
        await self.discord_notifications_demo()
        await self.custom_alerts_demo()
        await self.alert_history_demo()
        await self.alert_filters_demo()
        await self.notification_settings_demo()
        
        print("\n" + "=" * 70)
        print("🎉 All notification demos completed successfully!")
        print("💡 Notification capabilities demonstrated:")
        print("   🚨 Multi-channel alert system")
        print("   📱 Telegram bot integration")
        print("   🎮 Discord webhook integration")
        print("   ⚙️  Custom alert rules")
        print("   📋 Alert history and filtering")
        print("   ⚙️  Advanced notification settings")


async def main():
    """Main demonstration function"""
    
    # Run notification demos
    notifications_demo = NotificationsDemo()
    await notifications_demo.run_all_demos()


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