// TEYGU Shield v1.6 — Seviye 2: Java 17+ / Spring Boot Kritik İşlem Kapısı
// Harici kütüphane gerektirmeden standart `javax.crypto.Mac` (HmacSHA256) ile ham gövdeyi
// imzalar; kritik işlemler için varsayılan fail-closed, gölge/okuma uçları için fail-open sunar.

package tr.teygu.connector;

import java.net.URI;
import java.io.IOException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public final class TeyguShieldGuard {
    private final String shieldBaseUrl;
    private final byte[] clientHmacKey;
    private final boolean failOpenOnUnavailable;
    private final HttpClient http;

    public TeyguShieldGuard(String shieldBaseUrl, String clientHmacKeyHex, boolean failOpenOnUnavailable) {
        this.shieldBaseUrl = shieldBaseUrl.replaceAll("/+$", "");
        this.clientHmacKey = (clientHmacKeyHex != null && !clientHmacKeyHex.isBlank())
                ? HexFormat.of().parseHex(clientHmacKeyHex.trim())
                : null;
        this.failOpenOnUnavailable = failOpenOnUnavailable;
        this.http = HttpClient.newBuilder()
                .connectTimeout(Duration.ofMillis(300))
                .build();
    }

    private String computeHmacSha256Hex(byte[] bodyBytes) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(this.clientHmacKey, "HmacSHA256"));
        return HexFormat.of().formatHex(mac.doFinal(bodyBytes));
    }

    public String requestExecutionPermit(String evaluateRequestJson) throws Exception {
        byte[] bodyBytes = evaluateRequestJson.getBytes(StandardCharsets.UTF_8);
        HttpRequest.Builder req = HttpRequest.newBuilder()
                .uri(URI.create(shieldBaseUrl + "/v1/evaluate"))
                .timeout(Duration.ofMillis(1500))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofByteArray(bodyBytes));

        if (this.clientHmacKey != null) {
            req.header("X-Teygu-Client-Mac", computeHmacSha256Hex(bodyBytes));
        }

        try {
            HttpResponse<String> resp = http.send(req.build(), HttpResponse.BodyHandlers.ofString());
            String body = resp.body() != null ? resp.body() : "";
            if (resp.statusCode() != 200 || !resp.headers().allValues("X-Teygu-Decision").equals(java.util.List.of("allow"))) {
                throw new SecurityException("TEYGU Shield did not issue an enforce-mode permit (HTTP " + resp.statusCode() + ")");
            }
            return body;
        } catch (IOException netErr) {
            if (this.failOpenOnUnavailable) {
                return "{\"allowed\":true,\"decision\":\"FAIL_OPEN_FALLBACK\"}";
            }
            throw new IllegalStateException("TEYGU Shield unreachable (fail-closed): " + netErr.getMessage(), netErr);
        }
    }
}
