"""Fictional UPS Rating extracts; native JSON Pointer reads, never live quotes.

Install jsonpointer==3.0.0, then run this file. No API, checkout or ERP writes.
The local profile covers Shop/v2409, one requested service, EUR amounts and an
explicit display basis. This is not whole-response validation or a UPS SDK.
"""
from copy import deepcopy
from decimal import Decimal
from importlib.metadata import version
import json
import re
import sys

import jsonpointer

native_reads = 0
connections = 0
checks = []


def prevent_network(event, _args):
    global connections
    if event == "socket.connect":
        connections += 1
        raise AssertionError("Offline exercise: no connections allowed")


sys.addaudithook(prevent_network)


def check(name, condition):
    assert name not in checks, name
    assert condition, name
    checks.append(name)


def read(document, pointer):
    global native_reads
    native_reads += 1
    return jsonpointer.resolve_pointer(document, pointer)


def choose(document, profile):
    required = {"operation", "version", "requestOption", "service", "currency",
                "basis", "requireNegotiated", "taxInformationRequested", "masterCartonRequested"}
    if not isinstance(profile, dict) or not required.issubset(profile):
        return {"decision": "request_profile_review"}
    if profile["operation"] != "Rating":
        return {"decision": "other_operation_review"}
    if (profile["version"] != "v2409" or profile["requestOption"] != "Shop"
            or profile["currency"] != "EUR"
            or profile["masterCartonRequested"] is not False
            or profile["basis"] not in {"base_total", "with_taxes"}
            or type(profile["requireNegotiated"]) is not bool
            or type(profile["taxInformationRequested"]) is not bool):
        return {"decision": "request_profile_review"}
    if profile["basis"] == "with_taxes" and not profile["taxInformationRequested"]:
        return {"decision": "request_profile_review"}
    try:
        status = read(document, "/RateResponse/Response/ResponseStatus/Code")
        shipments = read(document, "/RateResponse/RatedShipment")
    except jsonpointer.JsonPointerException:
        return {"decision": "response_shape_review"}
    if status != "1":
        return {"decision": "provider_status_review"}
    if not isinstance(shipments, list):
        return {"decision": "response_shape_review"}
    candidates = []
    for index, entry in enumerate(shipments):
        if isinstance(entry, dict) and isinstance(entry.get("Service"), dict):
            if entry["Service"].get("Code") == profile["service"]:
                candidates.append(index)
    if not candidates:
        return {"decision": "requested_service_missing"}
    if len(candidates) != 1:
        return {"decision": "service_options_ambiguous"}
    root = "/RateResponse/RatedShipment/" + str(candidates[0])
    entry = shipments[candidates[0]]
    negotiated = "NegotiatedRateCharges" in entry
    if not negotiated and profile["requireNegotiated"]:
        return {"decision": "negotiated_rate_absent_review"}
    if negotiated:
        suffix = ("TotalCharge" if profile["basis"] == "base_total"
                  else "TotalChargesWithTaxes")
        pointer = root + "/NegotiatedRateCharges/" + suffix
        origin = "negotiated"
    else:
        suffix = ("TotalCharges" if profile["basis"] == "base_total"
                  else "TotalChargesWithTaxes")
        pointer = root + "/" + suffix
        origin = "published_explicitly_allowed"
    try:
        money = read(document, pointer)
    except jsonpointer.JsonPointerException:
        return {"decision": "selected_amount_missing_review", "pointer": pointer}
    if not isinstance(money, dict) or money.get("CurrencyCode") != "EUR":
        return {"decision": "currency_review", "pointer": pointer}
    raw = money.get("MonetaryValue")
    # Deliberate local EUR policy, not a universal currency/UPS amount grammar.
    if not isinstance(raw, str) or not re.fullmatch(r"(?:0|[1-9][0-9]*)(?:\.[0-9]{1,2})?", raw):
        return {"decision": "local_eur_amount_review", "pointer": pointer}
    return {"decision": "candidate_for_checkout_review", "pointer": pointer,
            "service": profile["service"], "origin": origin,
            "currency": "EUR", "amount": format(Decimal(raw), ".2f"),
            "basis": profile["basis"]}


def amount(value, currency="EUR"):
    return {"CurrencyCode": currency, "MonetaryValue": value}


