#!/usr/bin/env bash
# Cross-check Chain-138 deployment across all components

set -e

cd "$(dirname "$0")/../.."

# Color codes

echo "==================================================================="
echo "  CHAIN-138 CROSS-CHECK VERIFICATION"
echo "==================================================================="

# Load environment variables
if [ -f .env ]; then
    source .env 2>/dev/null || true
fi

ISSUES=0

check_consistency() {
    local component=$1
    local status=$2
    local details=$3
    
    if [ "$status" = "ok" ]; then
        echo -e "  ${GREEN}✅ $component${NC}"
    elif [ "$status" = "warning" ]; then
        echo -e "  ${YELLOW}⚠️  $component${NC}"
        ISSUES=$((ISSUES + 1))
    else
        echo -e "  ${RED}❌ $component${NC}"
        ISSUES=$((ISSUES + 1))
    fi
    
    if [ -n "$details" ]; then
        echo "    $details"
    fi
}

log_info "1. Configuration Consistency"

# Check .env vs genesis.json
if [ -f .env ] && [ -f genesis.json ]; then
    # Check chain ID consistency
    ENV_CHAIN_ID=$(grep "CHAIN_ID\|CHAINID" .env 2>/dev/null | grep -v "^#" | head -1 | cut -d'=' -f2 | tr -d ' ' || echo "")
    GENESIS_CHAIN_ID=$(grep -o '"chainId"[[:space:]]*:[[:space:]]*[0-9]*' genesis.json 2>/dev/null | grep -o '[0-9]*' | head -1 || echo "")
    
    if [ -n "$GENESIS_CHAIN_ID" ] && [ "$GENESIS_CHAIN_ID" = "138" ]; then
        check_consistency "Chain ID in Genesis" "ok" "Chain ID: 138"
    else
        check_consistency "Chain ID in Genesis" "error" "Chain ID mismatch or not found"
    fi
    
    # Check WETH9 address consistency
    if grep -q "C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" genesis.json 2>/dev/null; then
        check_consistency "WETH9 in Genesis" "ok" "Address: 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
    else
        check_consistency "WETH9 in Genesis" "error" "Not found in genesis.json"
    fi
    
    # Check WETH10 address consistency
    if grep -q "f4BB2e28688e89fCcE3c0580D37d36A7672E8A9f" genesis.json 2>/dev/null; then
        check_consistency "WETH10 in Genesis" "ok" "Address: 0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"
    else
        check_consistency "WETH10 in Genesis" "error" "Not found in genesis.json"
    fi
else
    check_consistency "Configuration Files" "error" ".env or genesis.json missing"
fi

log_info "2. Contract Address Consistency"

# Check if contract addresses are consistent across files
WETH9_CANONICAL="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
WETH10_CANONICAL="0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"

# Check documentation
DOCS_WETH9=$(grep -r "C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" docs/ 2>/dev/null | wc -l)
DOCS_WETH10=$(grep -r "f4BB2e28688e89fCcE3c0580D37d36A7672E8A9f" docs/ 2>/dev/null | wc -l)

if [ "$DOCS_WETH9" -gt 0 ]; then
    check_consistency "WETH9 in Documentation" "ok" "Found in $DOCS_WETH9 files"
else
    check_consistency "WETH9 in Documentation" "warning" "Not found in documentation"
fi

if [ "$DOCS_WETH10" -gt 0 ]; then
    check_consistency "WETH10 in Documentation" "ok" "Found in $DOCS_WETH10 files"
else
    check_consistency "WETH10 in Documentation" "warning" "Not found in documentation"
fi

log_info "3. Network Configuration"

# Check RPC URL format
if [ -n "$CHAIN138_RPC_URL" ]; then
    if [[ "$CHAIN138_RPC_URL" =~ ^https?:// ]]; then
        check_consistency "RPC URL Format" "ok" "Valid HTTP/HTTPS URL"
    else
        check_consistency "RPC URL Format" "error" "Invalid URL format"
    fi
else
    check_consistency "RPC URL" "error" "Not configured"
fi

# Check chain selector
if [ -n "$CHAIN138_SELECTOR" ]; then
    if [ "$CHAIN138_SELECTOR" = "0x000000000000008a" ] || [ "$CHAIN138_SELECTOR" = "138" ]; then
        check_consistency "Chain Selector" "ok" "Correct selector: $CHAIN138_SELECTOR"
    else
        check_consistency "Chain Selector" "warning" "Selector: $CHAIN138_SELECTOR (verify correctness)"
    fi
else
    check_consistency "Chain Selector" "warning" "Not configured"
fi

log_info "4. Deployment Artifacts"

# Check Foundry broadcast files
if [ -d "broadcast" ]; then
    CHAIN138_BROADCASTS=$(find broadcast -name "*.json" -type f 2>/dev/null | grep -E "138" | wc -l)
    if [ "$CHAIN138_BROADCASTS" -gt 0 ]; then
        check_consistency "Foundry Broadcasts" "ok" "$CHAIN138_BROADCASTS files found"
    else
        check_consistency "Foundry Broadcasts" "warning" "No Chain-138 broadcasts found"
    fi
else
    check_consistency "Foundry Broadcasts" "warning" "broadcast directory not found"
fi

# Check Hardhat artifacts
if [ -d "artifacts" ]; then
    ARTIFACT_COUNT=$(find artifacts -name "*.json" -type f 2>/dev/null | wc -l)
    check_consistency "Hardhat Artifacts" "ok" "$ARTIFACT_COUNT files found"
else
    check_consistency "Hardhat Artifacts" "warning" "artifacts directory not found"
fi

log_info "5. Service Configuration"

# Check Kubernetes configuration
if [ -d "k8s" ]; then
    K8S_FILES=$(find k8s -name "*.yaml" -o -name "*.yml" 2>/dev/null | wc -l)
    if [ "$K8S_FILES" -gt 0 ]; then
        check_consistency "Kubernetes Config" "ok" "$K8S_FILES manifest files"
    else
        check_consistency "Kubernetes Config" "warning" "No manifest files found"
    fi
else
    check_consistency "Kubernetes Config" "warning" "k8s directory not found"
fi

# Check Helm configuration
if [ -d "helm" ]; then
    HELM_CHARTS=$(find helm -name "Chart.yaml" 2>/dev/null | wc -l)
    if [ "$HELM_CHARTS" -gt 0 ]; then
        check_consistency "Helm Charts" "ok" "$HELM_CHARTS charts found"
    else
        check_consistency "Helm Charts" "warning" "No charts found"
    fi
else
    check_consistency "Helm Charts" "warning" "helm directory not found"
fi

echo "==================================================================="
log_info "SUMMARY"
echo "==================================================================="
echo "  Issues Found: $ISSUES"

if [ $ISSUES -eq 0 ]; then
    log_success "✅ All cross-checks passed!"
    exit 0
else
    log_warn "⚠️  Some inconsistencies found"
    exit 1
fi
