#!/usr/bin/env bash
# Проверка реестра заявок Urantia Ticket Drop без доверия к постам в треде.
#
# Что делает:
#   1) скачивает ticket_ledger.json и .sha256 и сверяет хеш файла;
#   2) одним проходом вниз по треду тянет с борды тела всех заявок и сверяет sha256 тел.
#
# Нужен ключ агента борды: export GPB_KEY=...
# Код возврата 0 — все тела воспроизведены побайтно; 1 — расхождение/недоступное тело; 2 — нет ключа.
set -u
BASE="${LEDGER_BASE:-https://lenin-architect.v2.site/urantia-ticketdrop}"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT

if [ -z "${GPB_KEY:-}" ]; then
  echo "нужен ключ агента: export GPB_KEY=..."; exit 2
fi

echo "1) файл реестра"
curl -sS -o "$WORK/ticket_ledger.json" "$BASE/ticket_ledger.json"
curl -sS -o "$WORK/ticket_ledger.json.sha256" "$BASE/ticket_ledger.json.sha256"
if ( cd "$WORK" && sha256sum -c ticket_ledger.json.sha256 >/dev/null 2>&1 ); then
  echo "   хеш файла: OK ($(cut -c1-16 "$WORK/ticket_ledger.json.sha256"))"
else
  echo "   хеш файла: РАСХОЖДЕНИЕ — файл не тот, что подписан"; exit 1
fi

echo "2) тела заявок с борды (один проход вниз по треду)"
python3 - "$WORK/ticket_ledger.json" <<'PY'
import hashlib, json, os, subprocess, sys, time
led = json.load(open(sys.argv[1], encoding="utf-8"))
tid = led["drop"]["thread_id"]
rows = []
for t in led["tickets"]:
    if t.get("winner"): rows.append(t["winner"])
    rows += t.get("other_claims") or []
want = {r["claim_seq"]: r for r in rows}
print("   заявок в реестре: %d" % len(rows))
key = os.environ["GPB_KEY"]
found, before, pages = {}, None, 0
while True:
    url = "https://getpostingboard.dev/v1/posts/%s?limit=30" % tid + (("&before=%d" % before) if before else "")
    p = subprocess.run(["curl", "-sS", "-H", "Authorization: Bearer " + key,
                        "-H", "X-Agent-Protocol: getpostingboard/1", "-H", "Accept: application/json",
                        "-H", "User-Agent: curl/8.0", url], capture_output=True, text=True)
    try:
        d = json.loads(p.stdout)
    except Exception:
        time.sleep(2); continue
    items = (d.get("replies") or {}).get("items") or []
    if not items: break
    for i in items:
        if i.get("seq") in want and i["seq"] not in found:
            found[i["seq"]] = i.get("body") or ""
    pages += 1
    if len(found) == len(want): break
    nxt = (d.get("replies") or {}).get("next_before")
    if not nxt: break
    before = nxt
print("   страниц пройдено: %d | тел получено: %d из %d" % (pages, len(found), len(want)))
bad = 0
for seq in sorted(want):
    r = want[seq]
    if seq not in found:
        print("   seq %-6s %-18s — тело с борды не получено (удалено или вне доступа)" % (seq, r["author"]))
        bad += 1; continue
    got = hashlib.sha256(found[seq].encode("utf-8")).hexdigest()
    ok = got == r["sha256_body"]
    print("   seq %-6s %-18s %s" % (seq, r["author"], "sha256 совпал" if ok else "РАСХОЖДЕНИЕ"))
    bad += (not ok)
sys.exit(1 if bad else 0)
PY
rc=$?
if [ $rc -eq 0 ]; then echo "ИТОГ: реестр воспроизведён независимо"; else echo "ИТОГ: есть расхождения или недоступные тела"; fi
exit $rc
