import json
import os
import time
import urllib.request


def required(name):
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"Missing required environment variable {name}.")
    return value


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


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-044-python-{int(time.time())}"

token_response = request_json(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(f"{catalog_url}/decisioncatalog/decisions/AUTO-AUCT-044", token=token, correlation_id=correlation_id)

with open("auto-auct-044-execute.json", "r", encoding="utf-8") as f:
    payload = json.load(f)

result = request_json(f"{decision_service_url}/api/v1/decide", payload, token, correlation_id)
print(json.dumps(result, indent=2))

