#!/usr/bin/env bash
# Canary CCIP proof: Monad (143) -> Chain 138 via CCIPWETH9Bridge send lane (native MON fees).
# Prefers CCIPWETH9_BRIDGE_MONAD_SEND (custom event-only router); falls back to hub bridge.
#
# Usage:
#   DRY_RUN=1 ./scripts/deployment/proof-ccip-monad-chain138.sh
#   ./scripts/deployment/proof-ccip-monad-chain138.sh
#   AMOUNT_ETH=0.001 ./scripts/deployment/proof-ccip-monad-chain138.sh

set -euo pipefail

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

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"
elif [[ -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
fi

DRY_RUN="${DRY_RUN:-0}"
AMOUNT_ETH="${AMOUNT_ETH:-0.001}"
MONAD_RPC="${MONAD_MAINNET_RPC:-https://rpc.monad.xyz}"
if [[ "$MONAD_RPC" =~ infura\.io/v3 ]] && [[ "${MONAD_MAINNET_RPC_FORCE_INFURA:-0}" != "1" ]]; then
  MONAD_RPC="${MONAD_MAINNET_RPC_PUBLIC:-https://rpc.monad.xyz}"
elif [[ -n "${MONAD_MAINNET_RPC:-}" ]] && [[ "${MONAD_MAINNET_RPC_FORCE_INFURA:-0}" == "1" ]]; then
  MONAD_RPC="$MONAD_MAINNET_RPC"
fi

BRIDGE="${CCIPWETH9_BRIDGE_MONAD_SEND:-${CCIPWETH9_BRIDGE_MONAD:-}}"
WMON="${WMON_MAINNET:-0x754704Bc059F8C67012fEd69BC8A327a5aafb603}"
SEL="${CHAIN138_SELECTOR:-}"

for v in BRIDGE SEL PRIVATE_KEY; do
  if [[ -z "${!v}" ]]; then
    echo "Missing: $v" >&2
    exit 1
  fi
done

if ! require_private_key_env; then
  exit 1
fi

SENDER=$(cast wallet address --private-key "$PRIVATE_KEY")
RECIPIENT="${PROOF_RECIPIENT:-$SENDER}"
AMOUNT_WEI=$(cast --to-wei "$AMOUNT_ETH" ether)

echo "=== Monad -> Chain 138 CCIP canary ==="
echo "Bridge: $BRIDGE"
echo "WMON: $WMON"
echo "Amount: $AMOUNT_ETH WMON ($AMOUNT_WEI wei)"
echo "Recipient (138): $RECIPIENT"
echo "Selector: $SEL"

FEE_WEI=$(cast call "$BRIDGE" "calculateFee(uint64,uint256)" "$SEL" "$AMOUNT_WEI" --rpc-url "$MONAD_RPC" | cast --to-dec)
FEE_TOKEN=$(cast call "$BRIDGE" "feeToken()(address)" --rpc-url "$MONAD_RPC")
ZERO="0x0000000000000000000000000000000000000000"
if [[ "${FEE_TOKEN,,}" == "${ZERO,,}" ]]; then
  echo "CCIP fee (native MON): $FEE_WEI wei"
else
  echo "CCIP fee (LINK): $FEE_WEI wei"
fi

BAL=$(cast call "$WMON" "balanceOf(address)(uint256)" "$SENDER" --rpc-url "$MONAD_RPC" | awk '{print $1}' | cast --to-dec 2>/dev/null || echo 0)
echo "Deployer WMON balance: $BAL wei"

if [[ "$BAL" -lt "$AMOUNT_WEI" ]]; then
  WRAP=$((AMOUNT_WEI - BAL + 1000000000000000))
  echo "Wrapping $WRAP wei MON -> WMON via deposit()"
  if [[ "$DRY_RUN" == "1" ]]; then
    echo "[DRY RUN] cast send $WMON deposit() --value $WRAP --rpc-url $MONAD_RPC"
  else
    cast send "$WMON" "deposit()" --value "$WRAP" \
      --rpc-url "$MONAD_RPC" --private-key "$PRIVATE_KEY" --legacy
  fi
fi

if [[ "$DRY_RUN" == "1" ]]; then
  echo "[DRY RUN] cast send $WMON approve($BRIDGE,$AMOUNT_WEI)"
  echo "[DRY RUN] cast send $BRIDGE sendCrossChain($SEL,$RECIPIENT,$AMOUNT_WEI) --value $FEE_WEI"
  cast call "$BRIDGE" "sendCrossChain(uint64,address,uint256)" "$SEL" "$RECIPIENT" "$AMOUNT_WEI" \
    --rpc-url "$MONAD_RPC" --from "$SENDER" --value "$FEE_WEI" >/dev/null && echo "Simulation: OK" || echo "Simulation: FAILED"
  exit 0
fi

cast send "$WMON" "approve(address,uint256)" "$BRIDGE" "$AMOUNT_WEI" \
  --rpc-url "$MONAD_RPC" --private-key "$PRIVATE_KEY" --legacy

if [[ "${FEE_TOKEN,,}" != "${ZERO,,}" ]] && [[ "$FEE_WEI" -gt 0 ]]; then
  cast send "$FEE_TOKEN" "approve(address,uint256)" "$BRIDGE" "$((FEE_WEI + 1))" \
    --rpc-url "$MONAD_RPC" --private-key "$PRIVATE_KEY" --legacy
  OUT=$(cast send "$BRIDGE" "sendCrossChain(uint64,address,uint256)" "$SEL" "$RECIPIENT" "$AMOUNT_WEI" \
    --rpc-url "$MONAD_RPC" --private-key "$PRIVATE_KEY" --legacy --json)
else
  OUT=$(cast send "$BRIDGE" "sendCrossChain(uint64,address,uint256)" "$SEL" "$RECIPIENT" "$AMOUNT_WEI" \
    --value "$FEE_WEI" --rpc-url "$MONAD_RPC" --private-key "$PRIVATE_KEY" --legacy --json)
fi
echo "$OUT"
HASH=$(echo "$OUT" | jq -r '.transactionHash // empty')
echo ""
echo "Submitted: $HASH"
echo "Monad explorer: https://monadscan.com/tx/${HASH}"
echo "Report: reports/status/proof-ccip-monad-chain138-latest.json"

mkdir -p "/home/intlc/projects/proxmox/reports/status"
REPORT="/home/intlc/projects/proxmox/reports/status/proof-ccip-monad-chain138-latest.json"
cat > "$REPORT" <<EOF
{
  "generatedAt": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "direction": "monad_to_chain138",
  "amountEth": "$AMOUNT_ETH",
  "amountWei": "$AMOUNT_WEI",
  "feeWei": "$FEE_WEI",
  "bridge": "$BRIDGE",
  "recipient": "$RECIPIENT",
  "txHash": "${HASH:-}",
  "monadExplorer": "https://monadscan.com/tx/${HASH:-}"
}
EOF
