#!/bin/bash

# Docker-compatible AA Contracts Deployment Script
# This script deploys the Account Abstraction contracts to the ethereum-node service

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo "🚀 Starting AA Contracts deployment for Docker..."

# Docker network configuration
ANVIL_HOST=ethereum-node
ANVIL_PORT=8545
CHAIN_ID=31337
DEPLOYER_ADDRESS="0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"
OMNI_EXECUTOR_SIGNER="0x90F79bf6EB2c4f870365E785982E1f101E93b906"
OUTPUT_FILE="/shared/contract-addresses.env"
JSON_OUTPUT_FILE="/shared/deployed-addresses.json"

# Function to check if anvil is running
check_anvil() {
    # Try to use curl first, fallback to cast if curl is not available
    if command -v curl >/dev/null 2>&1; then
        curl -s -X POST -H "Content-Type: application/json" \
            --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' \
            http://$ANVIL_HOST:$ANVIL_PORT > /dev/null 2>&1
    else
        # Use cast rpc to check if anvil is responsive
        cast rpc eth_blockNumber --rpc-url http://$ANVIL_HOST:$ANVIL_PORT > /dev/null 2>&1
    fi
}

# Function to wait for anvil to be ready
wait_for_anvil() {
    echo "⏳ Waiting for Anvil to be ready..."
    for i in {1..60}; do
        if check_anvil; then
            echo "✅ Anvil is ready!"
            return 0
        fi
        sleep 1
    done
    echo "❌ Anvil failed to start after 60 seconds"
    exit 1
}

# Function to deploy contracts
deploy_contracts() {
    echo "📦 Deploying contracts using Foundry script..."

    # Export environment variables for the script
    export PRIVATE_KEY="0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"  # Anvil's first private key
    export OMNI_EXECUTOR_SIGNER=$OMNI_EXECUTOR_SIGNER

    # Set proper permissions on the out directory
    chmod -R 755 out/ || true

    # Run the deployment script directly to see errors
    echo "Running forge script..."
    forge script script/DeployLocal.s.sol:DeployLocal --rpc-url http://$ANVIL_HOST:$ANVIL_PORT --broadcast --legacy

    if [ $? -ne 0 ]; then
        echo "❌ Failed to deploy contracts"
        exit 1
    fi

    # Extract addresses from the broadcast file
    BROADCAST_FILE="$SCRIPT_DIR/broadcast/DeployLocal.s.sol/$CHAIN_ID/run-latest.json"

    if [ -f "$BROADCAST_FILE" ]; then
        ENTRYPOINT_ADDRESS=$(grep -A2 '"contractName": "EntryPointV1"' "$BROADCAST_FILE" | grep '"contractAddress"' | sed 's/.*"contractAddress": "\(.*\)".*/\1/' | head -1)
        FACTORY_ADDRESS=$(grep -A2 '"contractName": "OmniAccountFactoryV1"' "$BROADCAST_FILE" | grep '"contractAddress"' | sed 's/.*"contractAddress": "\(.*\)".*/\1/' | head -1)
        PAYMASTER_ADDRESS=$(grep -A2 '"contractName": "SimplePaymaster"' "$BROADCAST_FILE" | grep '"contractAddress"' | sed 's/.*"contractAddress": "\(.*\)".*/\1/' | head -1)

        # Extract test token addresses
        USDC_ADDRESS=$(grep -A2 '"contractName": "TestToken"' "$BROADCAST_FILE" | grep '"contractAddress"' | sed 's/.*"contractAddress": "\(.*\)".*/\1/' | head -1)
        USDT_ADDRESS=$(grep -A2 '"contractName": "TestToken"' "$BROADCAST_FILE" | grep '"contractAddress"' | sed 's/.*"contractAddress": "\(.*\)".*/\1/' | tail -1)

        echo ""
        echo "🎉 All contracts deployed successfully!"
        echo ""
        echo "Contract Addresses:"
        echo "==================="
        echo "EntryPoint:         $ENTRYPOINT_ADDRESS"
        echo "OmniAccountFactory: $FACTORY_ADDRESS"
        echo "SimplePaymaster:    $PAYMASTER_ADDRESS"
        echo ""
        echo "Test Token Addresses:"
        echo "===================="
        echo "Test USDC:          $USDC_ADDRESS"
        echo "Test USDT:          $USDT_ADDRESS"
        echo ""

        # Write addresses to environment file for omni-executor
        echo "# AA Contract Addresses - Generated by deploy-docker.sh" > "$OUTPUT_FILE"
        echo "OE_ENTRY_POINT_ADDRESS=$ENTRYPOINT_ADDRESS" >> "$OUTPUT_FILE"
        echo "OE_OMNI_FACTORY_ADDRESS=$FACTORY_ADDRESS" >> "$OUTPUT_FILE"
        echo "OE_PAYMASTER_ADDRESS=$PAYMASTER_ADDRESS" >> "$OUTPUT_FILE"
        echo "OE_TEST_USDC_ADDRESS=$USDC_ADDRESS" >> "$OUTPUT_FILE"
        echo "OE_TEST_USDT_ADDRESS=$USDT_ADDRESS" >> "$OUTPUT_FILE"

        # Also write addresses to JSON format for test scripts
        cat > "$JSON_OUTPUT_FILE" << EOF
{
  "EntryPoint": "$ENTRYPOINT_ADDRESS",
  "OmniAccountFactory": "$FACTORY_ADDRESS",
  "SimplePaymaster": "$PAYMASTER_ADDRESS",
  "TestUSDC": "$USDC_ADDRESS",
  "TestUSDT": "$USDT_ADDRESS"
}
EOF

        echo "📝 Contract addresses written to $OUTPUT_FILE and $JSON_OUTPUT_FILE"
        echo "✅ Deployment complete!"

    else
        echo "⚠️  Contracts deployed but broadcast file not found"
        echo "Check the output above for contract addresses"
        exit 1
    fi
}

# Wait for Anvil to be ready
wait_for_anvil

# Compile contracts
echo "🔨 Compiling contracts..."
forge compile

# Deploy contracts
deploy_contracts

echo "🎯 Ready for omni-executor to start!"
