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

ROOT="/var/www/vps2.happyuser.info/top/callme_overnight_20260601"
PY="/home/simple_user/.pyenv/versions/3.8.18/bin/python3.8"
COORD="$ROOT/output/coordinator"
OUT_BASE="$ROOT/output/heavy_runs"
LOCKDIR="$COORD/heavy_job.lock"
STOP="$ROOT/STOP"

mkdir -p "$COORD" "$OUT_BASE"

if ! mkdir "$LOCKDIR" 2>/dev/null; then
  echo "Heavy tune already locked at $LOCKDIR"
  exit 0
fi
trap 'rm -rf "$LOCKDIR"' EXIT

RUN_ID="heavy_$(date -u +%Y%m%dT%H%M%SZ)"
OUT="$OUT_BASE/$RUN_ID"
mkdir -p "$OUT"

printf '{"state":"running","run_dir":"%s","started_at":"%s","policy":"one heavy tune at a time, no live orders"}\n' \
  "$OUT" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$COORD/HEAVY_CURRENT_RUN.json"

CPUSET="0"
if command -v taskset >/dev/null 2>&1; then
  RUNNER=(taskset -c "$CPUSET")
else
  RUNNER=()
fi

if command -v ionice >/dev/null 2>&1; then
  IO=(ionice -c2 -n7)
else
  IO=()
fi

"${RUNNER[@]}" "${IO[@]}" nice -n 15 "$PY" "$ROOT/callme_dca_v21_overnight_runner.py" \
  --positions "$ROOT/input/position_history_normalized.csv" \
  --ohlcv-cache "$ROOT/input/ohlcv_1m_cache" \
  --out-dir "$OUT" \
  --initial-equity 500 \
  --max-target-notional 500 \
  --min-free-mb 4096 \
  --stop-file "$STOP" \
  --heavy

"$PY" "$ROOT/callme_cleanup_heavy_output.py" \
  --out-dir "$OUT" \
  --top-per-group 25 \
  --coord-dir "$COORD"

printf '{"state":"complete","run_dir":"%s","completed_at":"%s","retention":"summary, selected_group_configs, group_top_metrics, report/status only"}\n' \
  "$OUT" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$COORD/HEAVY_CURRENT_RUN.json"
