# Quote changing an owned add-on
# Required environment: API_ORIGIN, SUBSCRIBER_ACCESS_TOKEN
# API_ORIGIN is the operator origin, without a /subscriber suffix.
# Edit the illustrative body below or set REQUEST_BODY_FILE to your JSON file.
# Makes one request; does not retry or follow redirects. After an uncertain write, check your order/SIM state before repeating.
# Save as addOnPlan_calculateChangePrice.py; run: python3 addOnPlan_calculateChangePrice.py (Python 3.9+, standard library).
import json
import os
import sys
import urllib.request
import urllib.parse
import urllib.error
from pathlib import Path

def required(name):
    value = os.environ.get(name)
    if not value:
        raise ValueError('Set ' + name)
    return value

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

origin = required('API_ORIGIN').rstrip('/')
parts = urllib.parse.urlsplit(origin)
if parts.scheme not in ('http', 'https') or not parts.netloc or parts.username or parts.password or parts.path or parts.query or parts.fragment:
    raise ValueError('API_ORIGIN must be an HTTP(S) origin only')
url = origin + "/subscriber/add-on_plans/change/price"
headers = {'Authorization': 'Bearer ' + required('SUBSCRIBER_ACCESS_TOKEN')}
data = None
example = json.loads("{\n  \"simId\": \"11111111-1111-4111-8111-111111111111\",\n  \"subscriberAddOnPlanId\": \"11111111-1111-4111-8111-111111111111\",\n  \"newAddOnPlanId\": \"11111111-1111-4111-8111-111111111111\"\n}")
body = json.loads(Path(os.environ['REQUEST_BODY_FILE']).read_text()) if os.environ.get('REQUEST_BODY_FILE') else example
data = json.dumps(body).encode('utf-8')
headers['Content-Type'] = 'application/json'
request = urllib.request.Request(url, data=data, headers=headers, method='POST')
try:
    try:
        response = urllib.request.build_opener(NoRedirect).open(request, timeout=30)
    except urllib.error.HTTPError as error:
        response = error
    with response:
        status = response.code
        text = response.read().decode('utf-8', errors='replace')
    print('HTTP ' + str(status))
    if text:
        try:
            print(json.dumps(json.loads(text), indent=2))
        except ValueError:
            print(text)
    sys.exit(0 if 200 <= status < 300 else 1)
except (urllib.error.URLError, TimeoutError, OSError) as error:
    print('Request failed: ' + str(error), file=sys.stderr)
    sys.exit(1)
