package com.chainvara;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * Chainvara server SDK for Java 11+ — https://www.chainvara.com/docs
 *
 * <p>One file, no dependency (java.net.http). Server side only: never ship a secret API key to a browser or an app.
 *
 * <pre>{@code
 * Chainvara cv = new Chainvara(System.getenv("CHAINVARA_API_KEY"));
 * Map<String, Object> wallet = cv.wallets.create(Map.of("network", "base-sepolia", "label", "Treasury"));
 * Map<String, Object> t = cv.transfers.create(Map.of("wallet_id", wallet.get("id"), "asset", "ETH", "amount", "0.01", "destination", "0x…"), null);
 * cv.transfers.waitFor((String) t.get("id"), Duration.ofSeconds(5), Duration.ofMinutes(10));
 *
 * // Webhooks: pass the RAW body, exactly as received.
 * Map<String, Object> event = Chainvara.verifyWebhook(rawBody, request.getHeader("fos-signature"), webhookSecret);
 * }</pre>
 *
 * Every POST carries an Idempotency-Key, so a retry never acts twice. JSON objects are {@code Map<String, Object>},
 * arrays {@code List<Object>}, numbers {@code BigDecimal}.
 */
public final class Chainvara {
    public static final String VERSION = "0.1.0";
    public static final List<String> FINAL_TRANSFER_STATUSES = List.of("confirmed", "failed", "rejected", "blocked", "canceled", "expired");
    private static final Pattern KEY = Pattern.compile("^fos_(test|live)_[0-9a-f]{12}_[0-9a-f]{64}$");

    private final String key;
    private final String base;
    private final int maxRetries;
    private final Duration timeout;
    private final HttpClient http;
    /** "test" or "live", from the key. */
    public final String mode;

    public final Wallets wallets = new Wallets();
    public final Transfers transfers = new Transfers();
    public final Operations operations = new Operations();
    public final Payouts payouts = new Payouts();
    public final Events events = new Events();
    public final Vaults vaults = new Vaults();
    public final Policy policy = new Policy();
    public final Addresses addresses = new Addresses();
    public final Reports reports = new Reports();
    public final Audit audit = new Audit();
    public final DepositAddresses depositAddresses = new DepositAddresses();
    public final Embedded embedded = new Embedded();
    public final Network network = new Network();
    public final Networks networks = new Networks();
    public final Payees payees = new Payees();
    public final Prices prices = new Prices();
    public final Tokens tokens = new Tokens();
    public final Swap swap = new Swap();
    public final Screening screening = new Screening();
    public final Security security = new Security();
    public final AddressProofs addressProofs = new AddressProofs();
    public final TravelRule travelRule = new TravelRule();
    public final Reserves reserves = new Reserves();

    public Chainvara(String apiKey) {
        this(apiKey, "https://www.chainvara.com", 2, Duration.ofSeconds(30));
    }

