package com.xfestudio.xfeservermanager.infra.http;

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

/** Bounded fan-out broker. A slow browser is disconnected rather than blocking a publisher. */
public final class SseBroker {
    private static final int REPLAY_LIMIT = 256;
    private static final int SUBSCRIBER_QUEUE_LIMIT = 128;

    private final int maximumSubscribers;
    private final AtomicLong sequence = new AtomicLong();
    private final Object lock = new Object();
    private final List<Subscription> subscriptions = new ArrayList<>();
    private final ArrayDeque<Event> replay = new ArrayDeque<>();

    public SseBroker(int maximumSubscribers) {
        if (maximumSubscribers < 1) {
            throw new IllegalArgumentException("maximumSubscribers must be positive");
        }
        this.maximumSubscribers = maximumSubscribers;
    }

    public Event publish(String type, String json) {
        if (type == null || !type.matches("[a-z][a-z0-9-]{0,31}")) {
            throw new IllegalArgumentException("invalid SSE event type");
        }
        Objects.requireNonNull(json, "json");
        synchronized (lock) {
            Event event = new Event(sequence.incrementAndGet(), type, json, Instant.now());
            replay.addLast(event);
            while (replay.size() > REPLAY_LIMIT) {
                replay.removeFirst();
            }
            var iterator = subscriptions.iterator();
            while (iterator.hasNext()) {
                Subscription subscription = iterator.next();
                if (!subscription.offer(event)) {
                    subscription.closeAsSlow();
                    iterator.remove();
                }
            }
            return event;
        }
    }

    public Optional<Subscription> subscribe(long afterEventId) {
        synchronized (lock) {
            subscriptions.removeIf(subscription -> !subscription.isOpen());
            if (subscriptions.size() >= maximumSubscribers) {
                return Optional.empty();
            }
            Subscription subscription = new Subscription();
            long replayCount = replay.stream().filter(event -> event.id() > afterEventId).count();
            if ((!replay.isEmpty() && afterEventId > 0
                            && afterEventId < replay.peekFirst().id() - 1)
                    || replayCount > SUBSCRIBER_QUEUE_LIMIT) {
                subscription.offer(
                        new Event(sequence.get(), "resync-required", "{}", Instant.now()));
            } else {
                replay.stream().filter(event -> event.id() > afterEventId).forEach(subscription::offer);
            }
            subscriptions.add(subscription);
            return Optional.of(subscription);
        }
    }

    public int subscriberCount() {
        synchronized (lock) {
            subscriptions.removeIf(subscription -> !subscription.isOpen());
            return subscriptions.size();
        }
    }

    public List<Event> replayAfter(long eventId) {
        synchronized (lock) {
            List<Event> result = new ArrayList<>();
            for (Event event : replay) {
                if (event.id() > eventId) {
                    result.add(event);
                }
            }
            return List.copyOf(result);
        }
    }

    public record Event(long id, String type, String json, Instant occurredAt) {
        public String encode() {
            String safeData = json.replace("\r", "").replace("\n", "\ndata: ");
            return "id: " + id + "\nevent: " + type + "\ndata: " + safeData + "\n\n";
        }
    }

    public static final class Subscription implements AutoCloseable {
        private final ArrayBlockingQueue<Event> queue = new ArrayBlockingQueue<>(SUBSCRIBER_QUEUE_LIMIT);
        private final AtomicBoolean open = new AtomicBoolean(true);
        private volatile boolean slow;

        private Subscription() {}

        private boolean offer(Event event) {
            return open.get() && queue.offer(event);
        }

        public Optional<Event> poll(Duration timeout) throws InterruptedException {
            if (!open.get() && queue.isEmpty()) {
                return Optional.empty();
            }
            return Optional.ofNullable(queue.poll(timeout.toMillis(), java.util.concurrent.TimeUnit.MILLISECONDS));
        }

        public boolean isOpen() {
            return open.get();
        }

        public boolean wasClosedAsSlow() {
            return slow;
        }

        private void closeAsSlow() {
            slow = true;
            close();
        }

        @Override
        public void close() {
            if (open.compareAndSet(true, false)) {
                queue.clear();
            }
        }
    }
}
