#!/bin/bash
# [zemlya-report-e2e] Оркестратор E2E цикла отчёта «Земля без риска».
# Запуск:  bash zw_report_e2e.sh "<КН>" "free,ai"
# Делает: mint admin-token → INSERT тестовых reports → polling → дамп полей →
#         Playwright-скриншоты на mini → scp PNG локально → grep маркеров → cleanup.
# Оставляет PNG в /tmp/zw_e2e_shots_local/ (Read их для контроля вёрстки).
set -uo pipefail

KN="${1:?Укажи кадастровый номер: bash zw_report_e2e.sh '47:14:0302006:4173' 'free,ai'}"
MODES="${2:-free,ai}"
HOST="${ZW_HOST:-cebers_mini@Cebers-mini.local}"  # mDNS — устойчиво к смене DHCP-IP (был хардкод .107)
KEY="$HOME/.ssh/id_ed25519"
SKILL_DIR="$(cd "$(dirname "$0")" && pwd)"
LOCAL_OUT="/tmp/zw_e2e_shots_local"
REMOTE_OUT="/tmp/zw_e2e_shots"
sshm() { ssh -i "$KEY" -o ConnectTimeout=12 "$HOST" "$@"; }

echo "== [1] mint admin token =="
TOKEN=$(sshm 'cd ~/Services/zemlya-web/backend && venv/bin/python -c "from app.auth.jwt import issue; print(issue(1005954706,3))"')
[ ${#TOKEN} -lt 50 ] && { echo "FAIL: токен не сминтился ($TOKEN)"; exit 1; }
echo "   token len=${#TOKEN}"

echo "== [2] freshness check + insert reports на $KN =="
RECENT=$(sshm "sqlite3 ~/Services/zemlya-bot/data/db/zemlya_bot.db \"SELECT COUNT(*) FROM reports WHERE cadastral_number='$KN' AND created_at>datetime('now','-24 hours') AND result_json IS NOT NULL;\"")
[ "$RECENT" != "0" ] && echo "   ⚠ есть отчёт за 24ч → reuse-cache может скопировать старый result_json. Возьми другой КН для проверки СВЕЖИХ полей."

FREE_ID=""; AI_ID=""
IFS=',' read -ra M <<< "$MODES"
for mode in "${M[@]}"; do
  paid=0; [ "$mode" != "free" ] && paid=1
  id=$(sshm "sqlite3 ~/Services/zemlya-bot/data/db/zemlya_bot.db \"INSERT INTO reports(user_id,cadastral_number,created_at,is_paid,report_mode) VALUES (3,'$KN',datetime('now'),$paid,'$mode'); SELECT last_insert_rowid();\"")
  echo "   $mode → report id=$id"
  [ "$mode" = "free" ] && FREE_ID=$id
  [ "$mode" = "ai" ] && AI_ID=$id
done

echo "== [3] polling готовности (до ~6 мин) =="
for i in $(seq 1 36); do
  ok=1
  if [ -n "$FREE_ID" ]; then j=$(sshm "sqlite3 ~/Services/zemlya-bot/data/db/zemlya_bot.db \"SELECT CASE WHEN result_json IS NOT NULL AND length(result_json)>300 THEN 1 ELSE 0 END FROM reports WHERE id=$FREE_ID;\""); [ "$j" = "1" ] || ok=0; fi
  if [ -n "$AI_ID" ]; then a=$(sshm "sqlite3 ~/Services/zemlya-bot/data/db/zemlya_bot.db \"SELECT COALESCE((SELECT status FROM ai_reports WHERE report_id=$AI_ID ORDER BY id DESC LIMIT 1),'none');\""); [ "$a" = "completed" ] || [ "$a" = "done" ] || ok=0; fi
  echo "   [$i] free=${FREE_ID:+$(sshm "sqlite3 ~/Services/zemlya-bot/data/db/zemlya_bot.db \"SELECT CASE WHEN result_json IS NOT NULL THEN 1 ELSE 0 END FROM reports WHERE id=$FREE_ID;\"")} ai_status=${a:-n/a}"
  [ "$ok" = "1" ] && { echo "   готово"; break; }
  sleep 12
done

echo "== [4] дамп ключевых полей (новый КН должен иметь cache_used=None) =="
TID="${AI_ID:-$FREE_ID}"
sshm "sqlite3 ~/Services/zemlya-bot/data/db/zemlya_bot.db \"SELECT result_json FROM reports WHERE id=$TID;\"" | python3 -c '
import sys,json
d=json.load(sys.stdin); inf=d.get("infrastructure",{}); s=inf.get("summary",{})
print("  borders_established:", d.get("borders_established"))
print("  cache_used:", d.get("cache_used"))
for k,lbl in [("cemeteries","🪦"),("landfills","🗑"),("industrial_zones","🏭"),("wastewater_plants","💧")]:
    its=inf.get(k,[]); print(f"  {lbl} {k}: {len(its)}", [(x.get("name"),x.get("distance_km")) for x in its[:2]])
print("  nearest_locality:", s.get("nearest_locality_name"), s.get("nearest_locality_km"))
' 2>/dev/null || echo "  (не удалось распарсить result_json)"

echo "== [5] Playwright скриншоты на mini =="
scp -q -i "$KEY" "$SKILL_DIR/shot_e2e.py" "$HOST:/tmp/zw_shot_e2e.py"
sshm "rm -rf $REMOTE_OUT; ZW_TOKEN='$TOKEN' FREE_ID='$FREE_ID' AI_ID='$AI_ID' ZW_OUT='$REMOTE_OUT' /usr/bin/python3 /tmp/zw_shot_e2e.py 2>&1 | grep -vE '^goto warn'"

echo "== [6] scp PNG локально + grep маркеров в сыром ai-html =="
rm -rf "$LOCAL_OUT"; mkdir -p "$LOCAL_OUT"
scp -q -i "$KEY" "$HOST:$REMOTE_OUT/*.png" "$LOCAL_OUT/" 2>/dev/null
ls -1 "$LOCAL_OUT"/ 2>/dev/null | sed 's/^/   PNG: /'
if [ -n "$AI_ID" ]; then
  UA="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"
  sshm "curl -s 'http://127.0.0.1:20141/api/reports/$AI_ID/ai-html' -H \"Cookie: zw_session=$TOKEN\" -A '$UA'" > /tmp/zw_ai_html.html
  echo "   ai-html bytes: $(wc -c < /tmp/zw_ai_html.html)"
fi

echo "== [7] cleanup тестовых отчётов =="
DEL_IDS=$(echo "$FREE_ID $AI_ID" | tr ' ' ',' | sed 's/,$//;s/^,//')
sshm "sqlite3 ~/Services/zemlya-bot/data/db/zemlya_bot.db \"DELETE FROM ai_reports WHERE report_id IN ($DEL_IDS); DELETE FROM reports WHERE id IN ($DEL_IDS);\"; echo cleaned"

echo ""
echo "ГОТОВО. Дальше Claude: Read каждый PNG из $LOCAL_OUT (контроль вёрстки),"
echo "проверь маркеры новых полей в выводе [5]/[6], при изменении фич — актуализируй доки"
echo "(сайт /help+лендинг, бот /help, Obsidian Changelog/Decisions). См. DOCS_CHECKLIST.md."
