#!/bin/bash
# 모멘텀·돌파·스캘핑 Optuna 순차 + --apply-best (2026-07-20 1일)
# 동시 실행 금지(RAM). 장전 적용용.
#
#   nohup bash scripts/run_optuna_3strat_apply_20260720.sh >> logs/optuna_3strat_apply_0720_master.log 2>&1 &
#   tail -f logs/optuna_3strat_apply_0720_master.log

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

START="${START:-2026-07-20}"
END="${END:-2026-07-20}"
MODE="${MODE:-fine}"
TRIALS="${TRIALS:-200}"
MIN_TRADES="${MIN_TRADES:-1}"
STRATEGIES="${STRATEGIES:-momentum breakout scalp}"
TS0="$(date +%Y%m%d_%H%M%S)"
MASTER="logs/optuna_3strat_apply_${START//-/}_${END//-/}_${TS0}_master.log"

{
  echo "======== Optuna 3전략 순차+apply-best 시작 $(date -Is) ========"
  echo "START=$START END=$END MODE=$MODE TRIALS=$TRIALS"
  echo "STRATEGIES=$STRATEGIES apply-best=ON orderbook=off n_jobs=1"
  echo "master_log=$MASTER"
  free -h | sed -n '1,2p'
} | tee -a "$MASTER"
echo "$MASTER" > logs/optuna_3strat_apply_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}_apply_${START//-/}_${ts}"
  log="logs/optuna_seq_${strat}_${MODE}_apply_${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"

  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" \
    --apply-best \
    > "$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 완료(+apply-best 시도). log=$log"
      grep -E "apply-best|DB 적용|env_config|스킵|best|순익|PnL" "$log" | tail -20 || true
    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
  echo "※ apply-best: 총손익≤0 이면 코드가 DB 적용 스킵할 수 있음 — 각 로그 grep apply"
} | tee -a "$MASTER"
