"""Telegram held-inbound queue: events PTB already acked that cannot dispatch yet are held,
redispatched on reconnect, and handed to the adapter that replaces this one (#132829)."""

import asyncio
import itertools
import logging
import weakref
from typing import Optional

from gateway.platforms.event import MessageEvent
from gateway.platforms.helpers import cancel_task

logger = logging.getLogger("plugins.platforms.telegram.adapter")

# Process-wide, so positions stay comparable when a replacement adapter adopts a predecessor's queue.
_ARRIVALS = itertools.count()
_ARRIVAL_ATTR = "_telegram_arrival_seq"


def _insert_by_arrival(held: list, event: MessageEvent) -> None:
    """Queue ``event`` behind every held event that arrived before it. Events are held at different
    times (on arrival behind the delivery fence, by their own flush, by a cancelled flush, by teardown
    salvage), so appending would replay a later update before an earlier buffered one. Unstamped events
    keep append order."""
    seq = getattr(event, _ARRIVAL_ATTR, None)
    if seq is not None:
        for i, other in enumerate(held):
            if getattr(other, _ARRIVAL_ATTR, -1) > seq:
                held.insert(i, event)
                return
    held.append(event)


class TelegramHeldInboundMixin:
    """Hold / redispatch / hand-over of inbound events for ``TelegramAdapter``."""

    async def stop_inbound(self) -> None:
        """Gateway drain: stop getUpdates while the message handler is still installed (#143122).

        A long-poll that outlives the handler withdrawal acks updates nobody admits; stopping it
        first leaves unfetched updates on Telegram for the next boot. Fences the polling lifecycle
        like ``disconnect()`` so the verifier/reconnect paths read this as teardown; egress stays up.
        The fence is set even when the updater is not running: a conflict/network recovery sleeping
        between its stop and its restart would otherwise restart polling after the handler is gone.
        """
        from plugins.platforms.telegram.adapter import _UPDATER_STOP_TIMEOUT, _await_with_thread_deadline
        if self._teardown_started or self._webhook_mode:
            return
        self._polling_teardown_started = True
        self._polling_progress_accepting = False
        self._polling_generation = getattr(self, "_polling_generation", 0) + 1
        self._polling_progress_event = asyncio.Event()
        updater = getattr(self._app, "updater", None) if self._app else None
        if getattr(updater, "running", False):
            await _await_with_thread_deadline(updater.stop(), timeout=_UPDATER_STOP_TIMEOUT, label="stop_inbound")

    def _schedule_held_inbound_redispatch(self) -> None:
        """Ensure a tracked drain runs when held events exist and delivery is live (no-op while
        down or after permanent fatal; an in-flight drain schedules its own follow-up)."""
        if self._is_permanent_fatal() or self._should_drop_delayed_delivery():
            return
        if not getattr(self, "_held_inbound_events", None):
            return
        try:
            loop = asyncio.get_running_loop()
        except RuntimeError:
            return
        prior = getattr(self, "_held_inbound_redispatch_task", None)
        try:
            current = asyncio.current_task()
        except RuntimeError:
            current = None
        if prior is not None and not prior.done() and prior is not current:
            return
        self._held_inbound_redispatch_task = loop.create_task(self._redispatch_held_inbound(prior=None if prior is current else prior))

    @staticmethod
    def _note_arrival(event: MessageEvent) -> None:
        """Stamp an inbound update with its arrival position; a batch keeps its first update's stamp."""
        if getattr(event, _ARRIVAL_ATTR, None) is None:
            setattr(event, _ARRIVAL_ATTR, next(_ARRIVALS))

    def _salvage_buffered_inbound(self) -> None:
        """Hold every buffered batch (text, photo burst, album) at teardown, before the maps are cleared."""
        for events, where in (
                (self._pending_text_batches, "text-batch-teardown"), (self._pending_photo_batches, "photo-batch-teardown"),
                (self._media_group_events, "media-group-teardown")):
            for key in list(events):  # popped: a batch handed over early is never salvaged twice
                self._hold_inbound_event(events.pop(key), where=where)

    def _hold_inbound_event(self, event: MessageEvent, *, where: str, schedule: bool = True) -> None:
        """Preserve an inbound event that cannot be dispatched now (PTB already acked the update, so dropping is silent loss).
        Capped, identity-deduped; permanent fatal discards. ``schedule=False`` inside a drain avoids poison-event loops.

        The disconnect drop-guard (#55971) correctly prevents dispatch into a torn-down session. Destroying
        the event is wrong: by the time we reach enqueue/flush, python-telegram-bot has already acked the
        update and advanced the offset — silent permanent loss, no log, no error.
        """
        if self._is_permanent_fatal():
            logger.warning(
                "[Telegram] Discarding inbound under non-retryable fatal (%s, %d chars)", where, len(getattr(event, "text", None) or ""))
            return
        successor = getattr(self, "_held_inbound_successor", None)
        target = successor() if successor is not None else None
        if target is not None:  # retired by a runner rebuild (#132829)
            self._accept_update()  # the claim being dispatched is ours, not the successor's
            target._adopt_held_event(event, where=f"{where}-forwarded", schedule=schedule)
            return
        held = getattr(self, "_held_inbound_events", None)
        if held is None:
            self._held_inbound_events = held = []
        if any(existing is event for existing in held):
            return
        max_n = int(getattr(self, "HELD_INBOUND_MAX", 64) or 64)
        while len(held) >= max_n:
            dropped = held.pop(0)
            logger.warning(
                "[Telegram] Held-inbound queue full (%d); dropping oldest (%d chars)", max_n, len(getattr(dropped, "text", None) or ""))
        _insert_by_arrival(held, event)
        self._accept_update()
        logger.warning(
            "[Telegram] Holding inbound (%s, %d chars, queue=%d)%s", where, len(getattr(event, "text", None) or ""), len(held),
            " - will redispatch on reconnect" if self._should_drop_delayed_delivery() else (" - scheduling redispatch" if schedule else ""))
        # A live-path hold must not orphan the event waiting for a reconnect that never comes.
        if schedule and not self._should_drop_delayed_delivery():
            self._schedule_held_inbound_redispatch()

    def adopt_held_inbound(self, predecessor: "TelegramHeldInboundMixin") -> None:
        """Take over the hold queue of the instance the runner just replaced with us (#132829): it only
        drains on its own ``_mark_connected``, which never comes; later holds there forward here."""
        self._held_inbound_successor = None  # we own the queue again: a reverse link would forward in a cycle
        if predecessor._should_drop_delayed_delivery():
            # Its buffered batches predate anything we receive; its own teardown salvage may still be
            # awaiting network cleanup, so take them now or our replay can overtake them.
            predecessor._salvage_buffered_inbound()
        predecessor._held_inbound_successor = weakref.ref(self)
        held = getattr(predecessor, "_held_inbound_events", None) or []
        events = list(held)
        held.clear()
        for event in events:
            self._adopt_held_event(event, where="adopted", schedule=False)
        self._schedule_held_inbound_redispatch()

    def _adopt_held_event(self, event: MessageEvent, *, where: str, schedule: bool) -> None:
        """Hold a predecessor's event here; only the transport ref moves (profile/authz stay as resolved)."""
        if getattr(event, "source", None) is not None:
            event.source._transport_adapter_ref = weakref.ref(self)
        self._hold_inbound_event(event, where=where, schedule=schedule)

    def _rehold_from(self, events: list, idx: int, where: str) -> None:
        """Re-hold ``events[idx:]`` without rescheduling (drain interrupted / failed / cancelled)."""
        for rest in events[idx:]:
            self._hold_inbound_event(rest, where=where, schedule=False)

    async def _redispatch_held_inbound(self, prior: Optional[asyncio.Task] = None) -> None:
        """Drain the hold queue after reconnect or a connected-path hold; ``prior`` (previous
        redispatch task) is cancelled+awaited here so ``_mark_connected`` stays synchronous."""
        if prior is not asyncio.current_task():  # a self-redispatch must not cancel itself
            await cancel_task(prior)
        held = getattr(self, "_held_inbound_events", None)
        if self._is_permanent_fatal():
            if held:
                n = len(held)
                held.clear()
                logger.warning("[Telegram] Redispatch aborted; discarded %d held inbound under non-retryable fatal", n)
            return
        if not held:
            return
        # Take ownership atomically; concurrent holds append to the fresh list for a follow-up.
        events = list(held)
        held.clear()
        logger.warning("[Telegram] Redispatching %d held inbound message(s)", len(events))
        allow_followup_schedule = True
        try:
            for idx, event in enumerate(events):
                if self._is_permanent_fatal() or self._should_drop_delayed_delivery():
                    self._rehold_from(events, idx, "redispatch-interrupted")
                    return
                try:
                    await self.handle_message(event)
                except asyncio.CancelledError:
                    self._rehold_from(events, idx, "redispatch-cancelled")
                    raise
                except Exception:
                    # Retryable failure: re-hold but do NOT reschedule now (a poison event would
                    # tight-loop); the next mark_connected/live hold drains.
                    logger.exception(
                        "[Telegram] Failed to redispatch held inbound (%d chars); re-holding", len(getattr(event, "text", None) or ""))
                    self._rehold_from(events, idx, "redispatch-failed")
                    allow_followup_schedule = False
                    return
        finally:
            # Events that arrived mid-drain while still connected need another pass.
            if (
                allow_followup_schedule
                and getattr(self, "_held_inbound_events", None)
                and not self._should_drop_delayed_delivery()
                and not self._is_permanent_fatal()):
                self._schedule_held_inbound_redispatch()
