#!/usr/bin/env bash
# Verify mainnet cWBTC (CompliantWrappedToken) on Etherscan and write status JSON.
#
# Usage:
#   cd smom-dbis-138 && ./scripts/deployment/verify-mainnet-cwbtc-etherscan.sh
#   ./scripts/deployment/verify-mainnet-cwbtc-etherscan.sh --dry-run
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
PROXMOX="$(cd "$PROJECT_ROOT/.." && pwd)"
REPORT="${PROXMOX}/reports/status/cwbtc-mainnet-etherscan-verify-latest.json"
cd "$PROJECT_ROOT"

DRY_RUN=false
for a in "$@"; do
  case "$a" in
    --dry-run) DRY_RUN=true ;;
  esac
done

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}"
fi

ADDR="${CWBTC_MAINNET:-0x2BBe3c809386FA5349EB2da31E0848ee9f54EE59}"
ADMIN="${CW_VERIFY_ADMIN:-}"
if [[ -z "$ADMIN" && -n "${PRIVATE_KEY:-}" ]]; then
  ADMIN="$(cast wallet address --private-key "$PRIVATE_KEY")"
fi
[[ -n "${ETHERSCAN_API_KEY:-}" ]] || { echo "ETHERSCAN_API_KEY required" >&2; exit 1; }
[[ -n "$ADMIN" ]] || { echo "CW_VERIFY_ADMIN or PRIVATE_KEY required" >&2; exit 1; }

CTOR="$(cast abi-encode 'constructor(string,string,uint8,address)' 'Wrapped cBTC' 'cWBTC' 8 "$ADMIN")"

echo "=== Verify cWBTC on Etherscan ==="
echo "  address=$ADDR admin=$ADMIN"

export FOUNDRY_SRC="contracts/tokens,contracts/interfaces"
export FOUNDRY_OUT="out/scopes/tokens"
export FOUNDRY_CACHE_PATH="cache/scopes/tokens"

if $DRY_RUN; then
  echo "forge verify-contract --chain-id 1 --num-of-optimizations 200 --via-ir \\"
  echo "  --constructor-args \"$CTOR\" --etherscan-api-key \"\$ETHERSCAN_API_KEY\" \\"
  echo "  \"$ADDR\" contracts/tokens/CompliantWrappedToken.sol:CompliantWrappedToken"
  exit 0
fi

bash "$PROJECT_ROOT/scripts/forge/scope.sh" build tokens -q

status="failed"
msg=""
set +e
out="$(forge verify-contract \
  --chain-id 1 \
  --num-of-optimizations 200 \
  --via-ir \
  --constructor-args "$CTOR" \
  --etherscan-api-key "$ETHERSCAN_API_KEY" \
  "$ADDR" \
  "contracts/tokens/CompliantWrappedToken.sol:CompliantWrappedToken" 2>&1)"
rc=$?
set -e
echo "$out"
if [[ $rc -eq 0 ]] || echo "$out" | grep -qiE 'already verified|Contract source code already verified'; then
  status="verified"
  msg="ok"
else
  msg="${out:0:500}"
  exit "$rc"
fi

mkdir -p "$(dirname "$REPORT")"
python3 - "$REPORT" "$ADDR" "$ADMIN" "$status" "$msg" <<'PY'
import datetime, json, sys
path, addr, admin, status, msg = sys.argv[1:6]
doc = {
    "generatedAt": datetime.datetime.utcnow().replace(microsecond=0).isoformat() + "Z",
    "chainId": 1,
    "symbol": "cWBTC",
    "address": addr,
    "constructorAdmin": admin,
    "etherscanUrl": f"https://etherscan.io/address/{addr}",
    "etherscanCodeUrl": f"https://etherscan.io/address/{addr}#code",
    "verifyStatus": status,
    "message": msg,
    "tokenLists": [
        "token-lists/lists/ethereum-mainnet.tokenlist.json",
        "smom-dbis-138/services/token-aggregation/config/token-lists/ethereum-mainnet.tokenlist.json",
    ],
}
open(path, "w", encoding="utf-8").write(json.dumps(doc, indent=2) + "\n")
print(path)
PY

echo "Published status: $REPORT"
echo "Etherscan: https://etherscan.io/address/$ADDR#code"
