"""VIP Booking — WhatsApp relay for the hosted (cPanel) app.

Runs on the PC where Hermes is paired with the company WhatsApp. Every run:
  1. POST {VIP_URL}/vip-relay/outbox  (header X-Relay-Token) -> due messages (this also runs the schedule on the server)
  2. for each: hermes send -t whatsapp:<digits> -f <text file> --json
  3. POST {VIP_URL}/vip-relay/result  {id, ok, message}

Set it up as a Hermes scheduled job (no AI, no credits), every 5 minutes:
  1. copy vip_relay.py and vip_relay.ini into %LOCALAPPDATA%\\hermes\\scripts\\
  2. hermes cron create "every 5m" --name vip-relay --no-agent --deliver local --script vip_relay.py
Prints only when something was sent or failed (empty output = Hermes stays silent).

Settings: environment variables, or a vip_relay.ini next to this file:
  [relay]
  url = https://booking.example.com          (the app's address, no trailing slash; include /public if your URL has it)
  token = <the VIP_RELAY_TOKEN from the server's .env>
  hermes = C:\\Users\\<you>\\AppData\\Local\\hermes\\bin\\hermes.exe   (optional)
"""
import configparser
import json
import os
import subprocess
import sys
import tempfile
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
cfg = configparser.ConfigParser()
cfg.read(os.path.join(HERE, 'vip_relay.ini'))
URL = (os.environ.get('VIP_URL') or cfg.get('relay', 'url', fallback='')).rstrip('/')
TOKEN = os.environ.get('VIP_RELAY_TOKEN') or cfg.get('relay', 'token', fallback='')
HERMES = os.environ.get('HERMES_BIN') or cfg.get('relay', 'hermes', fallback='') or os.path.join(
    os.environ.get('LOCALAPPDATA', ''), 'hermes', 'bin', 'hermes.exe')


def call(path, payload=None):
    data = json.dumps(payload or {}).encode('utf-8')
    req = urllib.request.Request(URL + path, data=data, method='POST', headers={
        'X-Relay-Token': TOKEN, 'Content-Type': 'application/json', 'Accept': 'application/json',
        'User-Agent': 'vip-relay/1.0'})
    with urllib.request.urlopen(req, timeout=60) as r:
        return json.loads(r.read().decode('utf-8') or '{}')


def send(digits, body):
    fd, path = tempfile.mkstemp(suffix='.txt')
    try:
        with os.fdopen(fd, 'w', encoding='utf-8') as f:
            f.write(body)
        target = 'whatsapp:' + digits if digits else 'whatsapp'
        p = subprocess.run([HERMES, 'send', '-t', target, '-f', path, '--json'], capture_output=True, text=True, timeout=120)
        out = (p.stdout or '').strip()
        ok = p.returncode == 0
        try:
            j = json.loads(out)
            if isinstance(j, dict) and (j.get('success', j.get('ok', True)) is False):
                ok = False
        except ValueError:
            pass
        msg = ('Sent by the Hermes relay to ' + target + '.') if ok else ('Relay: Hermes could not send: ' + (out + ' ' + (p.stderr or '')).strip()[:300])
        return ok, msg
    except Exception as e:  # noqa: BLE001 - report every failure back to the server
        return False, 'Relay: Hermes did not run: ' + str(e)[:300]
    finally:
        try:
            os.unlink(path)
        except OSError:
            pass


def main():
    if not URL or not TOKEN:
        print('Set VIP_URL and VIP_RELAY_TOKEN (or vip_relay.ini).')
        return 2
    box = call('/vip-relay/outbox')
    msgs = box.get('messages', [])
    sent = failed = 0
    for m in msgs:
        ok, msg = send(m.get('digits', ''), m.get('body', ''))
        call('/vip-relay/result', {'id': m['id'], 'ok': ok, 'message': msg})
        sent += ok
        failed += (not ok)
    if msgs:
        print('VIP Booking relay: %d sent, %d failed.' % (sent, failed))
    return 0


if __name__ == '__main__':
    try:
        sys.exit(main())
    except Exception as e:  # noqa: BLE001 - one line for Hermes instead of a traceback
        print('VIP Booking relay could not reach ' + (URL or '(no url)') + ': ' + str(e)[:300])
        sys.exit(1)
