#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
PROJECT_ROOT="$(cd "$REPO_ROOT/.." && pwd)"
BUNDLE_JSON="$REPO_ROOT/config/optimism-cronos-dodo-4-pools-execution-bundle.json"
OUT_DIR="$PROJECT_ROOT/reports/status"
OUT_JSON="$OUT_DIR/optimism-cronos-dodo-4-pools-execution-bundle-latest.json"
OUT_MD="$OUT_DIR/optimism-cronos-dodo-4-pools-execution-bundle-latest.md"

source "$REPO_ROOT/scripts/lib/deployment/dotenv.sh"
load_deployment_env --repo-root "$REPO_ROOT"

mkdir -p "$OUT_DIR"

json_escape() {
  jq -Rn --arg v "${1:-}" '$v'
}

resolve_env_from_list() {
  local joined="$1"
  local value=""
  local key
  IFS='|' read -r -a _keys <<< "$joined"
  for key in "${_keys[@]}"; do
    if [[ -n "${!key:-}" ]]; then
      value="${!key}"
      break
    fi
  done
  printf '%s' "$value"
}

code_status() {
  local rpc="$1"
  local address="$2"
  if [[ -z "$rpc" || -z "$address" ]]; then
    printf 'missing'
    return
  fi
  local code=""
  code="$(cast code --rpc-url "$rpc" "$address" 2>/dev/null || true)"
  if [[ -n "$code" && "$code" != "0x" ]]; then
    printf 'has_code'
  else
    printf 'no_code'
  fi
}

symbol_call() {
  local rpc="$1"
  local address="$2"
  local value
  value="$(cast call --rpc-url "$rpc" "$address" "symbol()(string)" 2>/dev/null || true)"
  value="${value#\"}"
  value="${value%\"}"
  printf '%s' "$value"
}

json_file="$(mktemp)"
md_file="$(mktemp)"

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

{
  echo "{"
  echo "  \"generatedAt\": $(json_escape "$generated_at"),"
  echo "  \"bundle\": $(jq '.bundleName' "$BUNDLE_JSON"),"
  echo "  \"chains\": ["
} >"$json_file"

{
  echo "# Optimism/Cronos DODO 4-Pool Execution Bundle"
  echo
  echo "Generated at: \`$generated_at\`"
  echo
  echo "This bundle covers the four remaining \`configured_no_code\` DODO PMM pools:"
  echo
  echo "- Optimism: \`cWUSDC/USDC\`, \`cWUSDT/USDT\`"
  echo "- Cronos: \`cWUSDC/USDC\`, \`cWUSDT/USDT\`"
  echo
  echo "Execution posture:"
  echo
  echo "- DODO vending-machine addresses are present in env."
  echo "- Compliant \`cWUSDT\` / \`cWUSDC\` token contracts have bytecode on both chains."
  echo "- The expected pool addresses still have no code on both chains."
  echo "- The canonical quote anchors for Optimism/Cronos are the chain-native official USDT/USDC addresses below."
} >"$md_file"

