#!/usr/bin/env bash
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

require_env() {
  local name="$1"
  if [[ -z "${!name:-}" ]]; then
    echo "ERROR: $name is required" >&2
    exit 1
  fi
}

require_env WEMIX_RPC
require_env CCIPWETH9_BRIDGE_WEMIX
require_env CCIPWETH10_BRIDGE_WEMIX
require_env CCIP_ROUTER_WEMIX
require_env WETH9_WEMIX
require_env WETH10_WEMIX
require_env LINK_TOKEN_WEMIX
require_env WEMIXSCAN_API_KEY

flatten_b64() {
  local source_file="$1"
  forge flatten "$source_file" | python3 -c 'import sys,base64; print(base64.b64encode(sys.stdin.buffer.read()).decode())'
}

constructor_args() {
  local weth="$1"
  cast abi-encode 'constructor(address,address,address)' \
    "$CCIP_ROUTER_WEMIX" \
    "$weth" \
    "$LINK_TOKEN_WEMIX" | sed 's/^0x//'
}

submit_verify() {
  local address="$1"
  local contract_name="$2"
  local source_file="$3"
  local weth="$4"

  local payload
  payload="$(mktemp)"

  python3 - "$payload" "$contract_name" "$(flatten_b64 "$source_file")" "$(constructor_args "$weth")" <<'PY'
import json
import sys
from pathlib import Path

path, contract_name, contract_source, constructor_arguments = sys.argv[1:]
body = {
    "contract_name": contract_name,
    "compiler": "v0.8.20+commit.a1b79de6",
    "runs_optimizer": 200,
    "optimization_enabled": 1,
    "contract_source": contract_source,
    "constructor_arguments": constructor_arguments,
    "libraries": [],
}
Path(path).write_text(json.dumps(body))
PY

  echo "Submitting verification for $contract_name at $address..."
  local response_file
  response_file="$(mktemp)"
  local http_code
  http_code="$(
    curl --max-time 90 \
      -sS \
      -o "$response_file" \
      -w '%{http_code}' \
      -H "api-key: ${WEMIXSCAN_API_KEY}" \
      -H 'Content-Type: application/json' \
      -X POST \
      --data @"$payload" \
      "https://explorerapi.wemix.com/v1/contracts/${address}/verify"
  )"

  echo "HTTP ${http_code}"
  cat "$response_file"
  echo

  if [[ "$http_code" == "200" ]]; then
    echo "Verification request accepted for $contract_name"
  elif [[ "$http_code" == "504" ]]; then
    echo "WARNING: Wemix explorer timed out while compiling $contract_name. Check the explorer code tab manually." >&2
  else
    echo "WARNING: Verification not accepted for $contract_name" >&2
  fi
}

check_status() {
  local address="$1"
  echo "Checking explorer code endpoint for $address..."
  curl --max-time 30 \
    -sS \
    -H "api-key: ${WEMIXSCAN_API_KEY}" \
    "https://explorerapi.wemix.com/v1/contracts/${address}/code" || true
  echo
}

submit_verify "$CCIPWETH9_BRIDGE_WEMIX" "CCIPWETH9Bridge" "contracts/ccip/CCIPWETH9Bridge.sol" "$WETH9_WEMIX"
submit_verify "$CCIPWETH10_BRIDGE_WEMIX" "CCIPWETH10Bridge" "contracts/ccip/CCIPWETH10Bridge.sol" "$WETH10_WEMIX"

check_status "$CCIPWETH9_BRIDGE_WEMIX"
check_status "$CCIPWETH10_BRIDGE_WEMIX"
