import json
import os
import sys
import urllib.request


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 post_json(url: str, payload: dict, token: str | None = None, correlation_id: str | None = None) -> str:
    data = json.dumps(payload).encode("utf-8")
    req = urllib.request.Request(url, data=data, method="POST")
    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)
    with urllib.request.urlopen(req, timeout=45) as response:
        return response.read().decode("utf-8")


def get_json(url: str, token: str, correlation_id: str) -> str:
    req = urllib.request.Request(url, method="GET")
    req.add_header("Authorization", f"Bearer {token}")
    req.add_header("X-Correlation-Id", correlation_id)
    with urllib.request.urlopen(req, timeout=45) as response:
        return response.read().decode("utf-8")


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 = "auto-ins-011-python"

token_text = post_json(identity_url, {
    "clientId": required("DECISIOQ_CLIENT_ID"),
    "clientSecret": required("DECISIOQ_CLIENT_SECRET"),
        "audience": os.environ.get("DECISIOQ_AUDIENCE", "vinquery:api:decisioq")
    })
token = json.loads(token_text)["jwtToken"]

get_json(f"{catalog_url}/decisioncatalog/decisions/AUTO-INS-011", token, correlation_id)

request = {
    "decisionId": "AUTO-INS-011",
    "profileId": "balanced",
    "scenarioId": "standard",
    "algorithm": "TOPSIS",
    "weightStrategy": "Expert",
    "runSensitivity": False,
    "requestContext": {"correlationId": correlation_id},
    "options": [
        {
            "optionId": "CLAIM-011-01",
            "name": "Claim CASE-001",
            "values": {
                "claim_severity_score": 83,
                "customer_impact_score": 83,
                "coverage_clarity_score": 83,
                "fraud_risk_score": 78,
                "estimated_loss_amount": 62500
            }
        },
        {
            "optionId": "CLAIM-011-02",
            "name": "Claim CASE-002",
            "values": {
                "claim_severity_score": 75,
                "customer_impact_score": 75,
                "coverage_clarity_score": 75,
                "fraud_risk_score": 70,
                "estimated_loss_amount": 107500
            }
        }
    ]
}

try:
    print(post_json(f"{decision_service_url}/api/v1/decide", request, token, correlation_id))
except Exception as exc:
    print(exc, file=sys.stderr)
    sys.exit(1)