def main():
    check("pinned_native_engine", version("jsonpointer") == "3.0.0")
    service = {"Service": {"Code": "03"}, "TotalCharges": amount("12.40"),
               "NegotiatedRateCharges": {"TotalCharge": amount("8.60"),
                                         "TotalChargesWithTaxes": amount("10.32")}}
    other = {"Service": {"Code": "11"}, "TotalCharges": amount("15.00", "USD")}
    document = {"RateResponse": {"Response": {"ResponseStatus": {"Code": "1"}},
                                 "RatedShipment": [service, other]}}
    profile = {"operation": "Rating", "version": "v2409", "requestOption": "Shop",
               "service": "03", "currency": "EUR", "basis": "base_total",
               "requireNegotiated": True, "taxInformationRequested": False,
               "masterCartonRequested": False}
    wrong = "/RateResponse/RatedShipment/0/NegotiatedRateCharges/TotalCharges"
    try:
        read(document, wrong)
        missing = False
    except jsonpointer.JsonPointerException:
        missing = True
    fallback = read(document, "/RateResponse/RatedShipment/0/TotalCharges")
    received = read(document, "/RateResponse/RatedShipment/0/NegotiatedRateCharges/TotalCharge")
    naive = {"wrongPluralPathMissing": missing, "displayedOrigin": "published",
             "displayedAmount": fallback["MonetaryValue"],
             "receivedNegotiatedAmount": received["MonetaryValue"],
             "currency": "EUR",
             "fictionalDifference": format(Decimal(fallback["MonetaryValue"])
                                           - Decimal(received["MonetaryValue"]), ".2f")}
    check("native_missing_plural_path_reproduced", missing)
    check("real_distinct_native_pointer_values", naive["displayedAmount"] == "12.40"
          and naive["receivedNegotiatedAmount"] == "8.60")
    cases = []

    def add(name, expected, change_document=None, change_profile=None):
        doc, cfg = deepcopy(document), deepcopy(profile)
        if change_document:
            change_document(doc)
        if change_profile:
            change_profile(cfg)
        cases.append((name, doc, cfg, expected))

    def change_service(doc, key, value):
        doc["RateResponse"]["RatedShipment"][0][key] = value

    add("received_negotiated", "candidate_for_checkout_review")
    add("other_service_first", "candidate_for_checkout_review",
        lambda d: d["RateResponse"]["RatedShipment"].reverse())
    add("negotiated_absent", "negotiated_rate_absent_review",
        lambda d: d["RateResponse"]["RatedShipment"][0].pop("NegotiatedRateCharges"))
    add("plural_mistake_inside_response", "selected_amount_missing_review",
        lambda d: change_service(d, "NegotiatedRateCharges", {"TotalCharges": amount("8.60")}))
    add("null_negotiated_container", "selected_amount_missing_review",
        lambda d: change_service(d, "NegotiatedRateCharges", None))
    for name, value, currency, expected in [
        ("foreign_currency", "8.60", "USD", "currency_review"),
        ("comma_amount", "8,60", "EUR", "local_eur_amount_review"),
        ("numeric_amount", 8.6, "EUR", "local_eur_amount_review"),
        ("not_finite_amount", "NaN", "EUR", "local_eur_amount_review"),
        ("negative_amount", "-8.60", "EUR", "local_eur_amount_review"),
        ("extra_precision", "8.601", "EUR", "local_eur_amount_review"),
        ("zero_amount", "0", "EUR", "candidate_for_checkout_review"),
    ]:
        add(name, expected, lambda d, v=value, c=currency:
            change_service(d, "NegotiatedRateCharges", {"TotalCharge": amount(v, c)}))
    add("with_taxes_recorded", "candidate_for_checkout_review", change_profile=
        lambda p: p.update(basis="with_taxes", taxInformationRequested=True))
    add("with_taxes_missing", "selected_amount_missing_review",
        lambda d: d["RateResponse"]["RatedShipment"][0]["NegotiatedRateCharges"].pop("TotalChargesWithTaxes"),
        lambda p: p.update(basis="with_taxes", taxInformationRequested=True))
    add("with_taxes_unrecorded_request", "request_profile_review",
        change_profile=lambda p: p.update(basis="with_taxes"))
    add("requested_service_missing", "requested_service_missing",
        change_profile=lambda p: p.update(service="99"))
    add("duplicate_service_options", "service_options_ambiguous",
        lambda d: d["RateResponse"]["RatedShipment"].append(deepcopy(service)))
    add("old_single_object_shape", "response_shape_review",
        lambda d: d["RateResponse"].update(RatedShipment=deepcopy(service)))
    add("master_carton_outside_profile", "request_profile_review",
        change_profile=lambda p: p.update(masterCartonRequested=True))
    add("other_operation", "other_operation_review",
        change_profile=lambda p: p.update(operation="Shipping"))
    add("unrecorded_profile", "request_profile_review",
        change_profile=lambda p: p.pop("basis"))
    add("provider_status_not_success", "provider_status_review",
        lambda d: d["RateResponse"]["Response"]["ResponseStatus"].update(Code="0"))
    add("published_explicit_policy", "candidate_for_checkout_review",
        lambda d: d["RateResponse"]["RatedShipment"][0].pop("NegotiatedRateCharges"),
        lambda p: p.update(requireNegotiated=False))
    observations = []
    for name, doc, cfg, expected in cases:
        result = choose(doc, cfg)
        check(name, result["decision"] == expected)
        check(name + "_no_checkout_authorization", "checkoutAuthorized" not in result)
        observations.append({"case": name, **result})
    by_name = {x["case"]: x for x in observations}
    check("service_reorder_same_amount", by_name["received_negotiated"]["amount"]
          == by_name["other_service_first"]["amount"] == "8.60")
    check("with_taxes_selected_without_arithmetic", by_name["with_taxes_recorded"]["amount"] == "10.32")
    check("published_origin_visible", by_name["published_explicit_policy"]["origin"]
          == "published_explicitly_allowed")
    check("no_connections", connections == 0)
    print(json.dumps({"checksPassed": len(checks), "checks": checks, "cases": len(cases),
                      "nativeJsonPointerReads": native_reads, "jsonpointer": version("jsonpointer"),
                      "naiveObservation": naive, "observations": observations,
                      "networkConnectionAttempts": connections, "upsApiCalls": 0,
                      "checkoutWrites": 0, "erpWrites": 0}, indent=2))


if __name__ == "__main__":
    main()
