#!/usr/bin/env bash
# Deploy Tether-style ISO-4217 complements (cAUDT, cJPYT, cCHFT, cCADT) on Chain 138.
#
# Why not CREATE2 via CREATE2Factory (0x750E4a8adCe9f0e67A420aBE91342DC64Eb90825)?
# On Core/Besu, factory.deploy(bytes,uint256) with CompliantFiatToken initcode consistently
# OOGs (~2.6M–8M+ gas) even with high limits; eth_call traces succeed — use standard CREATE here.
#
# Uses scoped Forge (scripts/forge/scope.sh create tokens) so solc does not pull the full repo.
# Compiles with --evm-version paris: Core 138 Besu may reject Cancun bytecode (invalid opcode 0x5f/PUSH0).
#
# Requires: PRIVATE_KEY; RPC via RPC_URL_138, CHAIN138_RPC, or RPC_URL (see below).
# Idempotent: skips if contract already has code at the address from env (if set).
#
# Usage: from repo root:
#   bash smom-dbis-138/scripts/deployment/deploy-compliant-fiat-tether-iso-chain138.sh

set -euo pipefail

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

if [[ -f "$PROXMOX_ROOT/scripts/lib/load-project-env.sh" ]]; then
  # shellcheck disable=SC1090
  PROJECT_ROOT="$PROXMOX_ROOT" source "$PROXMOX_ROOT/scripts/lib/load-project-env.sh"
elif [[ -f .env ]]; then
  set -a && source .env && set +a
fi

[[ -n "${PRIVATE_KEY:-}" ]] || { echo "PRIVATE_KEY required"; exit 1; }
command -v jq >/dev/null 2>&1 || { echo "jq required (for receipt status check)"; exit 1; }
RPC="${RPC_URL_138:-${CHAIN138_RPC:-${RPC_URL:-http://192.168.11.211:8545}}}"
# Paris bytecode deploy ~2M gas; leave headroom for Besu.
GAS_LIMIT_DEPLOY="${GAS_LIMIT_DEPLOY:-3500000}"
EVM_VERSION_CHAIN138="${EVM_VERSION_CHAIN138:-paris}"
OWNER="$(cast wallet address "$PRIVATE_KEY")"

# Ensure scoped artifacts match chain EVM (Paris for Chain 138 Core).
bash scripts/forge/scope.sh build tokens --evm-version "$EVM_VERSION_CHAIN138" --force

declare -a SPECS=(
  "cAUDT|Tether AUD (Compliant)|AUD|${CAUDT_ADDRESS_138:-}"
  "cJPYT|Tether JPY (Compliant)|JPY|${CJPYT_ADDRESS_138:-}"
  "cCHFT|Tether CHF (Compliant)|CHF|${CCHFT_ADDRESS_138:-}"
  "cCADT|Tether CAD (Compliant)|CAD|${CCADT_ADDRESS_138:-}"
)

DEPLOYED_SNIPPET="# After deploy (paste into smom-dbis-138/.env next to other C*ADDRESS_138):"
while IFS='|' read -r sym name cc existing; do
  if [[ -n "$existing" && "$existing" != "0x0000000000000000000000000000000000000000" ]]; then
    code=$(cast code "$existing" --rpc-url "$RPC" 2>/dev/null || echo "0x")
    if [[ -n "$code" && "$code" != "0x" ]]; then
      echo "Skip $sym (already deployed at $existing)"
      continue
    fi
  fi
  echo "Deploy $sym..."
  out=$(bash scripts/forge/scope.sh create tokens contracts/tokens/CompliantFiatToken.sol:CompliantFiatToken \
    --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy \
    --evm-version "$EVM_VERSION_CHAIN138" \
    --gas-limit "$GAS_LIMIT_DEPLOY" \
    --broadcast \
    --constructor-args "$name" "$sym" 6 "$cc" "$OWNER" "$OWNER" 1000000000000 2>&1) || {
      echo "$out"
      exit 1
    }
  echo "$out"
  txh=$(printf '%s\n' "$out" | sed -n 's/.*Transaction hash: \(0x[0-9a-fA-F]\{64\}\).*/\1/p' | head -1)
  if [[ -n "$txh" ]]; then
    st=$(cast receipt "$txh" --json --rpc-url "$RPC" 2>/dev/null | jq -r '.status // "0x0"')
    if [[ "$st" != "0x1" ]]; then
      echo "error: tx $txh failed on-chain (status=$st). Raise GAS_LIMIT_DEPLOY or inspect: cast run $txh --rpc-url $RPC" >&2
      exit 1
    fi
  fi
  addr=$(printf '%s\n' "$out" | sed -n 's/.*Deployed to: \(0x[0-9a-fA-F]\{40\}\).*/\1/p' | head -1)
  if [[ -z "$addr" ]]; then
    addr=$(printf '%s\n' "$out" | sed -n 's/.*"contract":"\(0x[0-9a-fA-F]\{40\}\)".*/\1/p' | head -1)
  fi
  if [[ -n "$addr" ]]; then
    ccode=$(cast code "$addr" --rpc-url "$RPC" 2>/dev/null || echo "0x")
    if [[ -z "$ccode" || "$ccode" == "0x" ]]; then
      echo "error: no code at $addr after successful receipt — aborting" >&2
      exit 1
    fi
  fi
  if [[ -n "$addr" ]]; then
    var=""
    case "$sym" in
      cAUDT) var="CAUDT_ADDRESS_138" ;;
      cJPYT) var="CJPYT_ADDRESS_138" ;;
      cCHFT) var="CCHFT_ADDRESS_138" ;;
      cCADT) var="CCADT_ADDRESS_138" ;;
    esac
    DEPLOYED_SNIPPET+=$'\n'"${var}=${addr}"
  fi
done < <(printf '%s\n' "${SPECS[@]}")

echo ""
echo "$DEPLOYED_SNIPPET"
echo ""
echo "Verify: cast code <addr> --rpc-url \"\$RPC_URL_138\""
echo "Optional mint (random 26M–85M per token, deployer must hold minter role):"
echo "  bash smom-dbis-138/scripts/mint-compliant-fiat-tether-iso-138.sh"
