// Carga personas y sus autorizaciones en el registro de habeas data desde un CSV.
//
// Uso (Java 21+, un solo archivo, sin dependencias):
//   export INTEGRATION_API_TOKEN=nxl_...
//   export INTEGRATION_API_URL=http://localhost:4100/integration/v1   # opcional
//   java SendBatch.java [ruta/al/archivo.csv]   # por defecto ../people.csv
//
// La Idempotency-Key se deriva del contenido de cada lote: volver a ejecutar el
// programa con el mismo archivo devuelve el resultado original (HTTP 200).
//
// Java no trae un parser JSON: aquí el cuerpo se arma a mano y la respuesta se
// imprime tal cual. En producción use Jackson o Gson para ambas cosas.
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.time.Duration;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
import java.util.regex.Pattern;

public class SendBatch {
    static final int BATCH_SIZE = 1000;
    static final int MAX_ATTEMPTS = 5;
    static final String API_URL = System.getenv().getOrDefault("INTEGRATION_API_URL", "http://localhost:4100/integration/v1").replaceAll("/$", "");
    static final String TOKEN = System.getenv("INTEGRATION_API_TOKEN");
    static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();

    public static void main(String[] args) throws Exception {
        if (TOKEN == null || TOKEN.isEmpty()) fail("Defina INTEGRATION_API_TOKEN con el token creado en el portal (Integraciones).");
        Path csv = Path.of(args.length > 0 ? args[0] : "../people.csv");

        System.out.println("Ping: " + send("GET", "/ping", null, null).body());

        // CSV sencillo (sin comas dentro de los campos). En producción use
        // una biblioteca como Apache Commons CSV.
        List<String> lines = Files.readAllLines(csv, StandardCharsets.UTF_8).stream().filter(l -> !l.isBlank()).toList();
        List<String> columns = List.of(lines.get(0).split(","));
        List<String> records = new ArrayList<>();
        for (String line : lines.subList(1, lines.size())) {
            String[] values = line.split(",", -1);
            java.util.function.Function<String, String> get = name -> values[columns.indexOf(name)].trim();
            String authorization = "{" + field("authorizedOn", get.apply("authorizedOn")) + "," + field("channel", get.apply("channel"))
                    + optional("policyVersion", get.apply("policyVersion")) + optional("evidenceReference", get.apply("evidenceReference")) + "}";
            records.add("{" + field("documentType", get.apply("documentType")) + "," + field("documentNumber", get.apply("documentNumber"))
                    + "," + field("fullName", get.apply("fullName")) + optional("email", get.apply("email")) + optional("phone", get.apply("phone"))
                    + ",\"authorization\":" + authorization + "}");
        }

        for (int start = 0; start < records.size(); start += BATCH_SIZE) {
            List<String> chunk = records.subList(start, Math.min(start + BATCH_SIZE, records.size()));
            String body = "{" + field("externalReference", csv.getFileName().toString()) + ",\"records\":[" + String.join(",", chunk) + "]}";
            byte[] hash = MessageDigest.getInstance("SHA-256").digest(body.getBytes(StandardCharsets.UTF_8));
            String key = "personas-" + HexFormat.of().formatHex(hash).substring(0, 32);
            HttpResponse<String> res = send("POST", "/authorizations", body, key);

            boolean replayed = res.headers().firstValue("Idempotent-Replayed").orElse("").equals("true");
            System.out.println("\nHTTP " + res.statusCode() + (replayed ? " (reintento: resultado original)" : ""));
            var counts = Pattern.compile("\"counts\":\\{[^}]*\\}").matcher(res.body());
            if (counts.find()) System.out.println("  " + counts.group());
            // El índice de cada registro rechazado + 2 es su línea en el CSV (la 1 es el encabezado).
            var rejected = Pattern.compile("\\{\"index\":(\\d+),\"status\":\"rejected\",\"subjectId\":null,\"issues\":(\\[[^\\]]*\\])").matcher(res.body());
            while (rejected.find()) {
                int line = start + Integer.parseInt(rejected.group(1)) + 2;
                System.out.println("  Rechazado · línea " + line + " del CSV: " + rejected.group(2));
            }
        }
    }

    // Envía la solicitud; reintenta errores de red, 409, 429 y 5xx con el mismo cuerpo.
    static HttpResponse<String> send(String method, String path, String body, String idempotencyKey) throws InterruptedException {
        for (int attempt = 1; ; attempt++) {
            long wait = 1L << (attempt - 1);
            var request = HttpRequest.newBuilder(URI.create(API_URL + path)).timeout(Duration.ofSeconds(60))
                    .header("Authorization", "Bearer " + TOKEN)
                    .method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8));
            if (body != null) request.header("Content-Type", "application/json").header("Idempotency-Key", idempotencyKey);
            try {
                HttpResponse<String> res = HTTP.send(request.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
                int status = res.statusCode();
                if (status < 300) return res;
                boolean retryable = status == 409 || status == 429 || status >= 500;
                if (!retryable || attempt == MAX_ATTEMPTS) fail("Error " + status + ": " + res.body());
                wait = res.headers().firstValue("Retry-After").map(Long::parseLong).orElse(wait);
            } catch (java.io.IOException e) {
                if (attempt == MAX_ATTEMPTS) fail("No se pudo conectar con la API: " + e.getMessage());
            }
            System.out.println("  Reintento " + attempt + "/" + (MAX_ATTEMPTS - 1) + " en " + wait + " s…");
            Thread.sleep(wait * 1000);
        }
    }

    static String field(String name, String value) {
        return "\"" + name + "\":\"" + escape(value) + "\"";
    }

    // Los campos opcionales vacíos se omiten.
    static String optional(String name, String value) {
        return value.isEmpty() ? "" : "," + field(name, value);
    }

    static String escape(String s) {
        StringBuilder out = new StringBuilder();
        for (char c : s.toCharArray()) {
            switch (c) {
                case '"' -> out.append("\\\"");
                case '\\' -> out.append("\\\\");
                case '\n' -> out.append("\\n");
                case '\r' -> out.append("\\r");
                case '\t' -> out.append("\\t");
                default -> out.append(c < 0x20 ? String.format("\\u%04x", (int) c) : String.valueOf(c));
            }
        }
        return out.toString();
    }

    static void fail(String message) {
        System.err.println(message);
        System.exit(1);
    }
}