first_chain=1
while IFS= read -r chain_row; do
  chain_id="$(jq -r '.chainId' <<<"$chain_row")"
  network="$(jq -r '.network' <<<"$chain_row")"
  integration_env="$(jq -r '.integrationEnv' <<<"$chain_row")"
  dvm_env="$(jq -r '.dodoVendingMachineEnv' <<<"$chain_row")"
  rpc_envs_joined="$(jq -r '.rpcEnv | join("|")' <<<"$chain_row")"

  rpc="$(resolve_env_from_list "$rpc_envs_joined")"
  dvm="${!dvm_env:-}"
  integration="${!integration_env:-}"

  official_usdc_env="$(jq -r '.official.USDC.env' <<<"$chain_row")"
  official_usdc_default="$(jq -r '.official.USDC.default' <<<"$chain_row")"
  official_usdt_env="$(jq -r '.official.USDT.env' <<<"$chain_row")"
  official_usdt_default="$(jq -r '.official.USDT.default' <<<"$chain_row")"
  official_usdc="${!official_usdc_env:-$official_usdc_default}"
  official_usdt="${!official_usdt_env:-$official_usdt_default}"

  cwusdc_env="$(jq -r '.compliant.cWUSDC.env' <<<"$chain_row")"
  cwusdt_env="$(jq -r '.compliant.cWUSDT.env' <<<"$chain_row")"
  cwusdc="${!cwusdc_env:-}"
  cwusdt="${!cwusdt_env:-}"

  integration_status="$(code_status "$rpc" "$integration")"
  dvm_status="$(code_status "$rpc" "$dvm")"
  official_usdc_status="$(code_status "$rpc" "$official_usdc")"
  official_usdt_status="$(code_status "$rpc" "$official_usdt")"
  cwusdc_status="$(code_status "$rpc" "$cwusdc")"
  cwusdt_status="$(code_status "$rpc" "$cwusdt")"

  pool_usdc_expected="$(jq -r '.pairs[] | select(.pair=="cWUSDC/USDC") | .expectedPoolAddress' <<<"$chain_row")"
  pool_usdt_expected="$(jq -r '.pairs[] | select(.pair=="cWUSDT/USDT") | .expectedPoolAddress' <<<"$chain_row")"
  pool_usdc_status="$(code_status "$rpc" "$pool_usdc_expected")"
  pool_usdt_status="$(code_status "$rpc" "$pool_usdt_expected")"
  forge_profile="default"
  if [[ "$chain_id" == "25" ]]; then
    forge_profile="cronos_legacy"
  fi

  deploy_cmd=$(cat <<EOF
cd $REPO_ROOT
DODO_VENDING_MACHINE_ADDRESS=$dvm \\
OFFICIAL_USDT_ADDRESS=$official_usdt \\
OFFICIAL_USDC_ADDRESS=$official_usdc \\
COMPLIANT_USDT_ADDRESS=$cwusdt \\
COMPLIANT_USDC_ADDRESS=$cwusdc \\
FOUNDRY_PROFILE=$forge_profile \\
forge script script/dex/DeployDODOPMMIntegration.s.sol:DeployDODOPMMIntegration \\
  --rpc-url $rpc \\
  --chain-id $chain_id \\
  --broadcast \\
  --private-key "\$PRIVATE_KEY" \\
  -vvv
jq -r '.transactions[] | select(.transactionType=="CREATE" and .contractName=="DODOPMMIntegration") | .contractAddress' \\
  broadcast/DeployDODOPMMIntegration.s.sol/$chain_id/run-latest.json
EOF
)

  create_cmd=$(cat <<EOF
cd $REPO_ROOT
DODO_PMM_INTEGRATION_ADDRESS=\${$integration_env:-REPLACE_WITH_DEPLOYED_INTEGRATION} \\
RPC_URL=$rpc \\
COMPLIANT_USDT_ADDRESS=$cwusdt \\
COMPLIANT_USDC_ADDRESS=$cwusdc \\
OFFICIAL_USDT_ADDRESS=$official_usdt \\
OFFICIAL_USDC_ADDRESS=$official_usdc \\
PRIVATE_KEY="\$PRIVATE_KEY" \\
bash scripts/setup-dodo-pools.sh
EOF
)

  verify_cmd=$(cat <<EOF
cast code --rpc-url $rpc $pool_usdc_expected
cast code --rpc-url $rpc $pool_usdt_expected
cast call --rpc-url $rpc \${$integration_env:-REPLACE_WITH_DEPLOYED_INTEGRATION} 'pools(address,address)(address)' $cwusdc $official_usdc
cast call --rpc-url $rpc \${$integration_env:-REPLACE_WITH_DEPLOYED_INTEGRATION} 'pools(address,address)(address)' $cwusdt $official_usdt
EOF
)

  if [[ $first_chain -eq 0 ]]; then
    echo "," >>"$json_file"
  fi
  first_chain=0

  cat >>"$json_file" <<EOF
    {
      "chainId": $chain_id,
      "network": $(json_escape "$network"),
      "rpc": $(json_escape "$rpc"),
      "integrationEnv": $(json_escape "$integration_env"),
      "integrationAddress": $(json_escape "$integration"),
      "integrationStatus": $(json_escape "$integration_status"),
      "dodoVendingMachine": {
        "env": $(json_escape "$dvm_env"),
        "address": $(json_escape "$dvm"),
        "status": $(json_escape "$dvm_status")
      },
      "officialTokens": {
        "USDC": {
          "env": $(json_escape "$official_usdc_env"),
          "address": $(json_escape "$official_usdc"),
          "status": $(json_escape "$official_usdc_status"),
          "symbol": $(json_escape "$(symbol_call "$rpc" "$official_usdc")")
        },
        "USDT": {
          "env": $(json_escape "$official_usdt_env"),
          "address": $(json_escape "$official_usdt"),
          "status": $(json_escape "$official_usdt_status"),
          "symbol": $(json_escape "$(symbol_call "$rpc" "$official_usdt")")
        }
      },
      "compliantTokens": {
        "cWUSDC": {
          "env": $(json_escape "$cwusdc_env"),
          "address": $(json_escape "$cwusdc"),
          "status": $(json_escape "$cwusdc_status"),
          "symbol": $(json_escape "$(symbol_call "$rpc" "$cwusdc")")
        },
        "cWUSDT": {
          "env": $(json_escape "$cwusdt_env"),
          "address": $(json_escape "$cwusdt"),
          "status": $(json_escape "$cwusdt_status"),
          "symbol": $(json_escape "$(symbol_call "$rpc" "$cwusdt")")
        }
      },
      "pairs": [
        {
          "pair": "cWUSDC/USDC",
          "expectedPoolAddress": $(json_escape "$pool_usdc_expected"),
          "poolCodeStatus": $(json_escape "$pool_usdc_status")
        },
        {
          "pair": "cWUSDT/USDT",
          "expectedPoolAddress": $(json_escape "$pool_usdt_expected"),
          "poolCodeStatus": $(json_escape "$pool_usdt_status")
        }
      ],
      "commands": {
        "deployIntegration": $(json_escape "$deploy_cmd"),
        "createPools": $(json_escape "$create_cmd"),
        "verifyPools": $(json_escape "$verify_cmd")
      }
    }
