#!/usr/bin/env python3
"""EntryLuma transport example. Dry run by default; not a production vendor connector."""
import argparse,datetime,hashlib,json,os,re,sys,urllib.request,urllib.error
EVENT_TYPES=('check_in','check_out','break_in','break_out','overtime_in','overtime_out')
class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self,*args):return None

def build_event(serial,person_id,occurred_at,source_event_id,event_type='check_in',method='fingerprint',mac=None):
    if not serial or not person_id or len(person_id)>80 or not source_event_id:raise ValueError('serial, string person_id and stable source_event_id are required')
    if not re.fullmatch(r'\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)',occurred_at):raise ValueError('Timestamp needs ISO 8601 with timezone')
    datetime.datetime.fromisoformat(occurred_at.replace('Z','+00:00'))
    if event_type not in EVENT_TYPES:raise ValueError('Unsupported event type')
    if method not in ('fingerprint','face','card','pin'):raise ValueError('Map the verified vendor method explicitly')
    canonical=json.dumps([serial,source_event_id],ensure_ascii=False,separators=(',',':')).encode()
    result={'event_id':hashlib.sha256(canonical).hexdigest(),'device_serial':serial,'person_id':person_id,'occurred_at':occurred_at,'event_type':event_type,'method':method,'verified':True}
    if mac:result['macAddress']=mac
    return result

def classify(reply):
    if reply.get('accepted') is not True:return 'rejected'
    status=reply.get('status')
    if status in ('recorded','duplicate','historical'):return status
    return 'review_required'

def send_event(url,token,event):
    if not url.startswith('https://') or '?' in url or '#' in url:raise ValueError('Use final HTTPS webhook URL without query/fragment; redirects are refused')
    if not re.fullmatch(r'[a-f0-9]{64}',token):raise ValueError('ENTRYLUMA_DEVICE_TOKEN must be 64 lowercase hex characters')
    request=urllib.request.Request(url,data=json.dumps(event).encode(),headers={'X-Device-Token':token,'Content-Type':'application/json','Accept':'application/json'},method='POST')
    try:
        with urllib.request.build_opener(NoRedirect()).open(request,timeout=20) as response:
            raw=response.read(65537)
        if len(raw)>65536:raise ValueError('Oversized response; preserve event in outbox for operator review')
        reply=json.loads(raw)
        if not isinstance(reply,dict):raise ValueError('Response must be an object')
        return classify(reply),reply
    except urllib.error.HTTPError as e:
        if e.code==429 or e.code>=500:raise RuntimeError('Transient HTTP error; retry SAME event later with bounded backoff: '+str(e.code)) from None
        raise RuntimeError('HTTP '+str(e.code)+'; preserve event and correct configuration before retrying') from None

def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--serial',required=True);p.add_argument('--person-id',required=True);p.add_argument('--source-event-id',required=True)
    p.add_argument('--occurred-at',required=True,help='Original scan timestamp, e.g. 2026-10-27T10:00:00+08:00; do not refresh on retry')
    p.add_argument('--event-type',choices=EVENT_TYPES,default='check_in');p.add_argument('--method',choices=['fingerprint','face','card','pin'],default='fingerprint')
    p.add_argument('--url',default='https://www.entryluma.com/api/v1/attendance/webhook.php')
    p.add_argument('--send',action='store_true');p.add_argument('--confirmed-success',action='store_true',help='Required for real sending; use only after vendor confirms successful person authentication')
    a=p.parse_args();event=build_event(a.serial,a.person_id,a.occurred_at,a.source_event_id,a.event_type,a.method)
    if not a.send:print(json.dumps(event,indent=2));print('DRY RUN: no request sent.');return
    if not a.confirmed_success:p.error('Sending requires --confirmed-success; never treat a door alarm as person authentication.')
    outcome,reply=send_event(a.url,os.environ.get('ENTRYLUMA_DEVICE_TOKEN',''),event);print(json.dumps(reply,indent=2));print('Transport classification:',outcome)
    if outcome not in ('recorded','duplicate','historical'):raise SystemExit(2)
if __name__=='__main__':
    try:main()
    except (ValueError,RuntimeError,urllib.error.URLError,TimeoutError,OSError) as e:print(str(e),file=sys.stderr);raise SystemExit(1)
