#!/bin/bash
# 4전략 Optuna 순차 실행 (동시 X — RAM 13G + 틱 2일 로딩 시 병렬은 OOM/스왑 위험)
# 기간: 2026-07-15 ~ 2026-07-16 (거래일) · apply-best 없음 · 호가 OFF
#
# 사용:
#   nohup bash scripts/run_optuna_4strat_seq_20260715_16.sh >> logs/optuna_4strat_seq_master.log 2>&1 &
#   tail -f logs/optuna_4strat_seq_master.log
#   # 전략별: tail -f logs/optuna_seq_<strategy>_*.log
#
# 환경변수 오버라이드 예:
#   MODE=coarse TRIALS=100 STRATEGIES="tail scalp" bash scripts/run_optuna_4strat_seq_20260715_16.sh

set -euo pipefail
cd /home/hoon/kis_bot
mkdir -p logs kis_trader/backtest/results

START="${START:-2026-07-15}"
END="${END:-2026-07-16}"
MODE="${MODE:-fine}"
TRIALS="${TRIALS:-200}"
MIN_TRADES="${MIN_TRADES:-1}"
# 공백 구분: tail momentum breakout scalp
STRATEGIES="${STRATEGIES:-tail momentum breakout scalp}"
TS0="$(date +%Y%m%d_%H%M%S)"
MASTER="logs/optuna_4strat_seq_${START}_${END}_${TS0}_master.log"

{
  echo "======== Optuna 4전략 순차 시작 $(date -Is) ========"
  echo "START=$START END=$END MODE=$MODE TRIALS=$TRIALS"
  echo "STRATEGIES=$STRATEGIES"
  echo "apply-best=OFF orderbook=off n_jobs=1"
  echo "master_log=$MASTER"
  free -h | sed -n '1,2p'
  df -h / | tail -1
} | tee -a "$MASTER"
echo "$MASTER" > logs/optuna_4strat_seq_latest_master.logpath

run_one() {
  local strat="$1"
  local ts study log sort_by
  ts="$(date +%Y%m%d_%H%M%S)"
  study="${strat}_${MODE}_${START//-/}_${END//-/}_${ts}"
  log="logs/optuna_seq_${strat}_${MODE}_${ts}.log"
  sort_by="pnl"
  if [[ "$strat" == "momentum" || "$strat" == "scalp" ]]; then
    sort_by="score"
  fi

  {
    echo ""
    echo "-------- $(date -Is) START $strat study=$study --------"
    echo "LOG=$log"
  } | tee -a "$MASTER"
  echo "$log" > "logs/optuna_seq_${strat}_latest.logpath"
  echo "$study" > "logs/optuna_seq_${strat}_latest.study"

  # --apply-best 없음 (기본 미적용)
  set +e
  python3 -u kis_trader/backtest/param_search_optuna.py \
    --strategy "$strat" \
    --mode "$MODE" \
    --start "$START" \
    --end "$END" \
    --trials "$TRIALS" \
    --min_trades "$MIN_TRADES" \
    --sort-by "$sort_by" \
    --orderbook-filter off \
    --no-progress \
    --n-jobs 1 \
    --study-name "$study" \
    > "$log" 2>&1
  local rc=$?
  set -e

  {
    echo "-------- $(date -Is) END $strat rc=$rc --------"
    if [[ $rc -ne 0 ]]; then
      echo "⚠️ $strat 실패(rc=$rc) — 다음 전략 계속. tail: $log"
    else
      echo "✅ $strat 완료. log=$log"
    fi
    free -h | sed -n '2p'
  } | tee -a "$MASTER"

  return 0
}

for s in $STRATEGIES; do
  run_one "$s"
done

{
  echo ""
  echo "======== 전부 종료 $(date -Is) ========"
  echo "master=$MASTER"
  for s in $STRATEGIES; do
    echo "  $s logpath=$(cat logs/optuna_seq_${s}_latest.logpath 2>/dev/null || echo '?')"
    echo "  $s study=$(cat logs/optuna_seq_${s}_latest.study 2>/dev/null || echo '?')"
  done
} | tee -a "$MASTER"
