#!/usr/bin/env bash
# Confirm Cronos deployments: test CRONOSCAN_API_KEY, verify contracts on-chain.
# See docs/04-configuration/CRONOS_EXPLORER_OPERATIONS.md

set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi

RPC="${CRONOS_RPC_URL:-https://evm.cronos.org}"
CONTRACTS=(
  "0x99B3511A2d315A497C8112C1fdd8D508d4B1E506:WETH9"
  "0x3304b747E565a97ec8AC220b0B6A1f6ffDB837e6:WETH10"
  "0x3Cc23d086fCcbAe1e5f3FE2bA4A263E1D27d8Cab:CCIPWETH9Bridge"
  "0x105F8A15b819948a89153505762444Ee9f324684:CCIPWETH10Bridge"
)

echo "=== Cronos (Chain 25) deployment confirmation ==="
echo ""

# 1. On-chain confirmation via RPC (eth_getCode)
echo "1. On-chain bytecode check (RPC: $RPC):"
ok=0 missing=0
for entry in "${CONTRACTS[@]}"; do
  addr="${entry%%:*}"
  name="${entry##*:}"
  code=$(cast code "$addr" --rpc-url "$RPC" 2>/dev/null || echo "0x")
  if [ "${#code}" -gt 10 ]; then
    echo "   ✓ $name ($addr)"
    ((ok++)) || true
  else
    echo "   ✗ $name ($addr) — no bytecode"
    ((missing++)) || true
  fi
done
echo "   Summary: $ok confirmed, $missing missing"
echo ""

# 2. Explorer API (if key set)
if [ -n "${CRONOSCAN_API_KEY:-}" ]; then
  echo "2. Cronos Explorer API (CRONOSCAN_API_KEY):"
  BLOCK=$(curl -s "https://explorer-api.cronos.org/mainnet/api/v1/ethproxy/getBlockNumber?apikey=${CRONOSCAN_API_KEY}")
  if echo "$BLOCK" | grep -q '"result"'; then
    NUM=$(echo "$BLOCK" | jq -r '.result')
    echo "   ✓ Block number: $NUM (dec: $((NUM)))"
  else
    echo "   ✗ API error: $BLOCK"
  fi
  echo ""
else
  echo "2. Cronos Explorer API: SKIP (set CRONOSCAN_API_KEY for block/explorer data)"
  echo ""
fi

# 3. Verification instructions
echo "3. Contract verification:"
echo "   Manual: https://explorer.cronos.org/verifyContract"
echo "   Per-address: https://explorer.cronos.org/address/<ADDR>"
echo ""
echo "Full reference: docs/04-configuration/CRONOS_EXPLORER_OPERATIONS.md"
