"""
Wallet verification and management for secure mining
"""
import json
import os
from typing import Optional, Dict, Any
import hashlib
from bitcoinlib.keys import Key

class WalletVerifier:
    def __init__(self, wallet_address: str = None, wallet_path: str = "my_wallet.json"):
        self.wallet_path = wallet_path
        self.wallet_data = None
        self.custom_address = wallet_address
        
        # Load existing wallet or create new one
        if os.path.exists(wallet_path):
            self.load_wallet()
        else:
            # Initialize new wallet
            self.wallet_data = {
                'address': wallet_address or "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh",
                'total_mined': 0,
                'mining_stats': {
                    'total_blocks_mined': 0,
                    'last_reward': None
                }
            }
            # Save the new wallet
            self.save_wallet()
    
    def load_wallet(self) -> None:
        """Load wallet data from file and initialize if needed"""
        try:
            if os.path.exists(self.wallet_path):
                with open(self.wallet_path, 'r') as f:
                    self.wallet_data = json.load(f)
                    
                # Initialize mining stats if not present
                if 'total_mined' not in self.wallet_data:
                    self.wallet_data['total_mined'] = 0
                if 'mining_stats' not in self.wallet_data:
                    self.wallet_data['mining_stats'] = {
                        'total_blocks_mined': 0,
                        'last_reward': None
                    }
                    
                # Save initialized data
                with open(self.wallet_path, 'w') as f:
                    json.dump(self.wallet_data, f, indent=4)
            else:
                # Create new wallet file with default values
                self.wallet_data = {
                    'address': 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh',  # Default test address
                    'total_mined': 0,
                    'mining_stats': {
                        'total_blocks_mined': 0,
                        'last_reward': None
                    }
                }
                with open(self.wallet_path, 'w') as f:
                    json.dump(self.wallet_data, f, indent=4)
        except Exception as e:
            print(f"Error loading wallet: {e}")
            # Use default values if file access fails
            self.wallet_data = {
                'address': 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh',
                'total_mined': 0,
                'mining_stats': {
                    'total_blocks_mined': 0,
                    'last_reward': None
                }
            }
        """Load wallet data from file"""
        try:
            if os.path.exists(self.wallet_path):
                with open(self.wallet_path, 'r') as f:
                    self.wallet_data = json.load(f)
            else:
                # If no wallet file, create with default address
                self.wallet_data = {
                    'address': '1LE9bpK6nkYScjNmnnGugYfSY4YPt4ZUoq',  # Default address
                    'total_mined': 0,
                    'mining_stats': {
                        'total_blocks_mined': 0,
                        'last_reward': None
                    }
                }
                
        except Exception as e:
            raise Exception(f"Failed to load wallet: {str(e)}")
    
    def _verify_wallet_integrity(self) -> bool:
        """Verify wallet data integrity and key pairs"""
        required_fields = ['private_key', 'public_key', 'address', 'wif_private_key']
        
        # Check required fields
        if not all(field in self.wallet_data for field in required_fields):
            return False
            
        try:
            # Verify key pair relationship
            key = Key(self.wallet_data['private_key'])
            if key.public_hex != self.wallet_data['public_key']:
                return False
                
            # Verify address derivation
            if key.address != self.wallet_data['address']:
                return False
                
            return True
            
        except Exception:
            return False
    
    def get_mining_address(self) -> str:
        """Get verified mining address"""
        if not self.wallet_data:
            raise Exception("Wallet not loaded")
        return self.wallet_data['address']
    
    def verify_mining_address(self, address: str) -> bool:
        """Verify if an address matches our wallet"""
        if not self.wallet_data:
            raise Exception("Wallet not loaded")
        return address == self.wallet_data['address']
    
    def save_wallet(self) -> None:
        """Save wallet data to file"""
        with open(self.wallet_path, 'w') as f:
            json.dump(self.wallet_data, f, indent=4)
            
    def get_wallet_info(self) -> Dict[str, Any]:
        """Get wallet information for mining"""
        if not self.wallet_data:
            raise Exception("Wallet not loaded")
        # Initialize required fields if they don't exist
        if 'total_mined' not in self.wallet_data:
            self.wallet_data['total_mined'] = 0
        if 'balance' not in self.wallet_data:
            self.wallet_data['balance'] = 0
        return {
            'address': self.wallet_data['address'],
            'total_mined': self.wallet_data['total_mined'],
            'balance': self.wallet_data.get('balance', 0),
            'mining_stats': self.wallet_data['mining_stats']
        }