    public Chainvara(String apiKey, String baseUrl, int maxRetries, Duration timeout) {
        var m = KEY.matcher(apiKey == null ? "" : apiKey);
        if (!m.matches()) throw new IllegalArgumentException("Chainvara: invalid API key. Expected fos_test_… or fos_live_… (create one in Developers).");
        this.mode = m.group(1);
        this.key = apiKey;
        this.base = baseUrl.replaceAll("/+$", "") + "/api/v1";
        this.maxRetries = maxRetries;
        this.timeout = timeout;
        this.http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).followRedirects(HttpClient.Redirect.NEVER).build();
    }

    @Override
    public String toString() {
        return "Chainvara(mode=" + mode + ")"; // never the key
    }

    /** API or transport error: status 0 for network errors, a stable machine code, the request id for support. */
    public static final class ChainvaraException extends RuntimeException {
        private static final long serialVersionUID = 1L;
        public final int status;
        public final String type;
        public final String code;
        public final String requestId;

        public ChainvaraException(String message, int status, String type, String code, String requestId) {
            super(message);
            this.status = status;
            this.type = type;
            this.code = code;
            this.requestId = requestId;
        }
    }

    // ------------------------------------------------------------------------------------------------ transport

    /** Any endpoint: GET or POST {@code /api/v1 + path}. Returns the decoded JSON. */
    public Object request(String method, String path, Map<String, ?> body, Map<String, ?> query, String idempotencyKey) {
        var url = new StringBuilder(base).append(path);
        if (query != null) {
            String sep = "?";
            for (var e : query.entrySet()) {
                if (e.getValue() == null) continue;
                url.append(sep).append(enc(e.getKey())).append('=').append(enc(String.valueOf(e.getValue())));
                sep = "&";
            }
        }
        var b = HttpRequest.newBuilder(URI.create(url.toString())).timeout(timeout)
            .header("authorization", "Bearer " + key).header("accept", "application/json").header("user-agent", "chainvara-java/" + VERSION);
        if ("POST".equals(method)) {
            b.header("content-type", "application/json").header("idempotency-key", idempotencyKey != null ? idempotencyKey : "sdk_" + UUID.randomUUID());
            b.POST(HttpRequest.BodyPublishers.ofString(Json.stringify(body == null ? Map.of() : body), StandardCharsets.UTF_8));
        } else b.GET();
        HttpRequest req = b.build();
        for (int attempt = 0; ; attempt++) {
            HttpResponse<String> res = null;
            Exception netErr = null;
            try {
                res = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
            } catch (IOException e) {
                netErr = e;
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new ChainvaraException("Interrupted.", 0, "connection_error", "interrupted", null);
            }
            int status = res == null ? 0 : res.statusCode();
            boolean retryable = netErr != null || status == 429 || status >= 500;
            if (retryable && attempt < maxRetries) {
                double ra = 0;
                if (res != null) {
                    try {
                        ra = Double.parseDouble(res.headers().firstValue("retry-after").orElse("0"));
                    } catch (NumberFormatException ignored) {
                        ra = 0;
                    }
                }
                sleep(ra > 0 ? (long) (Math.min(ra, 60) * 1000) : (long) (500 * Math.pow(2, attempt)) + ThreadLocalRandom.current().nextLong(250));
                continue;
            }
            if (netErr != null) throw new ChainvaraException("Network error: " + netErr.getMessage(), 0, "connection_error", "network_error", null);
            String requestId = res.headers().firstValue("request-id").orElse(null);
            Object payload = null;
            try {
                payload = res.body() == null || res.body().isEmpty() ? null : Json.parse(res.body());
            } catch (IllegalArgumentException ignored) {
                payload = null;
            }
            if (status >= 400) {
                Map<?, ?> err = payload instanceof Map && ((Map<?, ?>) payload).get("error") instanceof Map ? (Map<?, ?>) ((Map<?, ?>) payload).get("error") : Map.of();
                throw new ChainvaraException(str(err.get("message"), "HTTP " + status), status, str(err.get("type"), "api_error"), str(err.get("code"), "http_error"), str(err.get("request_id"), requestId));
            }
            return payload;
        }
    }

    @SuppressWarnings("unchecked")
    private Map<String, Object> obj(String method, String path, Map<String, ?> body, Map<String, ?> query, String idem) {
        Object o = request(method, path, body, query, idem);
        return o instanceof Map ? (Map<String, Object>) o : new LinkedHashMap<>();
    }

    private static String enc(String s) {
        return URLEncoder.encode(s, StandardCharsets.UTF_8).replace("+", "%20");
    }

    private static String str(Object o, String fallback) {
        return o instanceof String && !((String) o).isEmpty() ? (String) o : fallback;
    }

    private static void sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    /** A map without null values (optional parameters): params("limit", 50, "tag", null). */
    public static Map<String, Object> params(Object... kv) {
        var m = new LinkedHashMap<String, Object>();
        for (int i = 0; i + 1 < kv.length; i += 2) if (kv[i + 1] != null) m.put(String.valueOf(kv[i]), kv[i + 1]);
        return m;
    }

    // ------------------------------------------------------------------------------------------------ resources

    public final class Wallets {
        /** { network, label?, external_user_id?, kind?, key_mode? (single | split | mpc | mpc_backup) }. */
        public Map<String, Object> create(Map<String, ?> p) { return obj("POST", "/wallets", p, null, null); }
        public Map<String, Object> list(Map<String, ?> query) { return obj("GET", "/wallets", null, query, null); }
        public Map<String, Object> get(String id) { return obj("GET", "/wallets/" + enc(id), null, null, null); }
        public Map<String, Object> balances(String id, boolean refresh) { return obj("GET", "/wallets/" + enc(id) + "/balances", null, refresh ? Map.of("refresh", "true") : null, null); }
        public Map<String, Object> transactions(String id, Integer limit) { return obj("GET", "/wallets/" + enc(id) + "/transactions", null, params("limit", limit), null); }
        /** Token approvals of an EVM wallet that can still be used (ERC-20, NFT operators, Permit2), riskiest first. */
        public Map<String, Object> allowances(String id) { return obj("GET", "/wallets/" + enc(id) + "/allowances", null, null, null); }
        /** Requests the revocation of one approval (kind: erc20 | nft_operator | permit2). */
        /** One wallet per end user and network: created on first call, returned afterwards (the server deduplicates). */
        public Map<String, Object> forUser(String externalUserId, String network, String label) {
            return obj("POST", "/wallets", params("network", network, "external_user_id", externalUserId, "label", label), null, null);
        }
        /** Renews both shares of an MPC wallet with your co-signer (same address; older shares stop working). */
        public Map<String, Object> refreshKeys(String id) { return obj("POST", "/wallets/" + enc(id) + "/refresh-keys", Map.of(), null, null); }
        public Map<String, Object> revokeAllowance(String id, String kind, String token, String spender, String idempotencyKey) {
            return obj("POST", "/wallets/" + enc(id) + "/allowances", Map.of("kind", kind, "token", token, "spender", spender), null, idempotencyKey);
        }
    }

    public final class Transfers {
        /** { wallet_id, asset, amount, destination, note?, fee_level?, external_id?, tags?, travel_rule? }. */
        public Map<String, Object> create(Map<String, ?> p, String idempotencyKey) { return obj("POST", "/transfers", p, null, idempotencyKey); }
        /** The policy decision a transfer would get, without creating it. */
        public Map<String, Object> preview(Map<String, ?> p) { return obj("POST", "/transfers/preview", p, null, null); }
        /** Newest first; when has_more, pass next_cursor as starting_after. Filters: status, wallet_id, external_id, tag, limit. */
        public Map<String, Object> list(Map<String, ?> query) { return obj("GET", "/transfers", null, query, null); }
        public Map<String, Object> get(String id) { return obj("GET", "/transfers/" + enc(id), null, null, null); }
        public Map<String, Object> cancel(String id) { return obj("POST", "/transfers/" + enc(id) + "/cancel", null, null, null); }
        public Map<String, Object> speedUp(String id) { return obj("POST", "/transfers/" + enc(id) + "/speed-up", null, null, null); }
        public Map<String, Object> cancelOnchain(String id) { return obj("POST", "/transfers/" + enc(id) + "/cancel-onchain", null, null, null); }
        /** Replaces the accounting tags (never part of what was approved or signed). */
        public Map<String, Object> setTags(String id, List<String> tags) { return obj("POST", "/transfers/" + enc(id) + "/tags", Map.of("tags", tags), null, null); }

        /** Every transfer matching the filters, newest first, page after page. */
        public Iterable<Map<String, Object>> iterate(Map<String, ?> filters) {
            return () -> new Iterator<>() {
                private Iterator<Object> page = Collections.emptyIterator();
                private String after = null;
                private boolean more = true;

                @SuppressWarnings("unchecked")
                private void fill() {
                    while (!page.hasNext() && more) {
                        var q = new LinkedHashMap<String, Object>();
                        if (filters != null) q.putAll(filters);
                        q.put("limit", 200);
                        if (after != null) q.put("starting_after", after);
                        var p = list(q);
                        page = ((List<Object>) p.getOrDefault("data", List.of())).iterator();
                        after = p.get("next_cursor") instanceof String ? (String) p.get("next_cursor") : null;
                        more = Boolean.TRUE.equals(p.get("has_more")) && after != null;
                    }
                }

                public boolean hasNext() {
                    fill();
                    return page.hasNext();
                }

                @SuppressWarnings("unchecked")
                public Map<String, Object> next() {
                    fill();
                    if (!page.hasNext()) throw new NoSuchElementException();
                    return (Map<String, Object>) page.next();
                }
            };
        }

        /** Polls until the transfer reaches a final status (or {@code until} holds). */
        public Map<String, Object> waitFor(String id, Duration interval, Duration timeout, Predicate<Map<String, Object>> until) {
            long deadline = System.nanoTime() + timeout.toNanos();
            while (true) {
                var t = get(id);
                if (until != null ? until.test(t) : FINAL_TRANSFER_STATUSES.contains(String.valueOf(t.get("status")))) return t;
                if (System.nanoTime() > deadline) throw new ChainvaraException("Transfer " + id + " still " + t.get("status") + " after timeout.", 408, "timeout", "wait_timeout", null);
                sleep(interval.toMillis());
            }
        }

        public Map<String, Object> waitFor(String id, Duration interval, Duration timeout) { return waitFor(id, interval, timeout, null); }
    }

    public final class Operations {
        /** { wallet_id, type, … }: tokens, swaps, staking, CCTP, contract calls (contracts:write) — same policy and signing as transfers. */
        public Map<String, Object> create(Map<String, ?> p, String idempotencyKey) { return obj("POST", "/operations", p, null, idempotencyKey); }
        public Map<String, Object> list(Integer limit) { return obj("GET", "/operations", null, params("limit", limit), null); }
    }

    public final class Payouts {
        /** { wallet_id, asset, items: [{ destination, amount, reference? }], reference? } — up to 500 lines. */
        public Map<String, Object> create(Map<String, ?> p, String idempotencyKey) { return obj("POST", "/payouts", p, null, idempotencyKey); }
        public Map<String, Object> get(String id) { return obj("GET", "/payouts/" + enc(id), null, null, null); }
        public Map<String, Object> list(Integer limit) { return obj("GET", "/payouts", null, params("limit", limit), null); }
    }

    public final class Events {
        /** after: every event after this seq, oldest first, without gaps (next_after for the next call). */
        public Map<String, Object> list(Long after, String type, Integer limit) { return obj("GET", "/events", null, params("after", after, "type", type, "limit", limit), null); }
    }

    public final class Vaults {
        public Map<String, Object> list() { return obj("GET", "/vaults", null, null, null); }
        public Map<String, Object> create(String name, String description) { return obj("POST", "/vaults", params("name", name, "description", description), null, null); }
        /** Stops every outflow of the vault until it is unfrozen in the console (never by API). */
        public Map<String, Object> freeze(String id, String reason) { return obj("POST", "/vaults/" + enc(id) + "/freeze", Map.of("reason", reason), null, null); }
        /** Moves a wallet into a vault; null takes it out of its vault. */
        public Map<String, Object> assignWallet(String walletId, String vaultId) {
            var b = new LinkedHashMap<String, Object>();
            b.put("vault_id", vaultId);
            return obj("POST", "/wallets/" + enc(walletId) + "/vault", b, null, null);
        }
    }

    public final class Policy {
        public Map<String, Object> get() { return obj("GET", "/policy", null, null, null); }
        /** What a candidate policy would change on the last 200 requests (nothing is published). */
        public Map<String, Object> impact(Map<String, ?> candidate) { return obj("POST", "/policy/impact", Map.of("policy", candidate), null, null); }
    }

    public final class Addresses {
        public Map<String, Object> list() { return obj("GET", "/addresses", null, null, null); }
        /** { network, address, label, note?, beneficiary? } (scope addresses:write; screened, cooldown applies). */
        public Map<String, Object> add(Map<String, ?> p) { return obj("POST", "/addresses", p, null, null); }
        public Map<String, Object> revoke(String id) { return obj("POST", "/addresses/" + enc(id) + "/revoke", null, null, null); }
    }

    public final class Reports {
        public Map<String, Object> ledger(String from, String to) { return obj("GET", "/reports/ledger", null, params("from", from, "to", to), null); }
        /** Realized and unrealized gains (method: fifo | average). */
        public Map<String, Object> gains(String from, String to, String method) { return obj("GET", "/reports/gains", null, params("from", from, "to", to, "method", method), null); }
    }

    public final class Audit {
        public Map<String, Object> list(Long after, String since, String action, Integer limit) { return obj("GET", "/audit", null, params("after", after, "since", since, "action", action, "limit", limit), null); }
        public Map<String, Object> verify() { return obj("GET", "/audit/verify", null, null, null); }
    }

    public final class DepositAddresses {
        /** Every deposit address of one of your users (one wallet per network); calling again returns the same ones. networks null: defaults. */
        public Map<String, Object> create(String externalUserId, List<String> networks, String label) {
            return obj("POST", "/deposit-addresses", params("external_user_id", externalUserId, "networks", networks, "label", label), null, null);
        }
    }

    /** Embedded wallets: relay the device SDK's calls from your backend, with external_user_id from your own session. */
    public final class Embedded {
        public Map<String, Object> relay(String path, Map<String, ?> body) {
            if (!List.of("/embedded/wallets", "/embedded/sign", "/embedded/backup").contains(path)) throw new IllegalArgumentException("Unknown embedded path.");
            return obj("POST", path, body, null, null);
        }
    }

    /** Chainvara network: payment requests and bilateral net settlement with connected organizations. */
    public final class Network {
        /** { to: "@handle", network, asset, amount, reference, note?, ttl_days? }. */
        public Map<String, Object> requestPayment(Map<String, ?> p, String idempotencyKey) { return obj("POST", "/network/requests", p, null, idempotencyKey); }
        public Map<String, Object> requests(String direction, String status) { return obj("GET", "/network/requests", null, params("direction", direction, "status", status), null); }
        /** Pays an incoming request from one of your wallets: a normal transfer under your policy and approvals. */
        public Map<String, Object> payRequest(String requestId, String walletId, String idempotencyKey) {
            return obj("POST", "/network/requests/" + enc(requestId) + "/pay", Map.of("wallet_id", walletId), null, idempotencyKey);
        }
        public Map<String, Object> closeRequest(String requestId) { return obj("POST", "/network/requests/" + enc(requestId) + "/close", Map.of(), null, null); }
        /** { counterparty, direction: they_owe | we_owe, network, asset, amount, reference }: counts once the counterparty confirms. */
        public Map<String, Object> recordObligation(Map<String, ?> p, String idempotencyKey) { return obj("POST", "/network/obligations", p, null, idempotencyKey); }
        public Map<String, Object> obligations() { return obj("GET", "/network/obligations", null, null, null); }
        /** action: confirm, dispute or cancel. */
        public Map<String, Object> answerObligation(String obligationId, String action) {
            if (!List.of("confirm", "dispute", "cancel").contains(action)) throw new IllegalArgumentException("action must be confirm, dispute or cancel.");
            return obj("POST", "/network/obligations/" + enc(obligationId) + "/" + action, Map.of(), null, null);
        }
        /** Net of confirmed obligations per counterparty and asset. */
        public Map<String, Object> positions() { return obj("GET", "/network/positions", null, null, null); }
        /** The net debtor settles the whole position with one transfer. */
        public Map<String, Object> settle(String counterparty, String assetId, String walletId, String idempotencyKey) {
            return obj("POST", "/network/settlements", params("counterparty", counterparty, "asset_id", assetId, "wallet_id", walletId), null, idempotencyKey);
        }
        public Map<String, Object> settlements() { return obj("GET", "/network/settlements", null, null, null); }
    }

    public final class Networks {
        public Map<String, Object> list() { return obj("GET", "/networks", null, null, null); }
        /** Current fee estimates for a typical transfer at each fee_level (low, medium, high). */
        public Map<String, Object> fees(String network) { return obj("GET", "/networks/" + enc(network) + "/fees", null, null, null); }
    }

    /** Connected organizations you can pay with destination "@handle". */
    public final class Payees {
        public Map<String, Object> list() { return obj("GET", "/payees", null, null, null); }
    }

    public final class Prices {
        public Map<String, Object> list() { return obj("GET", "/prices", null, null, null); }
    }

    /** Tokens your organization issued, with live supply and market data. */
    public final class Tokens {
        public Map<String, Object> list() { return obj("GET", "/tokens", null, null, null); }
    }

    public final class Swap {
        /** Informational quote; operations.create with type "swap" swaps with a guaranteed minimum. */
        public Map<String, Object> quote(String walletId, String sell, String buy, String amount, Integer slippageBps) {
            return obj("GET", "/swap/quote", null, params("wallet_id", walletId, "sell", sell, "buy", buy, "amount", amount, "slippage_bps", slippageBps), null);
        }
    }

    public final class Screening {
        /** Sanctions screening (OFAC SDN) of any address. */
        public Map<String, Object> check(String network, String address) { return obj("GET", "/screening", null, params("network", network, "address", address), null); }
        /** Screening of the senders of your deposits (status: clear, flagged, released, reported; null for all). */
        public Map<String, Object> inbound(String status, Integer limit) { return obj("GET", "/screening/inbound", null, params("status", status, "limit", limit), null); }
    }

    public final class Security {
        /** Score 0-100 and every check with its fix. */
        public Map<String, Object> posture() { return obj("GET", "/security", null, null, null); }
    }

    /** Self-hosted wallet ownership proofs: create() returns the message and the link (url) to send the owner. */
    public final class AddressProofs {
        public Map<String, Object> create(String network, String address, String label) {
            return obj("POST", "/address-proofs", params("network", network, "address", address, "label", label), null, null);
        }
        public Map<String, Object> list() { return obj("GET", "/address-proofs", null, null, null); }
        public Map<String, Object> submitSignature(String id, String signature) {
            return obj("POST", "/address-proofs/" + enc(id) + "/signature", Map.of("signature", signature), null, null);
        }
    }

    public final class TravelRule {
        /** Messages exchanged with organizations on the Chainvara network (direction: incoming, outgoing or null). */
        public Map<String, Object> messages(String direction) { return obj("GET", "/travel-rule/messages", null, params("direction", direction), null); }
        /** As beneficiary: confirm you received the originator information. */
        public Map<String, Object> acknowledge(String messageId) { return obj("POST", "/travel-rule/messages/" + enc(messageId) + "/acknowledge", Map.of(), null, null); }
    }

    /** Proof of reserves (scope reserves:write). */
    public final class Reserves {
        /** customers: [{ user_id, balances: { "BTC": "0.25" } }]; commits them in a Merkle sum tree and reads your reserves. */
        public Map<String, Object> createSnapshot(List<? extends Map<String, ?>> customers, String idempotencyKey) {
            return obj("POST", "/reserves/snapshots", Map.of("customers", customers), null, idempotencyKey);
        }
        /** One customer's inclusion proof, to give to that customer. */
        public Map<String, Object> proof(String snapshotId, String userId) { return obj("GET", "/reserves/snapshots/" + enc(snapshotId) + "/proof", null, params("user_id", userId), null); }
    }

    // ------------------------------------------------------------------------------------------------ webhooks, co-signer

    private static String hmacHex(String secret, String data) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            var out = new StringBuilder();
            for (byte x : mac.doFinal(data.getBytes(StandardCharsets.UTF_8))) out.append(String.format("%02x", x));
            return out.toString();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    /** fos-signature header for a body: t=&lt;unix&gt;,v1=&lt;hex HMAC-SHA256 of "t.body"&gt;. For testing your endpoint. */
    public static String signWebhookPayload(String rawBody, String secret, long timestamp) {
        return "t=" + timestamp + ",v1=" + hmacHex(secret, timestamp + "." + rawBody);
    }

    public static Map<String, Object> verifyWebhook(String rawBody, String signatureHeader, String secret) {
        return verifyWebhook(rawBody, signatureHeader, secret, 300, System.currentTimeMillis() / 1000);
    }

    /**
     * Checks the fos-signature of a webhook (the RAW body, exactly as received) and returns the event. During a secret
     * rotation the header carries one v1 per secret: any of them may match.
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> verifyWebhook(String rawBody, String signatureHeader, String secret, long toleranceSeconds, long now) {
        if (signatureHeader == null || signatureHeader.isEmpty()) throw new ChainvaraException("Missing fos-signature header.", 400, "signature_error", "missing_signature", null);
        Long t = null;
        var v1s = new ArrayList<String>();
        for (String part : signatureHeader.split(",")) {
            int i = part.indexOf('=');
            if (i < 0) continue;
            String k = part.substring(0, i).trim(), v = part.substring(i + 1).trim();
            if (k.equals("t")) {
                try {
                    t = Long.parseLong(v);
                } catch (NumberFormatException ignored) {
                    t = null;
                }
            }
            if (k.equals("v1") && v.matches("[0-9a-f]{64}")) v1s.add(v);
        }
        if (t == null || v1s.isEmpty()) throw new ChainvaraException("Malformed fos-signature header.", 400, "signature_error", "malformed_signature", null);
        if (Math.abs(now - t) > toleranceSeconds) throw new ChainvaraException("Webhook signature timestamp is outside the tolerance window.", 400, "signature_error", "timestamp_out_of_range", null);
        byte[] expected = hmacHex(secret, t + "." + rawBody).getBytes(StandardCharsets.UTF_8);
        boolean ok = false;
        for (String v : v1s) ok |= MessageDigest.isEqual(expected, v.getBytes(StandardCharsets.UTF_8));
        if (!ok) throw new ChainvaraException("Webhook signature does not match.", 400, "signature_error", "invalid_signature", null);
        Object parsed = Json.parse(rawBody);
        if (!(parsed instanceof Map)) throw new ChainvaraException("Webhook body is not a JSON object.", 400, "signature_error", "unexpected_payload", null);
        return (Map<String, Object>) parsed;
    }

    /** Verifies an API co-signer request (transfer.sign_request) and returns it. */
    public static Map<String, Object> verifyCosignerRequest(String rawBody, String signatureHeader, String secret) {
        var req = verifyWebhook(rawBody, signatureHeader, secret);
        if (!"transfer.sign_request".equals(req.get("type"))) throw new ChainvaraException("Not a co-signer request.", 400, "signature_error", "unexpected_type", null);
        return req;
    }

    /** Signed answer (HTTP 200) to a co-signer request: [body, fos-signature header]. action: approve | reject. */
    @SuppressWarnings("unchecked")
    public static String[] cosignerResponse(Map<String, Object> req, String action, String secret, String reason) {
        if (!action.equals("approve") && !action.equals("reject")) throw new IllegalArgumentException("action must be approve or reject");
        var p = new LinkedHashMap<String, Object>();
        p.put("request_id", req.get("request_id"));
        p.put("transfer_id", ((Map<String, Object>) req.get("data")).get("id"));
        p.put("action", action);
        if (reason != null) p.put("reason", reason);
        String body = Json.stringify(p);
        return new String[] { body, signWebhookPayload(body, secret, System.currentTimeMillis() / 1000) };
    }

    // ------------------------------------------------------------------------------------------------ JSON

    /** Minimal, strict JSON: objects → LinkedHashMap, arrays → ArrayList, numbers → BigDecimal. */
    public static final class Json {
        private final String s;
        private int i;

        private Json(String s) {
            this.s = s;
        }

        public static Object parse(String text) {
            var p = new Json(text);
            p.ws();
            Object v = p.value(0);
            p.ws();
            if (p.i != p.s.length()) throw new IllegalArgumentException("Trailing characters in JSON.");
            return v;
        }

        private void ws() {
            while (i < s.length() && " \t\r\n".indexOf(s.charAt(i)) >= 0) i++;
        }

        private Object value(int depth) {
            if (depth > 256) throw new IllegalArgumentException("JSON too deep.");
            if (i >= s.length()) throw new IllegalArgumentException("Unexpected end of JSON.");
            char c = s.charAt(i);
            if (c == '{') {
                i++;
                var m = new LinkedHashMap<String, Object>();
                ws();
                if (consume('}')) return m;
                do {
                    ws();
                    String k = string();
                    ws();
                    expect(':');
                    ws();
                    m.put(k, value(depth + 1));
                    ws();
                } while (consume(','));
                expect('}');
                return m;
            }
            if (c == '[') {
                i++;
                var l = new ArrayList<Object>();
                ws();
                if (consume(']')) return l;
                do {
                    ws();
                    l.add(value(depth + 1));
                    ws();
                } while (consume(','));
                expect(']');
                return l;
            }
            if (c == '"') return string();
            if (s.startsWith("true", i)) {
                i += 4;
                return Boolean.TRUE;
            }
            if (s.startsWith("false", i)) {
                i += 5;
                return Boolean.FALSE;
            }
            if (s.startsWith("null", i)) {
                i += 4;
                return null;
            }
            int start = i;
            while (i < s.length() && "+-0123456789.eE".indexOf(s.charAt(i)) >= 0) i++;
            if (start == i) throw new IllegalArgumentException("Unexpected character in JSON at " + i + ".");
            return new BigDecimal(s.substring(start, i));
        }

        private boolean consume(char c) {
            if (i < s.length() && s.charAt(i) == c) {
                i++;
                return true;
            }
            return false;
        }

        private void expect(char c) {
            if (i >= s.length() || s.charAt(i) != c) throw new IllegalArgumentException("Expected '" + c + "' in JSON at " + i + ".");
            i++;
        }

        private String string() {
            expect('"');
            var b = new StringBuilder();
            while (true) {
                if (i >= s.length()) throw new IllegalArgumentException("Unterminated JSON string.");
                char c = s.charAt(i++);
                if (c == '"') return b.toString();
                if (c != '\\') {
                    b.append(c);
                    continue;
                }
                if (i >= s.length()) throw new IllegalArgumentException("Bad escape in JSON.");
                char e = s.charAt(i++);
                switch (e) {
                    case '"': b.append('"'); break;
                    case '\\': b.append('\\'); break;
                    case '/': b.append('/'); break;
                    case 'b': b.append('\b'); break;
                    case 'f': b.append('\f'); break;
                    case 'n': b.append('\n'); break;
                    case 'r': b.append('\r'); break;
                    case 't': b.append('\t'); break;
                    case 'u':
                        if (i + 4 > s.length()) throw new IllegalArgumentException("Bad escape in JSON.");
                        b.append((char) Integer.parseInt(s.substring(i, i + 4), 16));
                        i += 4;
                        break;
                    default: throw new IllegalArgumentException("Bad escape in JSON.");
                }
            }
        }

        public static String stringify(Object v) {
            var b = new StringBuilder();
            write(b, v);
            return b.toString();
        }

        private static void write(StringBuilder b, Object v) {
            if (v == null) b.append("null");
            else if (v instanceof String) quote(b, (String) v);
            else if (v instanceof Boolean || v instanceof Integer || v instanceof Long || v instanceof java.math.BigInteger) b.append(v);
            else if (v instanceof BigDecimal) b.append(((BigDecimal) v).toPlainString());
            else if (v instanceof Number) b.append(new BigDecimal(v.toString()).toPlainString());
            else if (v instanceof Map) {
                b.append('{');
                boolean first = true;
                for (var e : ((Map<?, ?>) v).entrySet()) {
                    if (!first) b.append(',');
                    first = false;
                    quote(b, String.valueOf(e.getKey()));
                    b.append(':');
                    write(b, e.getValue());
                }
                b.append('}');
            } else if (v instanceof Iterable) {
                b.append('[');
                boolean first = true;
                for (Object x : (Iterable<?>) v) {
                    if (!first) b.append(',');
                    first = false;
                    write(b, x);
                }
                b.append(']');
            } else quote(b, v.toString());
        }

        private static void quote(StringBuilder b, String s) {
            b.append('"');
            for (char c : s.toCharArray()) {
                switch (c) {
                    case '"': b.append("\\\""); break;
                    case '\\': b.append("\\\\"); break;
                    case '\n': b.append("\\n"); break;
                    case '\r': b.append("\\r"); break;
                    case '\t': b.append("\\t"); break;
                    default:
                        if (c < 0x20) b.append(String.format("\\u%04x", (int) c));
                        else b.append(c);
                }
            }
            b.append('"');
        }
    }
}
