import json
import os
import sys
import urllib.request
import uuid


def required(name):
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"Set {name} before running this example.")
    return value


def request_json(method, url, payload=None, token=None, correlation_id=None):
    data = None if payload is None else json.dumps(payload).encode("utf-8")
    request = urllib.request.Request(url, data=data, method=method)
    request.add_header("Content-Type", "application/json")
    if token:
        request.add_header("Authorization", f"Bearer {token}")
    if correlation_id:
        request.add_header("X-Correlation-Id", correlation_id)
    with urllib.request.urlopen(request, timeout=45) as response:
        body = response.read().decode("utf-8")
        return json.loads(body) if body else {}


def values(fit, demand, margin, cost, risk, customer):
    return {
        "assign_rental_vehicle_customer_fit_score": fit,
        "assign_rental_vehicle_vehicle_or_resource_fit": demand,
        "assign_rental_vehicle_operational_readiness": margin,
        "assign_rental_vehicle_financial_impact": cost,
        "assign_rental_vehicle_risk_exposure": risk,
        "assign_rental_vehicle_time_sensitivity": customer,
    }

try:
    identity_url = os.environ.get("DECISIOQ_IDENTITY_URL", "https://identity.vinquery.com/connect/token")
    catalog_url = os.environ.get("DECISIOQ_DKS_URL", "https://dks.vinquery.com").rstrip("/")
    decision_service_url = os.environ.get("DECISIOQ_DDE_URL", "https://dde.vinquery.com").rstrip("/")
    correlation_id = f"auto-rent-008-python-{uuid.uuid4()}"

    token_response = request_json("POST", identity_url, {
        "clientId": required("DECISIOQ_CLIENT_ID"),
    "clientSecret": required("DECISIOQ_CLIENT_SECRET"),
        "audience": os.environ.get("DECISIOQ_AUDIENCE", "vinquery:api:decisioq"),
    })
    token = token_response["jwtToken"]
    request_json("GET", f"{catalog_url}/decisioncatalog/decisions/AUTO-RENT-008", None, token, correlation_id)

    result = request_json("POST", f"{decision_service_url}/api/v1/decide", {
        "decisionId": "AUTO-RENT-008",
        "profileId": "balanced",
        "scenarioId": "standard_rental",
        "algorithm": "TOPSIS",
        "weightStrategy": "Expert",
        "runSensitivity": False,
        "requestContext": {"correlationId": correlation_id},
        "options": [
            {"optionId": "OPTION-001", "name": "Compact SUV Unit", "values": values(88, 91, 84, 76, 20, 26)},
            {"optionId": "OPTION-002", "name": "Standard Sedan Unit", "values": values(79, 85, 92, 70, 18, 34)},
            {"optionId": "OPTION-003", "name": "Premium SUV Unit", "values": values(92, 73, 68, 88, 42, 50)},
        ]
    }, token, correlation_id)
    print(json.dumps(result, indent=2))
except Exception as exc:
    print(exc, file=sys.stderr)
    sys.exit(1)
