import java.net.URI;
// Requires com.fasterxml.jackson.core:jackson-databind 2.x for strict receipt parsing.
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Instant;
import java.time.Duration;
import java.util.UUID;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

class ReadableIngestionExample {
  public static void main(String[] args) throws Exception {
    String key = System.getenv("READABLE_INGESTION_KEY");
    String site = System.getenv("READABLE_SITE_ID");
    String integration = System.getenv("READABLE_INTEGRATION_ID");
    if (key == null || site == null || integration == null) throw new IllegalStateException("Set Readable environment variables");
    String run = UUID.randomUUID().toString();
    String batch = "batch:example-" + run;
    String now = Instant.now().toString();
    String json = """
      {"schema":"readable.external-agentic.traffic","version":1,"site_id":"%s",
       "batch_id":"%s","created_at":"%s",
       "source":{"type":"application_event","provider":"generic","integration_id":"%s",
                 "collector":"java-example","collector_version":"1.0.0"},"event_count":1,
       "events":[{"event_id":"evt:example-%s","occurred_at":"%s",
         "request":{"request_id":"request:example-%s","method":"GET","scheme":"https",
                    "hostname":"www.example.com","path":"/products/example",
                    "user_agent":"ChatGPT-User/1.0","referrer_url":"https://chatgpt.com/"},
         "response":{"status":200,"content_type":"text/html","duration_ms":84,"bytes_sent":18422},
         "extensions":{}}]}
      """.formatted(site, batch, now, integration, run, now, run);
    HttpRequest request = HttpRequest.newBuilder(URI.create(
        "https://www.tryreadable.ai/api/external-agentic/traffic/batches"))
        .header("Authorization", "Bearer " + key).header("Content-Type", "application/json")
        .header("Idempotency-Key", batch).header("X-Readable-Ingestion-Version", "1")
        .timeout(Duration.ofSeconds(15)).POST(HttpRequest.BodyPublishers.ofString(json)).build();
    HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5))
        .followRedirects(HttpClient.Redirect.NEVER).build();
    HttpResponse<String> response = client.send(
        request, HttpResponse.BodyHandlers.ofString());
    if (response.statusCode() != 200) throw new IllegalStateException("Ingestion failed: " + response.statusCode());
    JsonNode receipt = new ObjectMapper().readTree(response.body()); // Jackson databind 2.x
    int eventCount = receipt.path("event_count").asInt(-1);
    int accounted = receipt.path("inserted").asInt(-1) + receipt.path("deduplicated").asInt(-1) + receipt.path("rejected").asInt(-1);
    if (!receipt.path("success").asBoolean(false) || !receipt.path("accepted").asBoolean(false) ||
        !site.equals(receipt.path("site_id").asText()) || !batch.equals(receipt.path("batch_id").asText()) ||
        eventCount != 1 || eventCount != accounted) throw new IllegalStateException("Invalid acknowledgement; retain the batch for retry");
    System.out.println(receipt);
  }
}
