import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class RequestTimeoutProbe {
    static final int BUDGET_MS = 2_000;

    record Observation(String state, int first, int count) {}

    static void pause(long ms) throws IOException {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IOException(e);
        }
    }

    static boolean hasTimeout(Throwable e) {
        for (var t = e; t != null; t = t.getCause()) {
            if (t instanceof HttpTimeoutException) return true;
        }
        return false;
    }

    static Observation observe(HttpClient client, String origin, String route, boolean stream)
            throws Exception {
        long started = System.nanoTime();
        String state = "send";
        int first = -1;
        int count = 0;
        try {
            var req = HttpRequest.newBuilder(URI.create(origin + route))
                .timeout(Duration.ofMillis(BUDGET_MS)).build();
            if (stream) {
                var reply = client.send(req, HttpResponse.BodyHandlers.ofInputStream());
                state = "read";
                try (var in = reply.body()) {
                    if (reply.statusCode() != 200) throw new AssertionError("status " + reply.statusCode());
                    for (int b; (b = in.read()) != -1; count++) {
                        if (count == 0) first = b;
                        if (b != 'A' + count) throw new AssertionError("wrong byte");
                    }
                }
            } else {
                var reply = client.send(req, HttpResponse.BodyHandlers.ofString());
                if (reply.statusCode() != 200 || !reply.body().equals("AB")) {
                    throw new AssertionError("unexpected buffered response: " + reply);
                }
                count = reply.body().length();
            }
            log(route, stream, "EOF", started, first, count, "-");
            return new Observation("EOF", first, count);
        } catch (IOException e) {
            if (!hasTimeout(e)) throw e;
            String kind = state + "-timeout";
            log(route, stream, kind, started, first, count, e.getClass().getSimpleName());
            return new Observation(kind, first, count);
        }
    }

    static void log(String route, boolean stream, String result, long started,
                    int first, int count, String exceptionType) {
        System.out.printf("%s %-8s %-12s elapsed=%4dms first=%s bytes=%d exception=%s%n",
            route, stream ? "stream" : "string", result,
            TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started),
            first < 0 ? "-" : String.valueOf((char) first), count, exceptionType);
    }

    static void check(Observation received, String state, int first, int count) {
        if (!received.state().equals(state) || received.first() != first ||
                (count < 0 ? received.count() < 2 || received.count() >= 10 : received.count() != count)) {
            throw new AssertionError("unexpected outcome " + received + "; wanted " + state);
        }
    }

    public static void main(String[] args) throws Exception {
        if (args.length != 1 || !(args[0].equals("headers-only") || args[0].equals("body-budget"))) {
            throw new IllegalArgumentException("use headers-only or body-budget");
        }
        boolean bodyBudget = args[0].equals("body-budget");
        var server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        ExecutorService handlers = Executors.newCachedThreadPool();
        server.setExecutor(handlers);
        server.createContext("/", x -> {
            try (x) {
                String path = x.getRequestURI().getPath();
                if (path.equals("/late-head")) pause(3_400);
                x.sendResponseHeaders(200, 0);
                var out = x.getResponseBody();
                out.write('A');
                out.flush();
                if (path.equals("/gap")) pause(3_400);
                int length = path.equals("/pulse") ? 10 : 2;
                for (int i = 1; i < length; i++) {
                    if (length == 10) pause(420);
                    out.write('A' + i);
                    out.flush();
                }
            } catch (IOException ignored) {
                // Closing the client after a timeout can interrupt this fixture's writes.
            }
        });
        server.start();
        String origin = "http://127.0.0.1:" + server.getAddress().getPort();
        System.out.println(Runtime.version() + " " + args[0]);
        try (var client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1)
                .proxy(HttpClient.Builder.NO_PROXY).build()) {
            check(observe(client, origin, "/fast", true), "EOF", 'A', 2);
            check(observe(client, origin, "/late-head", true), "send-timeout", -1, 0);
            check(observe(client, origin, "/gap", true), bodyBudget ? "read-timeout" : "EOF",
                    'A', bodyBudget ? 1 : 2);
            check(observe(client, origin, "/gap", false), bodyBudget ? "send-timeout" : "EOF",
                    -1, bodyBudget ? 0 : 2);
            check(observe(client, origin, "/pulse", true), bodyBudget ? "read-timeout" : "EOF",
                    'A', bodyBudget ? -1 : 10);
            System.out.println("PASS: 5 cases");
        } finally {
            server.stop(0);
            handlers.shutdownNow();
            if (!handlers.awaitTermination(5, TimeUnit.SECONDS)) throw new AssertionError("server did not stop");
        }
    }
}
