import json
import os
import sys
import uuid
from urllib import request, error


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


def json_request(url: str, method: str = "GET", token: str | None = None, payload: dict | None = None, correlation_id: str | None = None) -> dict:
    data = None if payload is None else json.dumps(payload).encode("utf-8")
    req = request.Request(url, data=data, method=method)
    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)
    try:
        with request.urlopen(req, timeout=30) as response:
            body = response.read().decode("utf-8")
            return json.loads(body) if body else {}
    except error.HTTPError as exc:
        details = exc.read().decode("utf-8")
        raise RuntimeError(f"{method} {url} failed with {exc.code}: {details}") from exc


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-auct-006-python-{uuid.uuid4().hex}"

token_response = json_request(identity_url, "POST", payload={
    "clientId": required("DECISIOQ_CLIENT_ID"),
    "clientSecret": required("DECISIOQ_CLIENT_SECRET"),
    "audience": os.environ.get("DECISIOQ_AUDIENCE", "vinquery:api:decisioq"),
})
jwt_token = token_response.get("jwtToken")
if not jwt_token:
    raise RuntimeError("Token response did not contain jwtToken.")

json_request(f"{catalog_url}/decisioncatalog/decisions/AUTO-AUCT-006", token=jwt_token, correlation_id=correlation_id)

execution_request = {
    "decisionId": "AUTO-AUCT-006",
    "profileId": "balanced",
    "scenarioId": "standard",
    "algorithm": "TOPSIS",
    "weightStrategy": "Expert",
    "runSensitivity": False,
    "requestContext": {"correlationId": correlation_id},
    "options": [
        {
            "optionId": "MANHEIM-TORONTO",
            "name": "Manheim Toronto",
            "values": {
                "vehicle_availability_score": 88,
                "buyer_fee_level": 1250,
                "average_vehicle_quality": 88,
                "distance_to_facility": 54,
                "auction_reputation_score": 88,
                "title_processing_speed": 88,
            },
        },
        {
            "optionId": "ADESA-TORONTO",
            "name": "ADESA Toronto",
            "values": {
                "vehicle_availability_score": 81,
                "buyer_fee_level": 1750,
                "average_vehicle_quality": 81,
                "distance_to_facility": 71,
                "auction_reputation_score": 81,
                "title_processing_speed": 81,
            },
        },
    ],
}

result = json_request(
    f"{decision_service_url}/api/v1/decide",
    "POST",
    token=jwt_token,
    payload=execution_request,
    correlation_id=correlation_id,
)
json.dump(result, sys.stdout, indent=2)
print()
