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

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

logger = logging.getLogger(__name__)

class BesuFireflyConnector:
    """Connector for Besu-Firefly integration"""
    
    def __init__(self, besu_rpc_url: str, firefly_api_url: str, firefly_api_key: str):
        self.besu_rpc_url = besu_rpc_url
        self.firefly_api_url = firefly_api_url
        self.firefly_api_key = firefly_api_key
        self.web3 = Web3(Web3.HTTPProvider(besu_rpc_url))
        self.firefly_session = requests.Session()
        if firefly_api_key:
            self.firefly_session.headers.update({'X-API-Key': firefly_api_key})
    
    def register_besu_network(self, network_name: str, chain_id: int) -> Dict[str, Any]:
        """Register Besu network with Firefly"""
        url = f"{self.firefly_api_url}/api/v1/networks"
        data = {
            "name": network_name,
            "type": "ethereum",
            "chainId": chain_id,
            "rpc": {
                "http": self.besu_rpc_url,
                "ws": self.besu_rpc_url.replace('http', 'ws').replace(':8545', ':8546')
            }
        }
        response = self.firefly_session.post(url, json=data)
        response.raise_for_status()
        return response.json()
    
    def deploy_erc20_contract(self, name: str, symbol: str, initial_supply: int) -> Dict[str, Any]:
        """Deploy ERC20 contract via Firefly"""
        url = f"{self.firefly_api_url}/api/v1/contracts/instances"
        data = {
            "name": name,
            "symbol": symbol,
            "initialSupply": str(initial_supply),
            "connector": "besu"
        }
        response = self.firefly_session.post(url, json=data)
        response.raise_for_status()
        return response.json()
    
    def get_firefly_status(self) -> Dict[str, Any]:
        """Get Firefly status"""
        url = f"{self.firefly_api_url}/api/v1/status"
        response = self.firefly_session.get(url)
        response.raise_for_status()
        return response.json()
    
    def get_besu_status(self) -> Dict[str, Any]:
        """Get Besu status"""
        try:
            chain_id = self.web3.eth.chain_id
            block_number = self.web3.eth.block_number
            return {
                "connected": True,
                "chainId": chain_id,
                "blockNumber": block_number,
            }
        except Exception as e:
            logger.error(f"Failed to connect to Besu: {e}")
            return {
                "connected": False,
                "error": str(e),
            }

