#!/usr/bin/env python3
"""Poll Michel's signed result endpoint for a completed Foster delegation."""
import argparse, hashlib, hmac, json, os, sys, time, urllib.error, urllib.request

p=argparse.ArgumentParser()
p.add_argument('request_id')
p.add_argument('--base-url',default=os.environ.get('MICHEL_RESULT_BASE_URL','https://michel.saitz.ai'))
p.add_argument('--timeout',type=int,default=300)
p.add_argument('--interval',type=float,default=3.0)
p.add_argument('--secret-file',default='')
a=p.parse_args()
secret=(open(a.secret_file,encoding='ascii').read().strip() if a.secret_file else os.environ.get('MICHEL_WEBHOOK_SECRET','').strip())
if not secret: raise SystemExit('MICHEL_WEBHOOK_SECRET is required')
path='/api/foster-result/'+a.request_id
end=time.time()+a.timeout
while time.time()<end:
 ts=str(int(time.time()))
 signature=hmac.new(secret.encode(),f'GET\n{path}\n{ts}'.encode(),hashlib.sha256).hexdigest()
 req=urllib.request.Request(a.base_url.rstrip('/')+path,headers={'X-Michel-Timestamp':ts,'X-Michel-Signature':signature})
 try:
  with urllib.request.urlopen(req,timeout=20) as response:
   data=json.loads(response.read())
 except urllib.error.HTTPError as exc:
  data=json.loads(exc.read() or b'{}')
  if exc.code not in (202,):
   print(json.dumps(data),file=sys.stderr);raise SystemExit(1)
 if data.get('status') in ('completed','failed'):
  print(json.dumps(data,ensure_ascii=False));raise SystemExit(0 if data['status']=='completed' else 2)
 time.sleep(a.interval)
print(json.dumps({'request_id':a.request_id,'status':'timeout'}),file=sys.stderr)
raise SystemExit(3)
