#!/usr/bin/env python3
"""
Besu-Cacti Connector
Connects Hyperledger Besu to Hyperledger Cacti
"""

import os
import json
import logging
from typing import Dict, Any, Optional
from web3 import Web3
import requests

logger = logging.getLogger(__name__)

class BesuCactiConnector:
    """Connector for Besu-Cacti integration"""
    
    def __init__(self, besu_rpc_url: str, cactus_api_url: str):
        self.besu_rpc_url = besu_rpc_url
        self.cactus_api_url = cactus_api_url
        self.web3 = Web3(Web3.HTTPProvider(besu_rpc_url))
        self.cactus_session = requests.Session()
    
    def register_besu_ledger(self, ledger_id: str, chain_id: int) -> Dict[str, Any]:
        """Register Besu ledger with Cacti"""
        url = f"{self.cactus_api_url}/api/v1/plugins/ledger-connector/besu"
        data = {
            "ledgerId": ledger_id,
            "chainId": chain_id,
            "rpc": {
                "http": self.besu_rpc_url,
                "ws": self.besu_rpc_url.replace('http', 'ws').replace(':8545', ':8546')
            }
        }
        response = self.cactus_session.post(url, json=data)
        response.raise_for_status()
        return response.json()
    
    def deploy_contract(self, contract_abi: list, contract_bytecode: str, constructor_args: list = None) -> Dict[str, Any]:
        """Deploy contract via Cacti"""
        url = f"{self.cactus_api_url}/api/v1/plugins/ledger-connector/besu/deploy-contract"
        data = {
            "abi": contract_abi,
            "bytecode": contract_bytecode,
            "constructorArgs": constructor_args or [],
        }
        response = self.cactus_session.post(url, json=data)
        response.raise_for_status()
        return response.json()
    
    def invoke_contract(self, contract_address: str, contract_abi: list, method: str, args: list = None) -> Dict[str, Any]:
        """Invoke contract method via Cacti"""
        url = f"{self.cactus_api_url}/api/v1/plugins/ledger-connector/besu/invoke-contract"
        data = {
            "contractAddress": contract_address,
            "abi": contract_abi,
            "method": method,
            "args": args or [],
        }
        response = self.cactus_session.post(url, json=data)
        response.raise_for_status()
        return response.json()
    
    def get_ledger_status(self, ledger_id: str) -> Dict[str, Any]:
        """Get ledger status from Cacti"""
        url = f"{self.cactus_api_url}/api/v1/plugins/ledger-connector/besu/status"
        params = {"ledgerId": ledger_id}
        response = self.cactus_session.get(url, params=params)
        response.raise_for_status()
        return response.json()

