#!/usr/bin/env bash
# Backfill market candles in quarterly chunks to stay within nginx proxy timeouts.
# Each (instrument, interval, quarter) is a separate request; idempotent via ON CONFLICT DO NOTHING.
set -euo pipefail

# Spot instruments (exchange: binance_spot)
declare -a spot_instruments=()
spot_instruments+=( BTCUSDC )
spot_instruments+=( ETHUSDC )
spot_instruments+=( SOLUSDC )

# USD-M futures perpetuals (exchange: binance_futures_usd)
declare -a futures_um_instruments=()
futures_um_instruments+=( BTCUSDC )
futures_um_instruments+=( ETHUSDC )
futures_um_instruments+=( SOLUSDC )

declare -a intervals=()
intervals+=( 1m )
intervals+=( 5m )
intervals+=( 15m )
intervals+=( 1h )
intervals+=( 4h )
intervals+=( 1d )

range_from="2025-01-01"
range_to="2026-03-08"

# Generate quarter boundaries between two dates (YYYY-MM-DD).
# Prints pairs of lines: chunk_from chunk_to (ISO-8601 with Z suffix).
quarter_chunks() {
  local from="$1" to="$2"
  local cursor="$from"
  while [[ "$cursor" < "$to" ]]; do
    local year month next_month next_year chunk_to
    year="${cursor%%-*}"
    month="${cursor#*-}"; month="${month%%-*}"
    # Advance by 3 months
    next_month=$(( 10#$month + 3 ))
    next_year=$year
    if (( next_month > 12 )); then
      next_month=$(( next_month - 12 ))
      next_year=$(( next_year + 1 ))
    fi
    chunk_to=$(printf "%04d-%02d-01" "$next_year" "$next_month")
    # Clamp to overall range_to
    if [[ "$chunk_to" > "$to" ]]; then
      chunk_to="$to"
    fi
    echo "${cursor}T00:00:00Z"
    echo "${chunk_to}T00:00:00Z"
    cursor="$chunk_to"
  done
}

backfill_group() {
  local exchange="$1"
  local -n _instruments="$2"
  local group_total=0

  echo "==> Backfilling ${exchange}"

  mapfile -t chunks < <(quarter_chunks "$range_from" "$range_to")

  for instrument in "${_instruments[@]}"; do
    for interval in "${intervals[@]}"; do
      local interval_inserted=0
      local i=0
      while (( i < ${#chunks[@]} )); do
        local chunk_from="${chunks[$i]}"
        local chunk_to="${chunks[$((i+1))]}"
        i=$(( i + 2 ))
        local response
        response=$(curl -k -s --max-time 300 -X POST \
          https://dev.swym.hanzalova.internal/api/v1/market-candles/backfill \
          -H 'Content-Type: application/json' \
          -d "{\"exchange\":\"${exchange}\",\"symbol\":\"${instrument}\",\"interval\":\"${interval}\",\"from\":\"${chunk_from}\",\"to\":\"${chunk_to}\"}")
        local inserted
        inserted=$(echo "${response}" | jq -r '.inserted // empty' 2>/dev/null)
        if [[ -n "$inserted" ]]; then
          interval_inserted=$(( interval_inserted + inserted ))
          echo "  ok  ${instrument} ${interval} ${chunk_from}→${chunk_to}: ${inserted} inserted"
        else
          echo "  err ${instrument} ${interval} ${chunk_from}→${chunk_to}: ${response}"
        fi
      done
      echo "${instrument} ${interval}: ${interval_inserted} total inserted"
      group_total=$(( group_total + interval_inserted ))
    done
  done

  echo "==> ${exchange}: ${group_total} candles inserted"
  echo "$group_total"
}

spot_total=$(backfill_group "binance_spot" spot_instruments | tail -1)
futures_um_total=$(backfill_group "binance_futures_usd" futures_um_instruments | tail -1)

grand_total=$(( spot_total + futures_um_total ))
echo "==> Done. ${grand_total} candles inserted across all instruments and intervals."
