#!/usr/bin/env bash
# Phase 2 꼬리 파라서치: 5월 fast → 5~6월 coarse (순차 실행)
set -euo pipefail
cd "$(dirname "$0")/../.."
PY=".venv/bin/python"
export TAIL_PARAM_SEARCH_ENTRY_MODE=align
LOG_DIR="kis_trader/backtest/results"
TS="$(date +%Y%m%d_%H%M%S)"
LOG="$LOG_DIR/_bg_tail_phase2_${TS}.log"

exec >"$LOG" 2>&1
echo "=== Phase2 tail search start $TS ==="

echo "--- [1/2] fast 2026-05-01 ~ 2026-05-31 ---"
$PY -u -m kis_trader.backtest.tail_param_search \
  --mode fast --start 2026-05-01 --end 2026-05-31 \
  --min_win_rate 0 --min_trades 3 --top 30

echo "--- [2/2] coarse 2026-05-01 ~ 2026-06-08 (env slim) ---"
export TAIL_GRID_COARSE_MAX_DAILY_CHG='20,25,30'
export TAIL_GRID_COARSE_MIN_DROP_RATE='0.02,0.03'
export TAIL_GRID_COARSE_MIN_RECOVERY_RATIO='0.4,0.5'
export TAIL_GRID_COARSE_TAIL_RATIO_MIN='1.0,1.5'
export TAIL_GRID_COARSE_MAX_REC_3M='0.85'
export TAIL_GRID_COARSE_SHOULDER_MIN_HIGH='0.003,0.005'
export TAIL_GRID_COARSE_SHOULDER_CUT_PCT='0.002'
export TAIL_GRID_COARSE_STOP_ATR_MULT='1.5,2.0'
export TAIL_GRID_COARSE_TARGET_ATR_MULT='1.5,2.0'
export TAIL_GRID_COARSE_ATR_TP_MAX_PCT='1.0'
export TAIL_GRID_COARSE_MAX_LOSS_KRW='200000'
export TAIL_GRID_COARSE_LIMIT_ATR_MULT='1.5'

$PY -u -m kis_trader.backtest.tail_param_search \
  --mode coarse --start 2026-05-01 --end 2026-06-08 \
  --min_win_rate 0 --min_trades 3 --top 50

echo "=== Phase2 tail search done ==="
