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(fit, demand, margin, cost, risk, customer):
    return {
        "determine_trade_in_value_vehicle_fit_score": fit,
        "determine_trade_in_value_market_demand_score": demand,
        "determine_trade_in_value_gross_margin_potential": margin,
        "determine_trade_in_value_reconditioning_or_process_cost": cost,
        "determine_trade_in_value_compliance_risk_score": risk,
        "determine_trade_in_value_customer_value_score": customer,
    }

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-ucd-008-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-UCD-008", None, token, correlation_id)

    result = request_json("POST", f"{decision_service_url}/api/v1/decide", {
        "decisionId": "AUTO-UCD-008",
        "profileId": "balanced",
        "scenarioId": "standard_retail",
        "algorithm": "TOPSIS",
        "weightStrategy": "Expert",
        "runSensitivity": False,
        "requestContext": {"correlationId": correlation_id},
        "options": [
            {"optionId": "OPTION-001", "name": "Retail Trade Option", "values": values(86, 92, 3200, 900, 22, 84)},
            {"optionId": "OPTION-002", "name": "Wholesale Backup Option", "values": values(78, 73, 4100, 1600, 35, 76)},
            {"optionId": "OPTION-003", "name": "Certified Retail Option", "values": values(91, 85, 2300, 650, 18, 88)},
        ]
    }, token, correlation_id)
    print(json.dumps(result, indent=2))
except Exception as exc:
    print(exc, file=sys.stderr)
    sys.exit(1)
