#!/usr/bin/env bash
# Deploy Vault System, then ac* / vdc* / sdc* vaults (DeployAcVdcSdcVaults).
# Run from a host that can reach Chain 138 RPC (e.g. on same LAN as 192.168.11.211).
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
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:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi


RPC_URL="${RPC_URL_138:-http://192.168.11.211:8545}"
GAS_PRICE="${GAS_PRICE:-1000000000}"
CHAIN_ID="${CHAIN_ID:-138}"

if [ -z "$PRIVATE_KEY" ]; then
    echo "Error: PRIVATE_KEY not set (e.g. in smom-dbis-138/.env)"
    exit 1
fi
if [[ ! "$PRIVATE_KEY" =~ ^0x ]]; then
    export PRIVATE_KEY="0x$PRIVATE_KEY"
fi

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "1. Deploy Vault System (DeployVaultSystem.s.sol)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "RPC: $RPC_URL  Chain: $CHAIN_ID  Gas: $GAS_PRICE"
echo ""

forge script script/deploy/vault/DeployVaultSystem.s.sol:DeployVaultSystem \
    --rpc-url "$RPC_URL" \
    --broadcast \
    --with-gas-price "$GAS_PRICE"

# Resolve VaultFactory address from broadcast (last contract creation)
RUN_JSON=""
for candidate in \
    "broadcast/DeployVaultSystem.s.sol/$CHAIN_ID/run-latest.json" \
    "broadcast/vault/DeployVaultSystem.s.sol/$CHAIN_ID/run-latest.json" \
    "broadcast/script/deploy/vault/DeployVaultSystem.s.sol/$CHAIN_ID/run-latest.json"; do
    if [ -f "$candidate" ]; then
        RUN_JSON="$candidate"
        break
    fi
done
if [ -z "$RUN_JSON" ] || [ ! -f "$RUN_JSON" ]; then
    echo "Could not find broadcast file. Set VAULT_FACTORY_ADDRESS manually and run:"
    echo "  VAULT_FACTORY_ADDRESS=0x... forge script script/deploy/vault/DeployAcVdcSdcVaults.s.sol:DeployAcVdcSdcVaults --rpc-url \$RPC_URL_138 --broadcast --with-gas-price 1000000000"
    exit 1
fi

VAULT_FACTORY_ADDRESS=$(jq -r '[.transactions[] | select(.contractAddress != null) | .contractAddress] | last' "$RUN_JSON")
if [ -z "$VAULT_FACTORY_ADDRESS" ] || [ "$VAULT_FACTORY_ADDRESS" = "null" ]; then
    echo "Could not parse Vault Factory address from $RUN_JSON. Set VAULT_FACTORY_ADDRESS and run DeployAcVdcSdcVaults manually."
    exit 1
fi

export VAULT_FACTORY_ADDRESS
echo ""
echo "Vault Factory address: $VAULT_FACTORY_ADDRESS"
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "2. Deploy ac* / vdc* / sdc* (DeployAcVdcSdcVaults.s.sol)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Optional: set CUSDC_ADDRESS_138, CUSDT_ADDRESS_138 (or COMPLIANT_USDC_ADDRESS, COMPLIANT_USDT_ADDRESS) to create vaults for those tokens."
echo ""

forge script script/deploy/vault/DeployAcVdcSdcVaults.s.sol:DeployAcVdcSdcVaults \
    --rpc-url "$RPC_URL" \
    --broadcast \
    --with-gas-price "$GAS_PRICE"

echo ""
echo "Done. Record Vault Factory and any new vault/deposit/debt token addresses in .env and config/smart-contracts-master.json if needed."
