#!/bin/bash
# 一次性驱动：逐个跑 query 并立即落盘到稳定文件名（aurora_direct 的 result_NN 序号每次运行重置会互相覆盖）
set -u
cd /data/workspace || exit 1
TMP=.kiro/cache/read-polaris-skill/tmp
RES=.kiro/cache/read-polaris-skill/result
D=/data/workspace/南部大区城市看板

run_one () {
  local q="$1" chart="$2" out="$3"
  echo "=== $q -> $out ==="
  local marker="/tmp/.marker_$q"
  touch "$marker"; sleep 1
  python3 skills/read-polaris-skill/scripts/aurora_direct.py chart --query-file "$TMP/$q" > "/tmp/$q.log" 2>&1
  local rc=$?
  if [ $rc -ne 0 ]; then echo "FAIL rc=$rc $q"; tail -8 "/tmp/$q.log"; return 1; fi
  local f
  f=$(find "$RES" -name "*_17040_$chart.json" -newer "$marker" | head -1)
  if [ -z "$f" ]; then echo "FAIL no fresh result file for $q"; tail -8 "/tmp/$q.log"; return 1; fi
  cp "$f" "$D/$out"
  echo "copied $(basename "$f") -> $out  $(wc -c < "$D/$out") bytes  $(grep -o 'refreshTime=[0-9: -]*' "/tmp/$q.log" | head -1)  $(grep -o 'rows=[0-9]*' "/tmp/$q.log" | head -1)"
  return 0
}

run_one q2_city_m.json 1764676014220 raw_city_m.json || exit 1
run_one q2_reg_m.json  1764676014220 raw_reg_m.json  || exit 1
run_one q2_reg_d.json  1765435183501 raw_reg_d.json  || exit 1
run_one q2_city_d.json 1765435183501 raw_city_d.json || exit 1
echo "ALL_DONE"
