        elif command == "test-resilience":
            # Test resilience to chain failures
            print("Testing resilience to chain failures...")
            from hdgl_resilience import StateCache, CommitmentQueue
            
            # Test state caching
            cache = StateCache()
            vm = HDGLVM()
            state = vm.state
            
            from hdgl_resilience import StateCheckpoint
            checkpoint = StateCheckpoint(
                state=state,
                commitment=state.commitment_hash(),
                timestamp=time.time(),
                evolution_count=0,
                source='test'
            )
            
            cache.save_checkpoint(checkpoint)
            loaded = cache.load_checkpoint()
            
            print(f"  ✓ State cache working")
            print(f"    Saved and loaded checkpoint successfully")
            
            # Test commitment queue
            queue = CommitmentQueue()
            test_commitment = bytes.fromhex('a' * 64)
            queue.enqueue(test_commitment, 1)
            queue.enqueue(test_commitment, 2)
            
            size = queue.size()
            print(f"  ✓ Commitment queue working")
            print(f"    Queued {size} commitments")
            
            batch = queue.dequeue_batch(1)
            print(f"    Dequeued {len(batch)} commitments")
            
            print("\n  Resilience system operational!")
            return
        
        elif command == "status-detailed":
            # Show detailed status including resilience
            config = Config()
            bridge = HDGLBridge(config)
            
            print("HDGL Bridge Detailed Status")
            print("=" * 50)
            
            status = bridge.bridge.get_resilience_status()
            
            print("\nMode:")
            print(f"  Offline: {status['offline_mode']}")
            
            print("\nChain Health:")
            for chain, health in status['chain_health'].items():
                status_str = "HEALTHY" if health['healthy'] else "UNHEALTHY"
                print(f"  {chain.capitalize():10} {status_str:10} "
                      f"(failures: {health['failures']}, "
                      f"last success: {health['time_since_success']:.0f}s ago)")
            
            print("\nCache:")
            print(f"  Checkpoints: {status['cached_checkpoints']}")
            print(f"  Last Solana sync: {status['time_since_solana_sync']:.0f}s ago")
            print(f"  Last Ethereum sync: {status['time_since_ethereum_sync']:.0f}s ago")
            
            print("\nQueued Operations:")
            print(f"  Pending commitments: {status['queued_commitments']}")
            
            # Show recent checkpoint history
            history = bridge.bridge.cache.get_history(5)
            if history:
                print("\nRecent Checkpoints:")
                for entry in history[-5:]:
                    print(f"  Evolution #{entry['evolution_count']:4} - "
                          f"{entry['source']:8} - "
                          f"{entry['commitment'][:16]}... - "
                          f"D1={entry['dimensions'][0]:.4f}")
            
            return
        
        elif command == "force-resync":
            # Force resynchronization
            print("Forcing resynchronization...")
            config = Config()
            bridge = HDGLBridge(config)
            bridge.bridge.force_resync()
            print("✓ Resync complete")
            return#!/usr/bin/env python3
"""
HDGL Unified Multi-Chain Bridge
Simplified, elegant, reliable architecture using the HDGL VM

Design: Everything flows through the numeric field
- Solana stores raw HDGL state (8 dimensions)
- VM executes evolution programs
- Ethereum verifies commitment hashes
- Bitcoin references commitments for CHG bridging
"""

import json
import time
import logging
from decimal import Decimal
from typing import Optional, Dict
from hdgl_vm_unified import HDGLVM, HDGLState, HDGLField
from hdgl_resilience import ResilientBridge, RecoveryStrategies
from web3 import Web3
from solana.rpc.api import Client as SolanaClient
from solana.publickey import PublicKey

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
logger = logging.getLogger(__name__)

# ============================================
# Configuration (Simple JSON file)
# ============================================

class Config:
    def __init__(self, config_path: str = "config.json"):
        with open(config_path) as f:
            cfg = json.load(f)
        
        # Network endpoints
        self.solana_rpc = cfg["solana_rpc"]
        self.eth_rpc = cfg["eth_rpc"]
        self.eth_contract = cfg["eth_contract"]
        self.eth_key = cfg["eth_private_key"]
        
        # State accounts
        self.solana_state = cfg["solana_state_account"]
        
        # Evolution parameters
        self.poll_interval = cfg.get("poll_interval", 30)
        self.auto_evolve = cfg.get("auto_evolve", True)

# ============================================
# Chain Adapters (Thin wrappers)
# ============================================

