#!/usr/bin/env bash
# Emit explorer-monorepo/frontend/public/config/topology-graph.json from
# repo-root config/smart-contracts-master.json (Chain 138 contracts as nodes).
# Run from any cwd; prefers monorepo ../../config when invoked from scripts/.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MONO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
OUT="$SCRIPT_DIR/../frontend/public/config/topology-graph.json"
MASTER="$MONO_ROOT/config/smart-contracts-master.json"
EXPLORER_PUBLIC_BASE="${EXPLORER_PUBLIC_BASE:-https://explorer.d-bis.org}"
BASE="${EXPLORER_PUBLIC_BASE%/}"

if [[ ! -f "$MASTER" ]]; then
  echo "warning: smart-contracts-master.json not found; leaving existing topology-graph.json unchanged" >&2
  exit 0
fi

mkdir -p "$(dirname "$OUT")"

ts="$(date -u +%Y-%m-%dT%H:%M:%SZ)"

LIQ_JSON="null"
if [[ -n "${TOKEN_AGGREGATION_BASE_URL:-}" ]]; then
  CUSDT="0x93E66202A11B1772E55407B32B44e5Cd8eda7f22"
  TA_URL="${TOKEN_AGGREGATION_BASE_URL%/}/api/v1/tokens/${CUSDT}/pools?chainId=138"
  code=$(curl -sS -o /tmp/ta-topology-pools.json -w "%{http_code}" -m 20 "$TA_URL" || echo "000")
  if [[ "$code" == "200" ]] && [[ -s /tmp/ta-topology-pools.json ]]; then
    pc=""
    pc=$(jq '(.pools // .data.pools // []) | length' /tmp/ta-topology-pools.json 2>/dev/null || true)
    if [[ "$pc" =~ ^[0-9]+$ ]]; then
      LIQ_JSON=$(jq -n --argjson poolCount "$pc" --arg token "$CUSDT" '{chainId:"138",sampleToken:$token,poolCount:$poolCount}')
    fi
  fi
fi

jq --arg ts "$ts" --arg base "$BASE" --argjson liquiditySample "$LIQ_JSON" '
  .chains["138"].contracts // {} | to_entries
  | map(select(.value | type == "string"))
  | map(select(.value | test("^0x[a-fA-F0-9]{40}$")))
  | .[:40]
  | . as $pairs
  | ($pairs | map({data: {id: (.value | ascii_downcase), label: (.key + " (" + (.value | .[0:10]) + "…)"), href: ($base + "/address/" + (.value | ascii_downcase))}})) as $nodes
  | ($pairs | map(select(.key | test("CCIP|Router|Bridge|UniversalCCIP")))) as $bridgeish
  | ($pairs | map(select(.key | test("DODO|PMM|Pool_cUS")))) as $pmmish
  | ($nodes)
    + [{data: {id: "stack_rpc", label: "Chain 138 RPC (logical)"}}]
    + ($bridgeish | map(.value | ascii_downcase) | unique | map({data: {source: "stack_rpc", target: ., label: "settlement"}}))
    + ($pmmish | map(.value | ascii_downcase) | unique | map({data: {source: "stack_rpc", target: ., label: "liquidity"}}))
  | {generatedAt: $ts, description: "Auto-generated from config/smart-contracts-master.json (subset)", liquiditySample: $liquiditySample, elements: .}
' "$MASTER" >"$OUT.tmp"
mv "$OUT.tmp" "$OUT"
echo "wrote $OUT"
