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(proximity, certification, load, safety, rating):
    return {
        "proximity_score": proximity,
        "certification_match_score": certification,
        "current_job_load": load,
        "safety_history_score": safety,
        "customer_rating_score": rating
    }

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-tow-019-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-TOW-019", None, token, correlation_id)

    result = request_json("POST", f"{decision_service_url}/api/v1/decide", {
        "decisionId": "AUTO-TOW-019",
        "profileId": "balanced",
        "scenarioId": "standard",
        "algorithm": "TOPSIS",
        "weightStrategy": "Expert",
        "runSensitivity": False,
        "requestContext": {"correlationId": correlation_id},
        "options": [
            {"optionId": "OPTION-001", "name": "Operator North Zone", "values": values(88, 88, 1, 88, 88)},
            {"optionId": "OPTION-002", "name": "Operator Central Zone", "values": values(80, 80, 3, 80, 80)},
            {"optionId": "OPTION-003", "name": "Operator East Zone", "values": values(72, 72, 5, 72, 72)},
        ]
    }, token, correlation_id)
    print(json.dumps(result, indent=2))
except Exception as exc:
    print(exc, file=sys.stderr)
    sys.exit(1)



