using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;

static string Required(string name) =>
    Environment.GetEnvironmentVariable(name) ??
    throw new InvalidOperationException($"Set {name} before running this example.");

var identityUrl = Environment.GetEnvironmentVariable("DECISIOQ_IDENTITY_URL") ?? "https://identity.vinquery.com/connect/token";
var catalogUrl = (Environment.GetEnvironmentVariable("DECISIOQ_DKS_URL") ?? "https://dks.vinquery.com").TrimEnd('/');
var decisionServiceUrl = (Environment.GetEnvironmentVariable("DECISIOQ_DDE_URL") ?? "https://dde.vinquery.com").TrimEnd('/');
var audience = Environment.GetEnvironmentVariable("DECISIOQ_AUDIENCE") ?? "vinquery:api:decisioq";
var correlationId = $"auto-fleet-001-csharp-{DateTimeOffset.UtcNow:yyyyMMddHHmmss}";
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(45) };

var tokenResponse = await http.PostAsJsonAsync(identityUrl, new
{
    clientId = Required("DECISIOQ_CLIENT_ID"),
    clientSecret = Required("DECISIOQ_CLIENT_SECRET"),
    audience
});
tokenResponse.EnsureSuccessStatusCode();
var jwtToken = JsonDocument.Parse(await tokenResponse.Content.ReadAsStringAsync()).RootElement.GetProperty("jwtToken").GetString();

using var metadataRequest = new HttpRequestMessage(HttpMethod.Get, $"{catalogUrl}/decisioncatalog/decisions/AUTO-FLEET-001");
metadataRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);
metadataRequest.Headers.TryAddWithoutValidation("X-Correlation-Id", correlationId);
using var metadataResponse = await http.SendAsync(metadataRequest);
metadataResponse.EnsureSuccessStatusCode();

var executionRequest = new
{
    decisionId = "AUTO-FLEET-001",
    profileId = "balanced",
    scenarioId = "standard",
    algorithm = "TOPSIS",
    weightStrategy = "Expert",
    runSensitivity = false,
    requestContext = new { correlationId },
    options = new object[]
    {
        new { optionId = "VEHICLE-001", name = "Vehicle 001", values = new Dictionary<string,double> { ["lifecycle_cost"] = 18000, ["downtime_risk"] = 4, ["maintenance_trend"] = 72, ["utilization_criticality"] = 92, ["safety_rating"] = 4.5 } },
        new { optionId = "VEHICLE-002", name = "Vehicle 002", values = new Dictionary<string,double> { ["lifecycle_cost"] = 14500, ["downtime_risk"] = 3, ["maintenance_trend"] = 54, ["utilization_criticality"] = 76, ["safety_rating"] = 4 } }
    }
};

using var execution = new HttpRequestMessage(HttpMethod.Post, $"{decisionServiceUrl}/api/v1/decide")
{
    Content = JsonContent.Create(executionRequest)
};
execution.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);
execution.Headers.TryAddWithoutValidation("X-Correlation-Id", correlationId);
using var executionResponse = await http.SendAsync(execution);
Console.WriteLine(await executionResponse.Content.ReadAsStringAsync());
executionResponse.EnsureSuccessStatusCode();
