"""Bridge the owner-private Sites upload queue to the existing Go inference commands on zap."""
import argparse
import json
import logging
from pathlib import Path
import re
import subprocess
import tempfile
import time
import urllib.request


class Site:
    def __init__(self, origin, credential):
        self.origin = origin.rstrip('/')
        self.headers = {'OAI-Sites-Authorization':'Bearer '+credential.strip(), 'X-Review-Agent':'zap-v1'}
        if not re.fullmatch(r'https://[a-z0-9.-]+\.chatgpt\.site', self.origin):
            raise ValueError('Expected a private Sites HTTPS origin')

    def call(self, path, method='GET', body=None, headers=None):
        request_headers = {**self.headers, **(headers or {})}
        req = urllib.request.Request(self.origin + path, data=body, method=method, headers=request_headers)
        # A redirected request must never forward the service credential to another origin.
        class NoRedirect(urllib.request.HTTPRedirectHandler):
            def redirect_request(self, *args):
                return None
        with urllib.request.build_opener(NoRedirect()).open(req, timeout=60) as res:
            return res.status,res.headers,res.read()


def infer(root, jpeg):
    with tempfile.NamedTemporaryFile(suffix='.jpg',dir=root) as photo:
        photo.write(jpeg);photo.flush()
        cmd=[root/'bin/horse-embed','-masks','-models',root/'infra/models/reid-v1','-detector',root/'infra/models/yolo26x.onnx',
             '-runtime',root/'infra/models/libonnxruntime.so.1.31.1',photo.name]
        vectors=subprocess.run(cmd,check=True,stdout=subprocess.PIPE,timeout=180).stdout
        rows=subprocess.run([root/'bin/horse-rank','-gallery',root/'gallery.json'],input=vectors,check=True,stdout=subprocess.PIPE,timeout=30).stdout
    return {'detections':[r for r in map(json.loads,rows.splitlines()) if r['source']!='missed']}


def serve(site,root):
    while True:
        try:
            code,headers,pixels=site.call('/internal/next')
            if code==204:
                time.sleep(8);continue
            job=headers['X-Job'];key=headers['X-Queue-Key']
            if not re.fullmatch(r'[0-9a-f-]{36}',job or ''):raise ValueError('invalid job id')
            try:
                result=infer(root,pixels)
            except (subprocess.SubprocessError,OSError,ValueError):
                logging.exception('Inference failed')
                result={'error':'Не удалось обработать снимок на zap. Попробуйте другой кадр.'}
            site.call('/internal/results/'+job,'PUT',json.dumps(result,allow_nan=False).encode(),
                      {'Content-Type':'application/json','X-Queue-Key':key})
            logging.info('Completed job %s, detections %s',job,len(result.get('detections',[])))
        except (OSError,ValueError) as err:
            logging.warning('Queue unavailable: %s',err);time.sleep(12)


if __name__=='__main__':
    ap=argparse.ArgumentParser(description=__doc__)
    ap.add_argument('origin');ap.add_argument('credential',type=Path);ap.add_argument('--seed',type=Path)
    args=ap.parse_args();site=Site(args.origin,args.credential.read_text())
    logging.basicConfig(level=logging.INFO,format='%(asctime)s %(message)s')
    if args.seed:
        for pack in sorted(args.seed.iterdir()):
            if pack.name.isdigit():
                site.call('/internal/assets/'+pack.name,'PUT',pack.read_bytes(),{'Content-Type':'application/octet-stream'})
                print('Seeded',pack.name,flush=True)
    else:serve(site,Path.cwd())
