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

SCRIPT_VERSION="tune_new_downloaded_npz_v1_2026_05_04"
echo "[script_version] $0 SCRIPT_VERSION=${SCRIPT_VERSION}"

# Capacity-aware tune runner for newly imported full-cycle NPZ datasets.
#
# Usage:
#   bash dex_platform/scripts/tune_new_downloaded_npz_v1.sh
#   POOL_FILTER=bio_usdc_apr_full,bio_usdc_may bash dex_platform/scripts/tune_new_downloaded_npz_v1.sh
#   DRY_RUN=1 bash dex_platform/scripts/tune_new_downloaded_npz_v1.sh

BACKTEST="${BACKTEST:-dex_platform/backtest/cl_fee_replay_fast_npz_v3.py}"
OUT_ROOT="${OUT_ROOT:-DEX_REPORTS/new_downloaded_npz_tune_v1}"
JOBS="${JOBS:-8}"
DRY_RUN="${DRY_RUN:-0}"
POOL_FILTER="${POOL_FILTER:-}"

CAPITAL_GRID_DEFAULT="${CAPITAL_GRID_DEFAULT:-25,50,100,200,300,600,1000}"
GRID_LOWER_DEFAULT="${GRID_LOWER_DEFAULT:-5,10,20,30,40,50,60,70,80}"
GRID_UPPER_DEFAULT="${GRID_UPPER_DEFAULT:-0.5,1,2,5,10,20,30,50,80,120}"
REBALANCE_GRID_DEFAULT="${REBALANCE_GRID_DEFAULT:-none:0,periodic:168,periodic:336,periodic:504}"

mkdir -p "${OUT_ROOT}"

want_pool() {
  local name="$1"
  if [[ -z "${POOL_FILTER}" ]]; then
    return 0
  fi
  case ",${POOL_FILTER}," in
    *",${name},"*) return 0 ;;
    *) return 1 ;;
  esac
}

run_npz() {
  local name="$1"
  local npz="$2"
  local fee="$3"
  local capital_grid="${4:-${CAPITAL_GRID_DEFAULT}}"
  local grid_lower="${5:-${GRID_LOWER_DEFAULT}}"
  local grid_upper="${6:-${GRID_UPPER_DEFAULT}}"
  local rebalance_grid="${7:-${REBALANCE_GRID_DEFAULT}}"

  if ! want_pool "${name}"; then
    echo "[skip_filter] ${name}"
    return 0
  fi
  if [[ ! -f "${npz}" ]]; then
    echo "[skip_missing] ${name} npz=${npz}" >&2
    return 0
  fi

  local out_dir="${OUT_ROOT}/${name}"
  local meta="${npz%.npz}.meta.json"
  local time_from="${TIME_FROM:-}"
  local time_to="${TIME_TO:-}"
  if [[ -z "${time_from}" || -z "${time_to}" ]]; then
    if [[ ! -f "${meta}" ]]; then
      echo "[skip_missing_meta] ${name} meta=${meta}" >&2
      return 0
    fi
    local range
    range="$(
      python3 -c "import datetime as dt,json; m=json.load(open('${meta}')); print(dt.datetime.fromtimestamp(int(m['timestamp_start']), tz=dt.timezone.utc).isoformat().replace('+00:00','Z') + ' ' + dt.datetime.fromtimestamp(int(m['timestamp_end']), tz=dt.timezone.utc).isoformat().replace('+00:00','Z'))"
    )"
    time_from="${range%% *}"
    time_to="${range##* }"
  fi

  local cmd=(
    python3 "${BACKTEST}"
    --jobs "${JOBS}"
    --fast-core
    --npz "${npz}"
    --out-dir "${out_dir}"
    --fee-rates "metadata:${fee}"
    --time-from "${time_from}"
    --time-to "${time_to}"
    --capital-mode grid
    --capital-grid "${capital_grid}"
    --grid-lower "${grid_lower}"
    --grid-upper "${grid_upper}"
    --rebalance-grid "${rebalance_grid}"
    --target-mdd-pct 25
    --max-avg-liquidity-share-pct 3
    --max-p95-liquidity-share-pct 5
    --max-p99-liquidity-share-pct 10
    --max-liquidity-share-pct 25
  )

  echo "[run] ${name} npz=${npz} fee=${fee} out=${out_dir}"
  if [[ "${DRY_RUN}" == "1" ]]; then
    printf '[dry_run]'
    printf ' %q' "${cmd[@]}"
    printf '\n'
    return 0
  fi
  "${cmd[@]}"
}

# BIO/USDC new monthly/segment datasets.
run_npz "bio_usdc_apr_full_corrected" "DEX_DATA/fast_npz/bio_usdc_apr2026_full_corrected.npz" "0.003"
run_npz "bio_usdc_apr_monthly_table" "DEX_DATA/fast_npz/bio_usdc_03_2026-04-01_00-00-00Z.npz" "0.003"
run_npz "bio_usdc_combined_apr17_may3" "DEX_DATA/fast_npz/bio_usdc_combined_apr17_may3.npz" "0.003"
run_npz "bio_usdc_feb_mar_full" "DEX_DATA/fast_npz/bio_usdc_feb_mar_full.npz" "0.003"
run_npz "bio_usdc_may_full" "DEX_DATA/fast_npz/bio_usdc_may2026_full.npz" "0.003"

# New CHECK 0.25% monthly table pool.
run_npz "check_usdc_025_new_apr" "DEX_DATA/fast_npz/check_usdc_025_new_2026-04-01_00-00-00Z.npz" "0.0025" \
  "25,50,100,200,300,600,1000,1500,2000" \
  "20,30,40,50,60,70,80,90" \
  "0.1,0.5,1,2,5,10,20,30" \
  "none:0,periodic:168,periodic:336,periodic:504"

# Other imported candidates.
run_npz "synd_usdc_apr_full2" "DEX_DATA/fast_npz/synd_usdc_apr_full2.npz" "0.0095"
run_npz "synd_usdc_monthly_corrected" "DEX_DATA/fast_npz/base_SYND_USDC_monthly_corrected.npz" "0.0095"
run_npz "aero_weth_1pct_monthly" "DEX_DATA/fast_npz/aero_weth_1pct_monthly.npz" "0.003016"
run_npz "bio_weth_005_monthly" "DEX_DATA/fast_npz/bio_weth_005_monthly.npz" "0.0025"
run_npz "bnkr_weth_monthly" "DEX_DATA/fast_npz/bnkr_weth_monthly.npz" "0.002732"

echo "[done] reports in ${OUT_ROOT}"
