#!/usr/bin/env python3
"""Free SAN Network HTTPS feeder. Requires Python 3 only. Never prints API keys."""
import argparse,getpass,json,time,urllib.request,urllib.error
from pathlib import Path
p=argparse.ArgumentParser();p.add_argument('--service',choices=['adsb','ais','vhf'],required=True);p.add_argument('--source-url');p.add_argument('--file');p.add_argument('--once',action='store_true');a=p.parse_args()
key=getpass.getpass('SAN Network API key: ').strip()
if not key.startswith(('san_'+a.service+'_','san_ingest_'+a.service+'_')):raise SystemExit('Key service does not match')
if a.service=='vhf' and not a.file:raise SystemExit('--file is required for an MP3 segment')
if a.service!='vhf' and not a.source_url:raise SystemExit('--source-url is required for local JSON data')
while True:
 try:
  if a.service=='vhf':body=Path(a.file).read_bytes();mime='audio/mpeg'
  else:
   with urllib.request.urlopen(a.source_url,timeout=10) as r:raw=json.load(r)
   if a.service=='adsb':data={'now':raw.get('now',time.time()),'aircraft':raw.get('aircraft',[])}
   else:data={'now':time.time(),'vessels':raw if isinstance(raw,list) else raw.get('vessels',[])}
   body=json.dumps(data,allow_nan=False).encode();mime='application/json'
  maximum=512000 if a.service=='vhf' else 250000
  if len(body)>maximum:raise ValueError('Payload exceeds limit')
  req=urllib.request.Request('https://ingest.sannetwork.net/api/contribute/'+a.service,data=body,headers={'Authorization':'Bearer '+key,'Content-Type':mime,'User-Agent':'SANNetworkFeeder'},method='POST')
  with urllib.request.urlopen(req,timeout=20) as r:result=json.load(r)
  print('Accepted; station:',result.get('stationId'),'records/bytes:',result.get('accepted',result.get('acceptedBytes')),flush=True)
 except Exception as e:print('Upload failed:',type(e).__name__,flush=True)
 if a.once:break
 time.sleep(15)
