#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
source "$ROOT_DIR/scripts/lib/init.sh"
load_env --file "$ROOT_DIR/.env" ${ENV_PROFILE:+--profile "$ENV_PROFILE"}
SCRIPT_NAME="verify-contract.sh"
SCRIPT_DESC="Submit contract verification to ChainID 138 Etherscan-like API"
SCRIPT_USAGE="${SCRIPT_NAME} --address <addr> --contract-name <name> --compiler <ver> --source <path> [--apikey <key>] [--url <api>]"
SCRIPT_OPTIONS="--address ADDR     Deployed contract address
--contract-name NAME Contract name (e.g., MirrorManager)
--compiler VER      Compiler version (e.g., v0.8.19+commit.7dd6d404)
--source PATH       Source file path
--apikey KEY        API key (default: CHAIN138_ETHERSCAN_API_KEY)
--url URL           API base (default: CHAIN138_ETHERSCAN_API_URL)"
handle_help "${1:-}"

ADDR=""; NAME=""; COMPILER=""; SOURCE=""; KEY="${CHAIN138_ETHERSCAN_API_KEY:-}"; API="${CHAIN138_ETHERSCAN_API_URL:-}"
while [[ $# -gt 0 ]]; do
  case "$1" in
    --address) ADDR="$2"; shift 2;;
    --contract-name) NAME="$2"; shift 2;;
    --compiler) COMPILER="$2"; shift 2;;
    --source) SOURCE="$2"; shift 2;;
    --apikey) KEY="$2"; shift 2;;
    --url) API="$2"; shift 2;;
    --help) handle_help "--help";;
    *) log_error "Unknown arg: $1"; exit 1;;
  esac
done

[ -n "$ADDR" ] && [ -n "$NAME" ] && [ -n "$COMPILER" ] && [ -n "$SOURCE" ] || { log_error "Missing required args"; exit 1; }
[ -n "$API" ] || { log_error "Set CHAIN138_ETHERSCAN_API_URL"; exit 1; }
[ -f "$SOURCE" ] || { log_error "Source not found: $SOURCE"; exit 1; }

# Minimal single-file verification payload; for multi-file use standard flattening
CODE=$(sed 's/\\r//g' "$SOURCE")
POST_DATA=$(jq -Rn --arg module "contract" --arg action "verifysourcecode" \
  --arg addresshash "$ADDR" --arg contractname "$NAME" --arg compilerversion "$COMPILER" \
  --arg code "$CODE" \
  '{module:$module,action:$action,address:$addresshash,contractname:$contractname,compilerversion:$compilerversion,code:$code}' )

curl -s -X POST -H "Content-Type: application/json" -d "$POST_DATA" "${API}" | jq .