class SolanaAdapter:
    """Read/Write HDGL state to Solana"""
    
    def __init__(self, rpc_url: str, state_account: str):
        self.client = SolanaClient(rpc_url)
        self.state_pubkey = PublicKey(state_account)
    
    def read_state(self) -> Optional[HDGLState]:
        """Read 8 dimensions + memory from Solana account"""
        try:
            resp = self.client.get_account_info(self.state_pubkey)
            if not resp['result']['value']:
                return None
            
            data = resp['result']['value']['data'][0]
            # Parse 8 x u64 dimensions (8 bytes each)
            import struct
            dims_raw = struct.unpack("<8Q", data[:64])
            
            # Convert to Decimal with scaling (stored as u64 * 10^9)
            state = HDGLState()
            state.dimensions = [Decimal(d) / Decimal(10**9) for d in dims_raw]
            
            return state
        except Exception as e:
            logger.error(f"Failed to read Solana state: {e}")
            return None
    
    def write_state(self, state: HDGLState) -> bool:
        """Write updated state back to Solana"""
        # In production, this would build and send a Solana transaction
        # For now, just log
        logger.info(f"Would write state to Solana: {state.commitment_hash().hex()[:16]}...")
        return True

class EthereumAdapter:
    """Submit commitments to Ethereum"""
    
    def __init__(self, rpc_url: str, contract_addr: str, private_key: str):
        self.w3 = Web3(Web3.HTTPProvider(rpc_url))
        self.account = self.w3.eth.account.from_key(private_key)
        self.contract_addr = contract_addr
        
        # Simple ABI - just the commitment function
        abi = [{
            "inputs": [{"name": "commitment", "type": "bytes32"}],
            "name": "submitCommitment",
            "outputs": [],
            "stateMutability": "nonpayable",
            "type": "function"
        }]
        self.contract = self.w3.eth.contract(address=contract_addr, abi=abi)
    
    def submit_commitment(self, commitment: bytes) -> Optional[str]:
        """Submit commitment hash to Ethereum"""
        try:
            tx = self.contract.functions.submitCommitment(commitment).build_transaction({
                "from": self.account.address,
                "nonce": self.w3.eth.get_transaction_count(self.account.address),
                "gas": 100000,
                "gasPrice": self.w3.eth.gas_price
            })
            
            signed = self.w3.eth.account.sign_transaction(tx, private_key=self.account.key)
            tx_hash = self.w3.eth.send_raw_transaction(signed.rawTransaction)
            
            logger.info(f"Submitted commitment to Ethereum: {tx_hash.hex()}")
            return tx_hash.hex()
        except Exception as e:
            logger.error(f"Failed to submit to Ethereum: {e}")
            return None

# ============================================
# Evolution Programs (Pure HDGL VM programs)
# ============================================

class EvolutionPrograms:
    """Pre-defined evolution programs for the HDGL VM"""
    
    @staticmethod
    def phi_fold_evolution():
        """Standard φ-fold evolution - evolve all dimensions"""
        return [
            (1, [Decimal(i)])  # Evolve each dimension
            for i in range(8)
        ] + [(99, [])]  # Halt
    
    @staticmethod
    def dna_braid_evolution(pattern: int = 0):
        """Apply DNA braid pattern to dimensions"""
        return [
            (7, [Decimal(i), Decimal(pattern)])  # DNA braid to each dim
            for i in range(8)
        ] + [(99, [])]
    
    @staticmethod
    def strand_superposition():
        """Create A+B strand superposition in D7"""
        return [
            (8, [Decimal(0), Decimal(3), Decimal(6)]),  # Super D1+D4 → D7
            (8, [Decimal(1), Decimal(4), Decimal(7)]),  # Super D2+D5 → D8
            (99, [])
        ]
    
    @staticmethod
    def prism_evolution():
        """Full prism state evolution"""
        return [
            (15, []),  # Enter prism state
            (6, [Decimal(1)]),  # Shift dimensions up
            (99, [])
        ]
    
    @staticmethod
    def conditional_branch(threshold_dim: int = 0):
        """Conditional evolution based on dimension value"""
        return [
            (1, [Decimal(threshold_dim)]),  # Evolve threshold dimension
            (5, [Decimal(threshold_dim), Decimal(5), Decimal(8)]),  # Branch
            # Path A: Strong evolution
            (1, [Decimal(i)]) for i in range(8)
        ] + [
            (99, []),
            # Path B: Gentle contraction  
            (2, [Decimal(i)]) for i in range(8)
        ] + [(99, [])]

# ============================================
# Main Bridge Daemon (Simplified orchestration)
# ============================================

class HDGLBridge:
    """Unified bridge coordinating all chains via HDGL VM"""
    
    def __init__(self, config: Config):
        self.config = config
        self.vm = HDGLVM()
        self.solana = SolanaAdapter(config.solana_rpc, config.solana_state)
        self.ethereum = EthereumAdapter(config.eth_rpc, config.eth_contract, config.eth_key)
        self.evolution_count = 0
    
    def run(self):
        """Main daemon loop"""
        logger.info("HDGL Bridge starting...")
        
        while True:
            try:
                self.cycle()
                time.sleep(self.config.poll_interval)
            except KeyboardInterrupt:
                logger.info("Bridge shutting down...")
                break
            except Exception as e:
                