import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class PermitWaitTimelineDemo {
    public static void main(String[] args) throws Exception {
        Semaphore capacity = new Semaphore(1, true);
        CountDownLatch borrowed = new CountDownLatch(1);
        CountDownLatch releaseHolder = new CountDownLatch(1);
        ExecutorService executor = Executors.newSingleThreadExecutor();
        try {
            Future<?> holder = executor.submit(() -> {
                boolean acquired = false;
                try {
                    capacity.acquire();
                    acquired = true;
                    borrowed.countDown();
                    if (!releaseHolder.await(5, TimeUnit.SECONDS)) throw new IllegalStateException("holder cutoff");
                } catch (InterruptedException interrupted) {
                    Thread.currentThread().interrupt();
                    throw new IllegalStateException(interrupted);
                } finally {
                    if (acquired) capacity.release();
                }
            });
            if (!borrowed.await(2, TimeUnit.SECONDS)) throw new IllegalStateException("holder not ready");
            attempt(capacity, "blocked", false);
            if (capacity.availablePermits() != 0) throw new IllegalStateException("failed acquisition leaked a permit");
            releaseHolder.countDown();
            holder.get(2, TimeUnit.SECONDS);
            attempt(capacity, "recovered", true);
            if (capacity.availablePermits() != 1) throw new IllegalStateException("permit not restored");
            System.out.println("failed acquire did not release; holder completion restores capacity: PASS");
        } finally {
            releaseHolder.countDown();
            executor.shutdownNow();
            if (!executor.awaitTermination(3, TimeUnit.SECONDS)) throw new IllegalStateException("holder not stopped");
        }
    }

    private static void attempt(Semaphore capacity, String label, boolean expected) throws Exception {
        long started = System.nanoTime();
        boolean acquired = capacity.tryAcquire(150, TimeUnit.MILLISECONDS);
        long acquiredAt = System.nanoTime();
        int simulatedOperations = 0;
        try {
            if (acquired) simulatedOperations++;
        } finally {
            if (acquired) capacity.release();
        }
        if (acquired != expected || simulatedOperations != (expected ? 1 : 0)) {
            throw new IllegalStateException("admission boundary mismatch");
        }
        System.out.println("case=" + label + " acquireMs=" + TimeUnit.NANOSECONDS.toMillis(acquiredAt - started)
                + " acquired=" + acquired + " simulatedOperations=" + simulatedOperations + ": PASS");
    }
}
