"""Python 3 standard library. Run: python compare.py input.json > result.json"""
import json
import os
import re
import sys
import uuid
import urllib.request
import urllib.error

key = os.environ.get('PAYLOADPIER_API_KEY')
if not key or len(sys.argv) != 2:
    sys.exit('Set PAYLOADPIER_API_KEY and supply an input JSON file.')
with open(sys.argv[1], 'rb') as source:
    body = source.read(5 * 1024 * 1024 + 1)
if len(body) > 5 * 1024 * 1024:
    sys.exit('Input exceeds 5 MiB.')
json.loads(body)
operation_id = os.environ.get('PAYLOADPIER_IDEMPOTENCY_KEY') or str(uuid.uuid4())
if not re.fullmatch(r'[\x21-\x7e]{1,128}', operation_id):
    sys.exit('Invalid idempotency key.')
print('Idempotency-Key: ' + operation_id, file=sys.stderr)

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

request = urllib.request.Request('https://payloadpier.com/api/v1/compare', data=body, method='POST', headers={
    'Content-Type': 'application/json', 'X-API-Key': key, 'Idempotency-Key': operation_id,
})
try:
    with urllib.request.build_opener(NoRedirect).open(request, timeout=60) as response:
        sys.stdout.buffer.write(response.read())
except urllib.error.HTTPError as error:
    sys.stdout.buffer.write(error.read())
    print(f'HTTP {error.code}; no automatic retry performed.', file=sys.stderr)
    sys.exit(1)
except (urllib.error.URLError, TimeoutError, OSError):
    sys.exit('Request failed or timed out. Outcome may be unknown. Preserve the printed idempotency key and check usage before submitting another operation.')
