"""
Real-time Bitcoin network statistics collector
"""
import requests
import json
from typing import Dict, Any, Optional

class NetworkStatsCollector:
    def __init__(self):
        self.api_endpoints = {
            'blockchain': 'https://blockchain.info/stats?format=json',
            'mempool': 'https://mempool.space/api/v1/statistics/2h',
            'blockchair': 'https://api.blockchair.com/bitcoin/stats'
        }
        
    def get_network_stats(self) -> Dict[str, Any]:
        """Get comprehensive network statistics from multiple sources"""
        stats = {
            'hashrate': 0,
            'difficulty': 0,
            'block_time': 0,
            'mempool_size': 0,
            'next_difficulty_estimate': 0
        }
        
        # Try multiple APIs with fallbacks
        for api_name, endpoint in self.api_endpoints.items():
            try:
                response = requests.get(endpoint, timeout=5)
                data = response.json()
                
                if api_name == 'blockchain':
                    stats['hashrate'] = data.get('hash_rate', 0)
                    stats['difficulty'] = data.get('difficulty', 0)
                    stats['block_time'] = data.get('minutes_between_blocks', 10) * 60
                elif api_name == 'mempool':
                    stats['mempool_size'] = data.get('mempool_size', 0)
                    if 'difficulty_adjustment' in data:
                        stats['next_difficulty_estimate'] = data['difficulty_adjustment'].get('estimated_difficulty', 0)
                elif api_name == 'blockchair':
                    if not stats['hashrate']:
                        stats['hashrate'] = data.get('data', {}).get('hashrate_24h', 0)
                    if not stats['difficulty']:
                        stats['difficulty'] = data.get('data', {}).get('difficulty', 0)
                        
            except Exception as e:
                print(f"Warning: Failed to fetch stats from {api_name}: {e}")
                continue
                
        return stats
        
    def estimate_next_difficulty(self, current_stats: Dict[str, Any]) -> float:
        """Estimate next difficulty adjustment based on current stats"""
        if current_stats['block_time'] <= 0:
            return current_stats['difficulty']
            
        # Bitcoin adjusts difficulty every 2016 blocks to target 10-minute block time
        adjustment_factor = 600 / current_stats['block_time']  # 600 seconds = 10 minutes
        return current_stats['difficulty'] * adjustment_factor