// Example HTTPS sender for Java 17+. No third-party dependencies.
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadLocalRandom;

public final class RmonClient {
    private static final URI ENDPOINT = URI.create(System.getenv("RMON_EVENT_ENDPOINT"));
    private static final String KEY = System.getenv("RMON_SENDING_KEY");
    private static final System.Logger LOG = System.getLogger("rmon.telemetry");
    private static final HttpClient CLIENT = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(3))
        .followRedirects(HttpClient.Redirect.NEVER).build();

    static {
        if (!"https".equals(ENDPOINT.getScheme()) || ENDPOINT.getHost() == null
                || ENDPOINT.getUserInfo() != null) {
            throw new IllegalArgumentException("RMON_EVENT_ENDPOINT must use HTTPS");
        }
        if (KEY == null || !KEY.matches("rmon_pub_[A-Za-z0-9_-]{43}")) {
            throw new IllegalArgumentException("Set RMON_SENDING_KEY to an issued key");
        }
    }

    public static <T> T observe(Callable<T> operation) throws Exception {
        long started = System.nanoTime();
        boolean success = false;
        try {
            T result = operation.call();
            success = true;
            return result;
        } catch (InterruptedException error) {
            Thread.currentThread().interrupt();
            throw error;
        } finally {
            long durationMs = (System.nanoTime() - started) / 1_000_000;
            // Variable strings below are fixed literals or validated key/UUID/time values.
            String body = """
                {"schema_version":1,"project_key":"%s","events":[{
                  "event_id":"%s","check":"cache.refresh","definition_version":1,
                  "observed_at":"%s","status":"%s","duration_ms":%d,
                  "metrics":{},"context":{"environment":"production",
                    "platform":"java","app_version":"2.4.0"}%s
                }]}
                """.formatted(KEY, UUID.randomUUID(), Instant.now().truncatedTo(ChronoUnit.MILLIS),
                    success ? "ok" : "error", durationMs,
                    success ? "" : ",\"error\":{\"code\":\"operation_failed\"}");
            send(body);
        }
    }

    private static void send(String body) {
        if (Thread.currentThread().isInterrupted()) {
            LOG.log(System.Logger.Level.WARNING, "RMON delivery skipped: interrupted");
            return;
        }
        HttpRequest request = HttpRequest.newBuilder(ENDPOINT)
            .timeout(Duration.ofSeconds(5)).header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body)).build();
        String reason = "not accepted";
        for (int attempt = 0; attempt < 3; attempt++) {
            long delayMs = (1L << attempt) * 1000;
            try {
                var response = CLIENT.send(request, HttpResponse.BodyHandlers.discarding());
                int status = response.statusCode();
                if (status == 200 || status == 202) return;
                reason = "HTTP " + status;
                if (status != 429 && (status < 500 || status >= 600)) break;
                String retry = response.headers().firstValue("Retry-After").orElse("");
                if (retry.matches("[0-9]{1,8}")) {
                    delayMs = Math.min(30_000, Long.parseLong(retry) * 1000);
                }
            } catch (IOException error) {
                reason = error.getClass().getSimpleName();
            } catch (InterruptedException error) {
                Thread.currentThread().interrupt();
                LOG.log(System.Logger.Level.WARNING, "RMON delivery interrupted");
                return;
            }
            if (attempt < 2) {
                try {
                    Thread.sleep(delayMs + ThreadLocalRandom.current().nextInt(500));
                } catch (InterruptedException error) {
                    Thread.currentThread().interrupt();
                    LOG.log(System.Logger.Level.WARNING, "RMON delivery interrupted");
                    return;
                }
            }
        }
        LOG.log(System.Logger.Level.WARNING, "RMON delivery failed: {0}", reason);
    }
}
