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

TARGET="/opt/microdao-daarion/gateway-bot/http_api.py"

python3 - <<'PY'
from pathlib import Path
import re
p = Path('/opt/microdao-daarion/gateway-bot/http_api.py')
text = p.read_text(encoding='utf-8')

anchors = {
    'file_base64': r'\n\s*if file_base64:\n',
    'image_base64': r'\n\s*elif image_base64:\n',
    'text_fallback': r'\n\s*else:\n\s*# Send text response only\n',
}

pos = {}
for k, pat in anchors.items():
    m = re.search(pat, text)
    if not m:
        raise SystemExit(f"[FAIL] anchor not found: {k}")
    pos[k] = m.start()

expected = ['file_base64','image_base64','text_fallback']
for a, b in zip(expected, expected[1:]):
    if not (pos[a] < pos[b]):
        raise SystemExit(f"[FAIL] priority order broken: {a} should be before {b}")

print('[OK] gateway delivery priority order is correct')
for k in expected:
    print(f'  - {k}: {pos[k]}')
PY

echo "[OK] gateway delivery priority canary passed"
