import subprocess, json, time, urllib.request
def sql(q): return subprocess.run("mysql -u root zc_safeguarding -N -e \"%s\""%q,shell=True,capture_output=True,text=True).stdout.strip()
n=0
def msg(num,text):
    global n; n+=1
    d={'event_type':'message_received','instanceId':'1150','data':{'id':'p_%d'%n,'from':num+'@c.us','type':'chat','body':text,'fromMe':False}}
    req=urllib.request.Request('http://127.0.0.1:8101/api/whatsapp/webhook.php?s=testsecret123',data=json.dumps(d).encode(),method='POST')
    return urllib.request.urlopen(req).status
N='263775550000'
for t in ['hi','1','2','2','6','me','now','1','field','something happened','DONE']: msg(N,t)
before=sql('SELECT COUNT(*) FROM anonymous_reports'), sql("SELECT state FROM whatsapp_sessions")
msg(N,'YES')   # production mode, no ULTRAMSG_TOKEN: the receipt cannot be delivered
after=sql('SELECT COUNT(*) FROM anonymous_reports'), sql("SELECT state FROM whatsapp_sessions")
ok = after[0]=='0' and after[1]=='confirm'
print('PASS' if ok else 'FAIL','undeliverable receipt rolls the submission back and keeps the session at confirm',before,after)
print('PASS' if int(sql("SELECT COUNT(*) FROM whatsapp_messages WHERE status='failed'"))>0 else 'FAIL','failed sends are recorded')
