"""
Import external wallet and add mining rewards
"""
import sqlite3
import json
import time
from datetime import datetime
import re

def is_valid_btc_address(address: str) -> bool:
    """Basic validation of Bitcoin address format"""
    # Check for legacy address (1...)
    legacy_pattern = re.compile('^[1][a-km-zA-HJ-NP-Z1-9]{25,34}$')
    # Check for SegWit address (3...)
    segwit_pattern = re.compile('^[3][a-km-zA-HJ-NP-Z1-9]{25,34}$')
    # Check for Native SegWit address (bc1...)
    bech32_pattern = re.compile('^bc1[a-zA-HJ-NP-Z0-9]{25,39}$')
    
    return bool(
        legacy_pattern.match(address) or 
        segwit_pattern.match(address) or 
        bech32_pattern.match(address)
    )

def init_database():
    """Initialize the database and create tables if they don't exist"""
    try:
        conn = sqlite3.connect('wallet_data.db')
        cursor = conn.cursor()
        
        # Create wallets table if it doesn't exist
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS wallets (
                address TEXT PRIMARY KEY,
                balance REAL DEFAULT 0.0,
                total_mined REAL DEFAULT 0.0,
                metadata TEXT
            )
        """)
        
        conn.commit()
        print("Database initialized successfully")
        return True
    except sqlite3.Error as e:
        print(f"Database initialization error: {str(e)}")
        return False
    finally:
        if conn:
            conn.close()

def import_wallet(address: str, initial_balance: float = 0.0):
    """Import external wallet into our database"""
    try:
        # Initialize database first
        if not init_database():
            print("Failed to initialize database!")
            return False
            
        # Validate the Bitcoin address
        if not is_valid_btc_address(address):
            print(f"Invalid Bitcoin address format: {address}")
            return False

        conn = sqlite3.connect('wallet_data.db')
        cursor = conn.cursor()
        
        # Check if wallet already exists
        cursor.execute("SELECT * FROM wallets WHERE address = ?", (address,))
        if cursor.fetchone():
            print(f"Wallet {address} already exists in database!")
            return False
        
        # Add the wallet with initial data
        metadata = {
            'imported': True,
            'import_date': time.time(),
            'last_mining_session': None,
            'total_blocks_mined': 0
        }
        
        cursor.execute("""
            INSERT INTO wallets (address, balance, total_mined, metadata)
            VALUES (?, ?, ?, ?)
        """, (address, initial_balance, 0.0, json.dumps(metadata)))
        
        conn.commit()
        print(f"\nSuccessfully imported wallet: {address}")
        print(f"Initial balance: {initial_balance} BTC")
        return True
        
    except sqlite3.Error as e:
        print(f"Database error: {str(e)}")
        return False
    finally:
        if conn:
            conn.close()

def add_mining_rewards(address: str, rewards_data: dict):
    """Add mining rewards to an imported wallet"""
    try:
        conn = sqlite3.connect('wallet_data.db')
        cursor = conn.cursor()
        
        # Get current wallet data
        cursor.execute("SELECT balance, total_mined, metadata FROM wallets WHERE address = ?", (address,))
        result = cursor.fetchone()
        
        if not result:
            print(f"Wallet {address} not found!")
            return False
            
        current_balance, total_mined, metadata_str = result
        metadata = json.loads(metadata_str)
        
        # Update the values
        new_balance = float(current_balance) + rewards_data['amount']
        new_total_mined = float(total_mined) + rewards_data['amount']
        
        # Update metadata
        metadata.update({
            'last_mining_session': time.time(),
            'last_reward': rewards_data['amount'],
            'last_hash_rate': rewards_data.get('hash_rate', 0),
            'total_blocks_mined': metadata.get('total_blocks_mined', 0) + 1
        })
        
        # Save changes
        cursor.execute("""
            UPDATE wallets 
            SET balance = ?, 
                total_mined = ?,
                metadata = ?
            WHERE address = ?
        """, (new_balance, new_total_mined, json.dumps(metadata), address))
        
        conn.commit()
        print(f"\nSuccessfully added mining rewards to wallet: {address}")
        print(f"Added amount: {rewards_data['amount']} BTC")
        print(f"New balance: {new_balance} BTC")
        print(f"Total mined: {new_total_mined} BTC")
        return True
        
    except sqlite3.Error as e:
        print(f"Database error: {str(e)}")
        return False
    finally:
        if conn:
            conn.close()

def view_wallet(address: str):
    """View wallet details"""
    try:
        conn = sqlite3.connect('wallet_data.db')
        cursor = conn.cursor()
        
        cursor.execute("SELECT * FROM wallets WHERE address = ?", (address,))
        wallet = cursor.fetchone()
        
        if not wallet:
            print(f"Wallet {address} not found!")
            return
            
        print("\n=== Wallet Details ===")
        print(f"Address: {wallet[0]}")
        print(f"Balance: {wallet[1]} BTC")
        print(f"Total Mined: {wallet[2]} BTC")
        
        metadata = json.loads(wallet[3])
        print("\nMetadata:")
        for key, value in metadata.items():
            if 'time' in key or 'date' in key:
                value = datetime.fromtimestamp(value).strftime('%Y-%m-%d %H:%M:%S')
            print(f"  {key}: {value}")
            
    except sqlite3.Error as e:
        print(f"Database error: {str(e)}")
    finally:
        if conn:
            conn.close()

def main():
    while True:
        print("\nWallet Import and Mining Rewards Tool")
        print("1. Import external wallet")
        print("2. Add mining rewards to wallet")
        print("3. View wallet details")
        print("4. Exit")
        
        choice = input("\nEnter your choice (1-4): ")
        
        if choice == '1':
            address = input("Enter Bitcoin wallet address: ")
            balance = float(input("Enter initial balance (0 if none): "))
            import_wallet(address, balance)
            
        elif choice == '2':
            address = input("Enter wallet address: ")
            amount = float(input("Enter mining reward amount: "))
            hash_rate = float(input("Enter hash rate (MH/s): "))
            
            rewards_data = {
                'amount': amount,
                'hash_rate': hash_rate * 1_000_000,  # Convert to H/s
                'timestamp': time.time()
            }
            add_mining_rewards(address, rewards_data)
            
        elif choice == '3':
            address = input("Enter wallet address: ")
            view_wallet(address)
            
        elif choice == '4':
            print("\nExiting...")
            break
            
        else:
            print("\nInvalid choice. Please try again.")

if __name__ == '__main__':
    main()
