#!/usr/bin/env bash
set -euo pipefail
# Remote packet: /opt/teleo-eval/workspaces/deploy-infra/docs/reports/leo-working-state-20260709/telegram-visible-direct-claim-authorization-packet-current.json
# Readback covers deploy head, .last-deploy-sha, leoclean-gateway.service, and DB counts:
# public.claims, public.sources, public.claim_evidence, public.claim_edges, kb_stage.kb_proposals
run_ssh() {
  ssh -i /Users/user/.ssh/livingip_hetzner_20260604_ed25519 -o BatchMode=yes -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 root@77.42.65.182 "$1"
}
DEPLOY_READBACK="$(run_ssh 'cd /opt/teleo-eval/workspaces/deploy-infra && printf '"'"'deploy_head='"'"' && git rev-parse HEAD && printf '"'"'last_deploy_sha='"'"' && cat /opt/teleo-eval/.last-deploy-sha && printf '"'"'\n'"'"' && if [ -s /opt/teleo-eval/workspaces/deploy-infra/docs/reports/leo-working-state-20260709/telegram-visible-direct-claim-authorization-packet-current.json ]; then printf '"'"'packet_present=true\npacket_bytes='"'"'; wc -c < /opt/teleo-eval/workspaces/deploy-infra/docs/reports/leo-working-state-20260709/telegram-visible-direct-claim-authorization-packet-current.json; else printf '"'"'packet_present=false\npacket_bytes=0\n'"'"'; fi')"
SERVICE_READBACK="$(run_ssh 'systemctl show leoclean-gateway.service -p ActiveState -p SubState -p MainPID -p NRestarts -p ExecMainStartTimestamp --no-pager')"
DB_COUNTS_READBACK="$(run_ssh 'docker exec teleo-pg psql -U postgres -d teleo -At -q -c '"'"'select jsonb_build_object(
  '"'"'"'"'"'"'"'"'public.claims'"'"'"'"'"'"'"'"', (select count(*) from public.claims),
  '"'"'"'"'"'"'"'"'public.sources'"'"'"'"'"'"'"'"', (select count(*) from public.sources),
  '"'"'"'"'"'"'"'"'public.claim_evidence'"'"'"'"'"'"'"'"', (select count(*) from public.claim_evidence),
  '"'"'"'"'"'"'"'"'public.claim_edges'"'"'"'"'"'"'"'"', (select count(*) from public.claim_edges),
  '"'"'"'"'"'"'"'"'kb_stage.kb_proposals'"'"'"'"'"'"'"'"', (select count(*) from kb_stage.kb_proposals)
)::text;'"'"'')"
python3 - "$DEPLOY_READBACK" "$SERVICE_READBACK" "$DB_COUNTS_READBACK" <<'PY' | base64 | tr -d '\n'
import json
import sys

def kv(text):
    out = {}
    for line in text.splitlines():
        if '=' in line:
            key, value = line.split('=', 1)
            out[key] = value.strip()
    return out

deploy = kv(sys.argv[1])
service = kv(sys.argv[2])
counts = json.loads(sys.argv[3])
payload = {
    'deploy_head': {'returncode': 0, 'stdout': deploy.get('deploy_head', ''), 'stderr': ''},
    'last_deploy_sha': {'returncode': 0, 'stdout': deploy.get('last_deploy_sha', ''), 'stderr': ''},
    'packet_present': deploy.get('packet_present') == 'true',
    'packet_bytes': int(deploy.get('packet_bytes') or 0),
    'service': {'returncode': 0, 'stderr': '', 'state': service},
    'db_counts': {'returncode': 0, 'stderr': '', 'counts': counts},
}
print(json.dumps(payload, sort_keys=True))
PY
printf '\n'
