#!/usr/bin/env python3
"""Send prepared JSONL events to ITcode CRM. Credentials are read from the environment.
Usage: CRM_KEY=... python3 exchange.py events.jsonl
The same immutable eventId/body is used on retry. Never logs keys or customer data.
"""
import argparse,json,os,time,urllib.request,urllib.error,urllib.parse
class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self,*args,**kwargs): return None

def send(event,base,key,attempts=3):
    parsed=urllib.parse.urlsplit(base)
    if parsed.scheme!='https' or parsed.username or parsed.password or parsed.query or parsed.fragment:
        raise ValueError('Use an HTTPS base URL without credentials or query')
    if not event.get('eventId'): raise ValueError('Every event needs a stable eventId')
    body=json.dumps(event,ensure_ascii=False,separators=(',',':')).encode()
    if len(body)>18000: raise ValueError('Event exceeds 18 KB')
    opener=urllib.request.build_opener(NoRedirect())
    for attempt in range(attempts):
        req=urllib.request.Request(base.rstrip('/')+'/event',data=body,headers={'X-CRM-Key':key,'Content-Type':'application/json'})
        try:
            with opener.open(req,timeout=25) as response:return json.load(response)
        except urllib.error.HTTPError as e:
            if e.code not in (429,500,502,503,504) or attempt==attempts-1:
                raise RuntimeError('CRM HTTP '+str(e.code)+'; inspect the CRM exchange journal') from None
        except urllib.error.URLError:
            if attempt==attempts-1: raise RuntimeError('Network error; rerun the same event file') from None
        time.sleep(2**attempt)
def main():
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('file');parser.add_argument('--base',default='https://itcode.tech/api/app/workspace/integration/v1');args=parser.parse_args()
    key=os.environ.get('CRM_KEY','')
    if not key:parser.error('Set CRM_KEY in the process environment')
    count=0
    with open(args.file,encoding='utf-8') as source:
        for line in source:
            if not line.strip():continue
            event=json.loads(line);send(event,args.base,key);count+=1
    print('Confirmed events:',count)
if __name__=='__main__':main()
