"""
Enhanced Mining Server with Virtual GPU Support and Bitcoin Reward Processing
"""
from aiohttp import web
import asyncio
from typing import Dict, Any
import logging
from ..mining.enhanced_bitcoin_miner import EnhancedBitcoinMiner
from ..core.wallet import BTCWallet
from ..mining.reward_processor import BitcoinRewardProcessor

class EnhancedMiningServer:
    def __init__(self, wallet: BTCWallet, host: str = "localhost", port: int = 8080):
        self.logger = logging.getLogger(__name__)
        self.host = host
        self.port = port
        self.app = web.Application()
        
        # Initialize components
        self.wallet = wallet
        self.miner = EnhancedBitcoinMiner(
            wallet_address=wallet.address,
            network=wallet.network
        )
        self.reward_processor = BitcoinRewardProcessor(network=wallet.network)
        
        # Track mining rewards
        self.total_rewards = 0
        self.pending_rewards = 0
        
        # Setup routes
        self.setup_routes()
        
    def setup_routes(self):
        """Configure server endpoints"""
        self.app.router.add_get("/status", self.get_status)
        self.app.router.add_get("/stats", self.get_stats)
        self.app.router.add_get("/wallet", self.get_wallet)
        
    async def get_status(self, request: web.Request) -> web.Response:
        """Get mining system status"""
        try:
            status = {
                'mining': self.miner.mining,
                'uptime': self.miner.get_mining_stats()['uptime'],
                'wallet_balance': await self.wallet.get_balance(),
                'pending_rewards': self.reward_processor.get_reward_stats(self.wallet.address)['pending'],
                'confirmed_rewards': self.reward_processor.get_reward_stats(self.wallet.address)['confirmed'],
                'mature_rewards': self.reward_processor.get_reward_stats(self.wallet.address)['mature']
            }
            return web.json_response(status)
        except Exception as e:
            return web.json_response({'error': str(e)}, status=500)
            
    async def get_stats(self, request: web.Request) -> web.Response:
        """Get detailed mining statistics"""
        try:
            stats = self.miner.get_mining_stats()
            return web.json_response(stats)
        except Exception as e:
            return web.json_response({'error': str(e)}, status=500)
            
    async def get_wallet(self, request: web.Request) -> web.Response:
        """Get wallet information"""
        try:
            wallet_info = {
                'address': self.wallet.address,
                'balance': await self.wallet.get_balance(),
                'network': self.wallet.network,
                'reward_stats': self.reward_processor.get_reward_stats(self.wallet.address),
                'reward_history': self.reward_processor.get_reward_history(self.wallet.address),
                'estimated_earnings': self.reward_processor.estimate_earnings(
                    address=self.wallet.address,
                    hashrate=self.miner.get_mining_stats()['hash_rate']
                )
            }
            return web.json_response(wallet_info)
        except Exception as e:
            return web.json_response({'error': str(e)}, status=500)
            
    async def start(self):
        """Start the mining server"""
        self.miner.start_mining()
        await web._run_app(self.app, host=self.host, port=self.port)
        
    async def stop(self):
        """Stop the mining server"""
        self.miner.stop_mining()
