"""
Quick Bitcoin Transfer Script
Makes real Bitcoin transfers using the simplified wallet system
"""
from decimal import Decimal, InvalidOperation
from coin_miner.src.core.wallet import load_or_create_wallet

def main():
    # Load or create wallet (will use my_wallet.json by default)
    wallet = load_or_create_wallet()
    
    # Show wallet info
    balance = wallet.get_balance()
    total_mined = Decimal(str(wallet.wallet_data.get('total_mined', 0)))
    
    print("\nWallet Info:")
    print(f"Your address: {wallet.keys.address}")
    print(f"Current balance: {balance} BTC")
    print(f"Total mined: {total_mined} BTC")
    
    # Destination wallet (your bc1 address)
    to_address = "bc1qkzx66he32evxktdhauj7cmfs50p6x909m8l5ru"
    
    # Get amount to transfer
    try:
        amount_str = input("\nEnter amount to transfer in BTC: ")
        # Replace any commas with dots and remove spaces
        amount_str = amount_str.replace(',', '.').strip()
        amount = Decimal(amount_str)
        
        if amount <= 0:
            print("Error: Amount must be greater than 0")
            return
            
        # Check if we have enough BTC
        if amount > balance:
            print("Error: Insufficient funds")
            return
            
    except InvalidOperation:
        print("Error: Please enter a valid number")
        return

    # Get fee estimates - use fallback values if estimation fails
    try:
        fees = wallet.estimate_transfer_fees()
    except Exception as e:
        print(f"Warning: Could not estimate network fees, using fallback values")
        fees = {'high': 5000, 'medium': 2000, 'low': 1000}
    
    print("\nEstimated fees (in satoshis):")
    print(f"High priority: {fees['high']}")
    print(f"Medium priority: {fees['medium']}")
    print(f"Low priority: {fees['low']}")
    
    priority = input("\nChoose fee priority (high/medium/low): ").lower()
    while priority not in ['high', 'medium', 'low']:
        print("Invalid priority. Please choose 'high', 'medium', or 'low'")
        priority = input("Choose fee priority (high/medium/low): ").lower()
        
    fee_rate = fees[priority]  # Use direct dictionary access since we validated the input
    
    # Confirm transaction
    total = amount + Decimal(fee_rate) / Decimal('100000000')  # Convert fee to BTC
    print(f"\nTotal cost: {amount} BTC + {fee_rate} satoshis fee = {total} BTC")
    if input("Proceed with transaction? (yes/no): ").lower() != 'yes':
        print("Transaction cancelled")
        return
    
    # Make the real Bitcoin transfer
    try:
        txid = wallet.send_bitcoin(
            to_address=to_address,
            amount=amount,
            fee_rate=fee_rate
        )
        
        if txid:
            print(f"\nSuccess! Transaction ID: {txid}")
            print("You can track your transaction on blockchain explorers")
        else:
            print("Error: Transaction failed to broadcast")
            
    except Exception as e:
        print(f"Error sending Bitcoin: {str(e)}")
        return
    
    if txid:
        print(f"\nTransaction broadcast successfully!")
        print(f"Transaction ID: {txid}")
        print(f"\nTrack your transaction:")
        print(f"• Blockchain.com: https://www.blockchain.com/btc/tx/{txid}")
        print(f"• Blockchair: https://blockchair.com/bitcoin/transaction/{txid}")
        print(f"• BitcoinExplorer: https://bitcoinexplorer.org/tx/{txid}")
        
        # Get initial transaction details
        details = wallet.get_transaction_details(txid)
        if details:
            print(f"\nInitial Transaction Details:")
            print(f"Status: {details.status}")
            print(f"Amount: {details.amount} BTC")
            if details.fee > 0:
                print(f"Network Fee: {details.fee} BTC")
            print(f"Confirmations: {details.confirmations}")
            
            if details.status == 'pending':
                print("\nNote: Transaction is pending confirmation.")
                print("It may take 10-60 minutes to be confirmed depending on network traffic.")
        print(f"https://www.blockchain.com/btc/tx/{txid}")
        
        # Get transaction details
        details = wallet.get_transaction_details(txid)
        if details:
            print(f"\nTransaction Status: {details.status}")
            print(f"Confirmations: {details.confirmations}")
    else:
        print("\nError: Transaction failed")
if __name__ == '__main__':
    main()
