#!/usr/bin/env bash
# CI bootstrap script — runs under bash to support 'source' and bash-isms.
# Env vars ANVIL_RPC, CONTRACT_ENV, LOG_FILE, ONCHAIN_DIR, TXNBOT_FUND_VALUE,
# TXNBOT_ADDRESS, TXNBOT_PRIVATE_KEY must be set before calling this script.
set -euo pipefail

echo "=== Foundry version ==="
forge --version
cast --version

# Source shared bootstrap functions
source scripts/bootstrap-common.sh

echo "=== Waiting for Anvil ==="
wait_for_rpc

echo "=== Deploying contracts ==="
run_forge_script
extract_addresses

echo "=== Contract Deployment Complete ==="
echo "KRAIKEN: $KRAIKEN"
echo "STAKE: $STAKE"
echo "LIQUIDITY_MANAGER: $LIQUIDITY_MANAGER"
echo "DEPLOY_BLOCK: $DEPLOY_BLOCK"

# Build kraiken-lib BEFORE writing contracts.env
# (services wait for contracts.env, so kraiken-lib must be ready first)
echo "=== Building kraiken-lib (shared dependency) ==="
cd kraiken-lib
npm ci --ignore-scripts
if [[ -f ../scripts/sync-tax-rates.mjs ]]; then
  node ../scripts/sync-tax-rates.mjs
fi
./node_modules/.bin/tsc
cd ..

# Get current block number as start block
START_BLOCK=$(cast block-number --rpc-url "$ANVIL_RPC")

# Write contracts.env with CI-specific extra vars
{
  echo "KRAIKEN=$KRAIKEN"
  echo "STAKE=$STAKE"
  echo "LIQUIDITY_MANAGER=$LIQUIDITY_MANAGER"
  echo "START_BLOCK=$START_BLOCK"
  echo "PONDER_RPC_URL_1=http://anvil:8545"
  echo "DATABASE_URL=postgres://ponder:ponder_local@postgres:5432/ponder_local"
  echo "RPC_URL=http://anvil:8545"
} > "$CONTRACT_ENV"

# Write deployments-local.json for E2E tests
write_deployments_json "$ONCHAIN_DIR/deployments-local.json"
echo "=== deployments-local.json written ==="
cat "$ONCHAIN_DIR/deployments-local.json"

echo "=== Bootstrapping VWAP ==="
bootstrap_vwap

echo "=== Funding LiquidityManager ==="
fund_liquidity_manager

echo "=== Seeding application state (initial swap) ==="
seed_application_state

echo "=== Funding txnBot ==="
fund_txn_bot_wallet

echo "TXNBOT_PRIVATE_KEY=$TXNBOT_PRIVATE_KEY" >> "$CONTRACT_ENV"

echo "=== Bootstrap complete ==="
