#!/bin/bash
# Fix all issues: keys, allowlist, health checks
# Usage: ./scripts/fix-all-issues.sh

set -e

PROXMOX_HOST="192.168.11.11"
WEB3SIGNER_IP="192.168.11.111"
WEB3SIGNER_CONTAINER="107"

echo "═══════════════════════════════════════════════════════════════"
echo "🔧 FIXING ALL ISSUES"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# Step 1: Fix Web3Signer keys
echo "Step 1: Fixing Web3Signer keys..."
echo "  - Fixing permissions..."
ssh root@$PROXMOX_HOST "pct exec $WEB3SIGNER_CONTAINER -- bash -c 'for f in /opt/web3signer/data/keys/*.json; do [ -f \"\$f\" ] && chmod 644 \"\$f\"; done'" || echo "  ⚠️  Permission fix had issues"

echo "  - Restarting Web3Signer..."
ssh root@$PROXMOX_HOST "pct exec $WEB3SIGNER_CONTAINER -- systemctl restart web3signer && sleep 5" || echo "  ⚠️  Restart had issues"

echo "  - Checking keys..."
sleep 3
KEYS=$(curl -s http://$WEB3SIGNER_IP:9000/api/v1/eth1/publicKeys 2>/dev/null || echo "[]")

if [ "$KEYS" != "[]" ] && [ -n "$KEYS" ]; then
    KEY_COUNT=$(echo "$KEYS" | jq '. | length' 2>/dev/null || echo "0")
    if [ "$KEY_COUNT" -gt 0 ]; then
        echo "  ✅ $KEY_COUNT key(s) loaded!"
        ADDRESSES=$(echo "$KEYS" | jq -r '.[]' | tr '\n' ',' | sed 's/,$//')
        echo "$ADDRESSES" > /tmp/web3signer-addresses.txt
    else
        echo "  ⚠️  Keys not loaded yet"
        exit 1
    fi
else
    echo "  ⚠️  No keys found"
    echo "  Checking logs..."
    ssh root@$PROXMOX_HOST "pct exec $WEB3SIGNER_CONTAINER -- journalctl -u web3signer.service -n 20 --no-pager" 2>&1 | tail -10
    exit 1
fi

# Step 2: Configure allowlist
echo ""
echo "Step 2: Configuring wallet allowlist..."
if [ -f /tmp/web3signer-addresses.txt ]; then
    ADDRESSES=$(cat /tmp/web3signer-addresses.txt)
    cd "$(dirname "$0")/.."
    ./scripts/configure-wallet-allowlist.sh "$ADDRESSES" || echo "  ⚠️  Allowlist configuration had issues"
else
    echo "  ⚠️  Addresses file not found"
fi

# Step 3: Check health endpoint issues
echo ""
echo "Step 3: Diagnosing health endpoint issues..."
for IP in 192.168.11.240 192.168.11.241 192.168.11.242; do
    echo ""
    echo "=== $IP ==="
    
    # Check if service is running
    SERVICE_STATUS=$(ssh -i ~/.ssh/proxmox_translator -o StrictHostKeyChecking=no root@$IP "systemctl is-active rpc-translator-138.service" 2>/dev/null || echo "inactive")
    echo "  Service: $SERVICE_STATUS"
    
    if [ "$SERVICE_STATUS" = "active" ]; then
        # Check if port is listening
        PORT_LISTEN=$(ssh -i ~/.ssh/proxmox_translator -o StrictHostKeyChecking=no root@$IP "netstat -tlnp 2>/dev/null | grep ':9545' || ss -tlnp 2>/dev/null | grep ':9545'" 2>/dev/null || echo "")
        if [ -n "$PORT_LISTEN" ]; then
            echo "  ✅ Port 9545 is listening"
        else
            echo "  ⚠️  Port 9545 not listening"
        fi
        
        # Test health endpoint with timeout
        HEALTH_RESPONSE=$(curl -s -m 10 http://$IP:9545/health 2>&1 || echo "ERROR")
        if echo "$HEALTH_RESPONSE" | grep -q "status"; then
            echo "  ✅ Health endpoint responding"
            echo "$HEALTH_RESPONSE" | jq '.status' 2>/dev/null || echo "$HEALTH_RESPONSE"
        else
            echo "  ⚠️  Health endpoint not responding correctly"
            echo "  Response: $HEALTH_RESPONSE"
            
            # Check logs for errors
            echo "  Checking recent logs..."
            ssh -i ~/.ssh/proxmox_translator -o StrictHostKeyChecking=no root@$IP "journalctl -u rpc-translator-138.service -n 30 --no-pager" 2>&1 | grep -i "error\|health\|exception" | tail -5 || echo "  No errors in logs"
        fi
        
        # Test RPC endpoint
        RPC_RESPONSE=$(curl -s -m 5 -X POST http://$IP:9545 \
            -H 'Content-Type: application/json' \
            -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' 2>&1)
        if echo "$RPC_RESPONSE" | grep -q "result"; then
            CHAIN_ID=$(echo "$RPC_RESPONSE" | jq -r '.result' 2>/dev/null || echo "unknown")
            echo "  ✅ RPC working (ChainID: $CHAIN_ID)"
        else
            echo "  ⚠️  RPC not working"
            echo "  Response: $RPC_RESPONSE" | head -3
        fi
    else
        echo "  ⚠️  Service not active, attempting restart..."
        ssh -i ~/.ssh/proxmox_translator -o StrictHostKeyChecking=no root@$IP "systemctl restart rpc-translator-138.service && sleep 3" 2>&1 || echo "  ⚠️  Restart failed"
    fi
done

# Step 4: Summary
echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "📊 SUMMARY"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# Check Web3Signer
KEYS=$(curl -s http://$WEB3SIGNER_IP:9000/api/v1/eth1/publicKeys 2>/dev/null || echo "[]")
if [ "$KEYS" != "[]" ]; then
    KEY_COUNT=$(echo "$KEYS" | jq '. | length' 2>/dev/null || echo "0")
    echo "Web3Signer: ✅ $KEY_COUNT key(s) loaded"
else
    echo "Web3Signer: ⚠️  No keys loaded"
fi

# Check translators
for IP in 192.168.11.240 192.168.11.241 192.168.11.242; do
    SERVICE_STATUS=$(ssh -i ~/.ssh/proxmox_translator -o StrictHostKeyChecking=no root@$IP "systemctl is-active rpc-translator-138.service" 2>/dev/null || echo "unknown")
    HEALTH=$(curl -s -m 5 http://$IP:9545/health 2>/dev/null | jq -r '.status' 2>/dev/null || echo "unknown")
    RPC=$(curl -s -m 5 -X POST http://$IP:9545 -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' 2>/dev/null | jq -r '.result' 2>/dev/null || echo "unknown")
    
    echo "$IP: Service=$SERVICE_STATUS, Health=$HEALTH, RPC=$RPC"
done

echo ""
echo "✅ Diagnostic complete!"
