import json
import os
import sys
import urllib.request

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")
    req = urllib.request.Request(url, data=data, method=method)
    req.add_header("Accept", "application/json")
    if payload is not None:
        req.add_header("Content-Type", "application/json")
    if token:
        req.add_header("Authorization", f"Bearer {token}")
    if correlation_id:
        req.add_header("X-Correlation-Id", correlation_id)
    with urllib.request.urlopen(req, timeout=45) as response:
        return response.read().decode("utf-8")

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 = "auto-fleet-001-python"

try:
    token_text = 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 = json.loads(token_text)["jwtToken"]
    request_json("GET", f"{catalog_url}/decisioncatalog/decisions/AUTO-FLEET-001", None, token, correlation_id)
    result = request_json("POST", f"{decision_service_url}/api/v1/decide", {
        "decisionId": "AUTO-FLEET-001",
        "profileId": "balanced",
        "scenarioId": None,
        "algorithm": "TOPSIS",
        "weightStrategy": "Expert",
        "runSensitivity": False,
        "requestContext": {"correlationId": correlation_id},
        "options": [
            {"optionId": "VEHICLE-001", "name": "Vehicle 001", "values": {"lifecycle_cost": 18000, "downtime_risk": 9, "maintenance_trend": 6, "utilization_criticality": 92, "safety_rating": 4.5}},
            {"optionId": "VEHICLE-002", "name": "Vehicle 002", "values": {"lifecycle_cost": 14500, "downtime_risk": 3, "maintenance_trend": 2, "utilization_criticality": 76, "safety_rating": 4}}
        ]
    }, token, correlation_id)
    print(result)
except Exception as exc:
    print(exc, file=sys.stderr)
    sys.exit(1)
