#!/usr/bin/env python3
# Copyright (c) Subzero Labs, Inc.
# SPDX-License-Identifier: Apache-2.0

"""
Wallet management example demonstrating wallet operations
"""

from rialo_py_cdk import (
    generate_keypair,
    generate_mnemonic,
    keypair_from_mnemonic,
    Wallet,
    InMemoryWalletProvider,
    create_wallet_with_mnemonic,
    recover_wallet_from_mnemonic,
)


def wallet_management_example():
    """Run wallet management example demonstrating wallet operations."""
    print('🔐 Starting Rialo CDK Wallet Management Example\n')

    try:
        # 1. Create an in-memory wallet provider
        print('1. Creating wallet provider...')
        provider = InMemoryWalletProvider()
        print('   Wallet provider created')

        # 2. Create a simple wallet
        print('2. Creating simple wallet...')
        wallet1 = provider.create('simple-wallet', 'password123')
        print(f'   Created wallet: {wallet1.name}')
        print(f'   Wallet address: {wallet1.get_public_key_string()}')

        # 3. Generate and use a mnemonic (if mnemonic feature is enabled)
        try:
            print('3. Working with mnemonic phrases...')
            mnemonic = generate_mnemonic()
            print(f'   Generated mnemonic: {mnemonic[:50]}...')

            # Create keypair from mnemonic
            keypair_from_mnem = keypair_from_mnemonic(mnemonic)
            print(f'   Keypair from mnemonic: {len(keypair_from_mnem)} bytes')

            # Create wallet from mnemonic
            mnemonic_wallet = Wallet(
                'mnemonic-wallet',
                keypair_from_mnem,
                mnemonic,
                "m/44'/501'/0'/0'"
            )
            print(f'   Mnemonic wallet address: {mnemonic_wallet.get_public_key_string()}')
            
            # Create wallet through convenience function with mnemonic
            wallet2, wallet2_mnemonic = create_wallet_with_mnemonic('recoverable-wallet')
            print(f'   Recoverable wallet: {wallet2.name}')
            print(f'   Has mnemonic: {wallet2.get_mnemonic() is not None}')
            print(f'   Mnemonic preview: {wallet2_mnemonic[:50]}...')

        except Exception as error:
            print(f'   Mnemonic feature error: {error}')

        # 4. List wallets
        print('4. Listing wallets...')
        wallet_names = provider.list()
        print(f'   Found {len(wallet_names)} wallets: {", ".join(wallet_names)}')

        # 5. Check wallet existence
        print('5. Checking wallet existence...')
        exists = provider.exists('simple-wallet')
        print(f'   \'simple-wallet\' exists: {exists}')

        not_exists = provider.exists('nonexistent-wallet')
        print(f'   \'nonexistent-wallet\' exists: {not_exists}')

        # 6. Load existing wallet
        print('6. Loading existing wallet...')
        loaded_wallet = provider.load('simple-wallet', 'password123')
        print(f'   Loaded wallet: {loaded_wallet.name}')
        print(f'   Addresses match: {loaded_wallet.get_public_key_string() == wallet1.get_public_key_string()}')

        # 7. Get public key without loading full wallet
        print('7. Getting public key without password...')
        public_key = provider.get_public_key('simple-wallet')
        print(f'   Public key: {public_key}')

        # 8. Account operations
        print('8. Testing account operations...')
        print(f'   Wallet name: {wallet1.name}')
        print(f'   Wallet public key: {wallet1.get_public_key_string()}')

        # Sign a message with the wallet
        message = b'Test message for signing'
        signature = wallet1.sign(message)
        print(f'   Signed message, signature length: {len(signature)}')

        # 9. Get all accounts for the wallet
        print('9. Testing wallet account information...')
        accounts = wallet1.get_accounts()
        print(f'   Account public keys: {accounts}')
        
        account_indices = wallet1.list_accounts()
        print(f'   Account indices: {account_indices}')

        # 10. Test mnemonic recovery
        try:
            print('10. Testing mnemonic recovery...')
            test_mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
            recovered_wallet1 = recover_wallet_from_mnemonic('test-recovery-1', test_mnemonic)
            recovered_wallet2 = recover_wallet_from_mnemonic('test-recovery-2', test_mnemonic)
            
            print(f'    Recovered wallet 1: {recovered_wallet1.get_public_key_string()}')
            print(f'    Recovered wallet 2: {recovered_wallet2.get_public_key_string()}')
            print(f'    Recovery consistent: {recovered_wallet1.get_public_key_string() == recovered_wallet2.get_public_key_string()}')
            
        except Exception as error:
            print(f'    Mnemonic recovery error: {error}')

        print('\n✅ Wallet management operations completed successfully!')

    except Exception as error:
        print(f'❌ Error during wallet management: {error}')
        raise error


def main():
    """Run the wallet management example."""
    try:
        wallet_management_example()
        print('🎉 Wallet management example finished!')
    except Exception as error:
        print(f'💥 Wallet management example failed: {error}')
        import traceback
        traceback.print_exc()
        exit(1)


if __name__ == "__main__":
    main()