EOF

  {
    echo
    echo "## $network ($chain_id)"
    echo
    echo "| Item | Address | Status |"
    echo "| --- | --- | --- |"
    echo "| DODO vending machine | \`$dvm\` | \`$dvm_status\` |"
    echo "| Integration env \`$integration_env\` | \`${integration:-unset}\` | \`$integration_status\` |"
    echo "| Official USDC | \`$official_usdc\` | \`$official_usdc_status\` |"
    echo "| Official USDT | \`$official_usdt\` | \`$official_usdt_status\` |"
    echo "| cWUSDC | \`$cwusdc\` | \`$cwusdc_status\` |"
    echo "| cWUSDT | \`$cwusdt\` | \`$cwusdt_status\` |"
    echo "| Pool cWUSDC/USDC | \`$pool_usdc_expected\` | \`$pool_usdc_status\` |"
    echo "| Pool cWUSDT/USDT | \`$pool_usdt_expected\` | \`$pool_usdt_status\` |"
    echo
    echo "Deploy integration:"
    echo
    echo '```bash'
    echo "$deploy_cmd"
    echo '```'
    echo
    echo "Create pools:"
    echo
    echo '```bash'
    echo "$create_cmd"
    echo '```'
    echo
    echo "Verify pools:"
    echo
    echo '```bash'
    echo "$verify_cmd"
    echo '```'
  } >>"$md_file"
done < <(jq -c '.chains[]' "$BUNDLE_JSON")

{
  echo
  echo "  ]"
  echo "}"
} >>"$json_file"

jq . "$json_file" >"$OUT_JSON"
mv "$md_file" "$OUT_MD"
rm -f "$json_file"

echo "Wrote:"
echo "  $OUT_JSON"
echo "  $OUT_MD"
