import json
import os
import urllib.request

identity_url = os.getenv("DECISIOQ_IDENTITY_URL", "https://identity.vinquery.com/connect/token")
catalog_url = os.getenv("DECISIOQ_DKS_URL", "https://dks.vinquery.com")
decision_service_url = os.getenv("DECISIOQ_DDE_URL", "https://dde.vinquery.com")
audience = os.getenv("DECISIOQ_AUDIENCE", "vinquery:api:decisioq")

def post_json(url, payload, headers=None):
    data = json.dumps(payload).encode("utf-8")
    request = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json", **(headers or {})}, method="POST")
    with urllib.request.urlopen(request) as response:
        return json.loads(response.read().decode("utf-8"))

token = post_json(identity_url, {
    "clientId": os.environ["DECISIOQ_CLIENT_ID"],
    "clientSecret": os.environ["DECISIOQ_CLIENT_SECRET"],
    "audience": audience,
})["jwtToken"]

urllib.request.urlopen(urllib.request.Request(f"{catalog_url}/decisioncatalog/decisions/AUTO-REPR-070", headers={"Authorization": f"Bearer {token}"}))

with open("../auto-repr-070-execute.json", "r", encoding="utf-8") as file:
    payload = json.load(file)

result = post_json(f"{decision_service_url}/api/v1/decide", payload, {"Authorization": f"Bearer {token}", "X-Correlation-Id": "auto-repr-070-demo-001"})
print(json.dumps(result, indent=2))
