// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Anil Jangra
// A minimal RiskRouter client and demo. JDK 17+, no dependencies.
// Run: RISKROUTER_API_KEY=rr_sandbox_... java RiskRouterDemo.java [output-dir]
//
// Server to server only: your backend holds the key, never a browser.
// In production, parse responses with the JSON library you already use; the
// tiny field() helper below exists only so this file needs nothing but the JDK.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.HexFormat;
import java.util.UUID;
import java.util.regex.Pattern;

public class RiskRouterDemo {
    static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
    static final String BASE = System.getenv().getOrDefault("RISKROUTER_BASE", "https://api.riskrouter.eu").replaceAll("/$", "");
    static final String KEY = System.getenv("RISKROUTER_API_KEY");

    static String call(String method, String path, String json, boolean withKey, String idempotencyKey) throws Exception {
        var builder = HttpRequest.newBuilder(URI.create(BASE + path)).timeout(Duration.ofSeconds(10)).header("Accept", "application/json");
        if (withKey && KEY != null) builder.header("Authorization", "Bearer " + KEY);
        if (idempotencyKey != null) builder.header("Idempotency-Key", idempotencyKey);
        builder.method(method, json == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(json));
        if (json != null) builder.header("Content-Type", "application/json");
        var response = HTTP.send(builder.build(), HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() >= 400) {
            throw new IllegalStateException(response.statusCode() + " " + field(response.body(), "code") + ": " + field(response.body(), "message"));
        }
        return response.body();
    }

    /** First value of "name" in a JSON text: a string, number or boolean. Demo use only. */
    static String field(String json, String name) {
        var m = Pattern.compile("\"" + Pattern.quote(name) + "\"\\s*:\\s*(\"([^\"]*)\"|[-0-9.]+|true|false|null)").matcher(json);
        return m.find() ? (m.group(2) != null ? m.group(2) : m.group(1)) : null;
    }

    public static void main(String[] args) throws Exception {
        var out = Path.of(args.length > 0 ? args[0] : ".");
        var quote = "{\"active_vertical\":\"mobility\",\"selected_components\":{\"commuter_roadside\":true,\"battery_hardware_theft\":true}}";

        // Priced by the server, never by you. No key is sent: nothing is recorded.
        var priced = call("POST", "/api/v1/quote", "{\"active_vertical\":\"mobility\",\"selected_components\":{\"commuter_roadside\":true}}", false, null);
        System.out.println("PRICED     EUR " + field(priced, "total_monthly_premium") + "/month, recorded: " + field(priced, "persisted"));

        // Retrying with the same idempotency key never records twice.
        // Check persisted: a 200 prices the quote even when the ledger refused the write.
        var idem = UUID.randomUUID().toString();
        var first = call("POST", "/api/v1/quote", quote, true, idem);
        var again = call("POST", "/api/v1/quote", quote, true, idem);
        System.out.println("RECORDED   entry " + field(first, "chain_index") + ", recorded: " + field(first, "persisted"));
        System.out.println("RETRIED    same entry " + field(again, "chain_index") + ", replayed: " + field(again, "replayed"));

        // Record that a regulated decision existed, without sending it. Keep the salt with your record.
        var note = "Demands and needs, 23 Sept 2026: commutes daily by e-bike, wants theft and roadside cover. Customer: Jan Peeters.";
        var salt = new byte[16];
        new SecureRandom().nextBytes(salt);
        var sha = MessageDigest.getInstance("SHA-256");
        sha.update(salt);
        var digest = HexFormat.of().formatHex(sha.digest(note.getBytes(StandardCharsets.UTF_8)));
        var evidence = call("POST", "/api/v2/evidence", "{\"record_digest\":\"" + digest + "\",\"kind\":\"idd.demands-needs\"}", true, null);
        var leaf = field(evidence, "leaf_index");
        System.out.println("EVIDENCE   leaf " + leaf + ", only the digest left this machine");

        Files.writeString(out.resolve("export.json"), call("GET", "/api/v1/ledger/export", null, true, null));
        Files.writeString(out.resolve("evidence-proof.json"), call("GET", "/api/v2/evidence/proof?leaf_index=" + leaf, null, true, null));
        System.out.println("SAVED      export.json, evidence-proof.json in " + out);
    }
}
