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

"""
RISC-V Program Deployment Example

This example demonstrates how to deploy RISC-V programs to the Rialo blockchain:
- Deploying RISC-V programs using the RISC-V Loader
- Comparing RISC-V vs EBPF (LoaderV4) deployment
- Using the LoaderType.RiscV option
"""

from rialo_py_cdk import (
    generate_keypair,
    Wallet,
    HttpRpcClient,
    ProgramDeployment,
    LoaderType,
    get_localnet_url,
    RialoException,
)
import os


def riscv_deployment_example():
    """Demonstrate RISC-V program deployment capabilities."""
    print('🚀 Starting Rialo CDK RISC-V Program Deployment Example\n')

    try:
        # 1. Create a wallet for program deployment
        print('1. Creating deployment wallet...')
        keypair = generate_keypair()
        wallet = Wallet('deployer-wallet', keypair, None, None)
        print(f'   Deployer public key: {wallet.get_public_key_string()}')

        # 2. Create RPC client
        print('2. Creating RPC client...')
        client = HttpRpcClient(get_localnet_url())
        print(f'   Connected to: {get_localnet_url()}')

        # 3. Deploy RISC-V program
        print('3. Deploying RISC-V program...')

        # Example RISC-V program path (adjust to your actual program)
        riscv_program_path = "programs/rialo-risc-v-loader-program/test-programs/out/log.elf"

        if os.path.exists(riscv_program_path):
            try:
                # Create deployment and specify RISC-V loader
                deployment = ProgramDeployment(riscv_program_path)
                deployment.with_loader_type(LoaderType.RiscV)

                # Deploy the program
                program_id = deployment.deploy(client, wallet)
                print(f'   ✅ RISC-V program deployed successfully!')
                print(f'   Program ID: {program_id}')
                print(f'   Program is owned by: RiscVLoader11111111111111111111111111111111')

            except RialoException as e:
                print(f'   ⚠️ RISC-V program deployment failed: {e}')
                print('   (This is likely due to insufficient funds or network not running)')
        else:
            print(f'   ⚠️ RISC-V program not found at: {riscv_program_path}')
            print('   Skipping deployment demo...')

        # 4. Compare with EBPF deployment
        print('\n4. Comparison: RISC-V vs EBPF (LoaderV4) deployment')
        print('   RISC-V programs (.elf):')
        print('     - Use LoaderType.RiscV')
        print('     - Owned by: RiscVLoader11111111111111111111111111111111')
        print('     - Executed by RISC-V VM')
        print('   ')
        print('   EBPF programs (.so):')
        print('     - Use LoaderType.LoaderV4 (default)')
        print('     - Owned by: LoaderV411111111111111111111111111111111111')
        print('     - Executed by EBPF VM')

        # 5. Show deployment patterns
        print('\n5. RISC-V Deployment Patterns:')
        print('   ')
        print('   # Basic RISC-V deployment:')
        print('   deployment = ProgramDeployment("program.elf")')
        print('   deployment.with_loader_type(LoaderType.RiscV)')
        print('   program_id = deployment.deploy(client, wallet)')
        print('   ')
        print('   # EBPF deployment (default - no loader type needed):')
        print('   deployment = ProgramDeployment("program.so")')
        print('   program_id = deployment.deploy(client, wallet)')
        print('   ')
        print('   # Or explicitly specify LoaderV4:')
        print('   deployment = ProgramDeployment("program.so")')
        print('   deployment.with_loader_type(LoaderType.LoaderV4)')
        print('   program_id = deployment.deploy(client, wallet)')

        print('\n✅ RISC-V program deployment demo completed!')
        print('\n📋 Key Takeaways:')
        print('   • RISC-V programs use .elf extension')
        print('   • Set LoaderType.RiscV when deploying RISC-V programs')
        print('   • RISC-V and EBPF programs can coexist on the same chain')
        print('   • Deployment process is identical, only loader type differs')

    except Exception as error:
        print(f'❌ Error during RISC-V deployment demo: {error}')
        raise error


def main():
    """Run the RISC-V deployment example."""
    try:
        riscv_deployment_example()
        print('\n🎉 RISC-V deployment example finished!')
    except Exception as error:
        print(f'\n💥 Example failed: {error}')
        import traceback
        traceback.print_exc()
        exit(1)


if __name__ == "__main__":
    main()
