package quic

import (
	
	
	

	
	
	
	
	
	
	
)

const (
	maxPathResponses = 256
	maxControlFrames = 16 << 10
)

// This is the largest possible size of a stream-related control frame
// (which is the RESET_STREAM frame).
const maxStreamControlFrameSize = 25

type streamFrameGetter interface {
	priority() (urgency int8, incremental bool, generation uint32)
	popStreamFrame(protocol.ByteCount, protocol.Version) (_ ackhandler.StreamFrame, _ *wire.StreamDataBlockedFrame, hasMoreData bool)
	popRetransmissionFrame(protocol.ByteCount, protocol.Version) (ackhandler.StreamFrame, bool)
}

type streamControlFrameGetter interface {
	getControlFrame(monotime.Time) (_ ackhandler.Frame, ok, hasMore bool)
}

// streamQueueEntry captures the stream's generation when it is queued.
// A mismatch with the current generation identifies an entry left behind by a priority change.
type streamQueueEntry struct {
	id         protocol.StreamID
	generation uint32
}

// queuedStream tracks the latest generation added to a scheduling queue,
// preventing duplicate and out-of-order notifications from queueing it again.
type queuedStream struct {
	streamFrameGetter
	generation uint32
}

type framer struct {
	mutex sync.Mutex

	activeStreams         map[protocol.StreamID]queuedStream
	retransmissionStreams map[protocol.StreamID]streamFrameGetter

	incrementalStreams    [8]ringbuffer.RingBuffer[streamQueueEntry]
	nonIncrementalStreams [8]minheap.Heap[protocol.StreamID, uint32 /* generation */]
	// If an urgency level contains both incremental and non-incremental streams,
	// we round-robin between incremental and non-incremental streams.
	lastSendWasIncremental [8]bool

	streamsWithControlFrames map[protocol.StreamID]streamControlFrameGetter
	// Retransmissions are not incremental: repair all lost data for the first queued stream.
	// New losses extend its batch, so A, B, A is repaired as A, A, B, delaying B.
	// The ring buffer provides FIFO scheduling while reusing its storage.
	retransmissionQueue [8]ringbuffer.RingBuffer[protocol.StreamID]

	// streamMask and retransMask hold a bit per urgency level whose queues may
	// be non-empty, so Append scans only the levels in use instead of all 8.
	// A set bit is a hint: bits are set when queueing and cleared only after
	// the level is observed empty under mutex, so a clear bit always means
	// empty and no stream can be missed.
	streamMask  uint8
	retransMask uint8

	controlFrameMutex          sync.Mutex
	controlFrames              []wire.Frame
	pathResponses              []*wire.PathResponseFrame
	maxDataFrame               wire.MaxDataFrame
	hasMaxDataFrame            bool
	connFlowController         *connectionFlowController
	queuedTooManyControlFrames bool
}

func newFramer( *connectionFlowController) *framer {
	return &framer{
		activeStreams:            make(map[protocol.StreamID]queuedStream),
		retransmissionStreams:    make(map[protocol.StreamID]streamFrameGetter),
		streamsWithControlFrames: make(map[protocol.StreamID]streamControlFrameGetter),
		connFlowController:       ,
	}
}

func ( *framer) () bool {
	.controlFrameMutex.Lock()
	// hasMaxDataFrame is a go-iroh addition: MAX_DATA is coalesced into the
	// framer rather than queued as an ordinary control frame.
	 := .hasMaxDataFrame || len(.streamsWithControlFrames) > 0 || len(.controlFrames) > 0 || len(.pathResponses) > 0
	.controlFrameMutex.Unlock()

	if  {
		return true
	}

	.mutex.Lock()
	defer .mutex.Unlock()

	for  := range .incrementalStreams {
		if !.incrementalStreams[].Empty() || !.nonIncrementalStreams[].Empty() ||
			!.retransmissionQueue[].Empty() {
			return true
		}
	}
	return false
}

func ( *framer) ( wire.Frame) {
	.controlFrameMutex.Lock()
	defer .controlFrameMutex.Unlock()

	if ,  := .(*wire.PathResponseFrame);  {
		// Only queue up to maxPathResponses PATH_RESPONSE frames.
		// This limit should be high enough to never be hit in practice,
		// unless the peer is doing something malicious.
		if len(.pathResponses) >= maxPathResponses {
			return
		}
		.pathResponses = append(.pathResponses, )
		return
	}
	// This is a hack.
	if len(.controlFrames) >= maxControlFrames {
		.queuedTooManyControlFrames = true
		return
	}
	.controlFrames = append(.controlFrames, )
}

func ( *framer) ( protocol.ByteCount) {
	.controlFrameMutex.Lock()
	if !.hasMaxDataFrame ||  > .maxDataFrame.MaximumData {
		.maxDataFrame.MaximumData = 
		.hasMaxDataFrame = true
	}
	.controlFrameMutex.Unlock()
}

func ( *framer) (
	 []ackhandler.Frame,
	 []ackhandler.StreamFrame,
	 protocol.ByteCount,
	 monotime.Time,
	 protocol.Version,
) ([]ackhandler.Frame, ackhandler.StreamFrame, bool, []ackhandler.StreamFrame, protocol.ByteCount) {
	.controlFrameMutex.Lock()
	,  := .appendControlFrames(, , , )
	 -= 

	var  ackhandler.StreamFrame
	var  ackhandler.StreamFrame
	var  bool
	var  protocol.ByteCount
	.mutex.Lock()
	// retransmit all lost STREAM data before sending new STREAM data
:
	for  := .retransMask;  != 0; {
		 := bits.TrailingZeros8()
		 &^= 1 << uint()
		 := &.retransmissionQueue[]
		for !.Empty() && protocol.MinStreamFrameSize <=  {
			 := .PeekFront()
			,  := .retransmissionStreams[]
			if ! {
				.PopFront()
				continue
			}
			, ,  := .priority()
			if  != int8() {
				.PopFront()
				.retransmissionQueue[].PushBack()
				.retransMask |= 1 << uint()
				// Reach a higher level later in this same pass, as a scan
				// over every level would have.
				if int() >  {
					 |= 1 << uint()
				}
				continue
			}
			// For the last STREAM frame, we'll remove the DataLen field later.
			 :=  + protocol.ByteCount(quicvarint.Len(uint64()))
			,  := .popRetransmissionFrame(, )
			if ! {
				.PopFront()
				delete(.retransmissionStreams, )
			}
			if .Frame == nil {
				// If the retransmission didn't fit, retry it in the next packet.
				if  {
					break 
				}
				continue
			}
			 = append(, )
			 -= .Frame.Length()
			 = 
			 += .Frame.Length()
		}
		if .Empty() {
			.retransMask &^= 1 << uint()
		}
	}
	// pop STREAM frames, until less than 128 bytes are left in the packet
	for  := .streamMask;  != 0; {
		 := bits.TrailingZeros8()
		 &^= 1 << uint()
		 := .incrementalStreams[].Len() + .nonIncrementalStreams[].Len()

		for range  {
			if protocol.MinStreamFrameSize >  {
				break
			}
			,  := .getNextStreamFrame(, int8(), )
			if .Frame != nil {
				// go-iroh addition: hold the first STREAM frame back in
				// singleFrame so a packet carrying exactly one frame, the
				// common case, does not allocate the slice. A retransmission
				// above already appended, so len(streamFrames) != 0 skips this.
				if ! && len() == 0 {
					 = 
					 = true
				} else {
					if  {
						 = append(, )
						 = ackhandler.StreamFrame{}
						 = false
					}
					 = append(, )
				}
				 -= .Frame.Length()
				 = 
				 += .Frame.Length()
			}
			// If the stream just became blocked on stream flow control, attempt to pack the
			// STREAM_DATA_BLOCKED into the same packet.
			if  != nil {
				 := .Length()
				// In case it doesn't fit, queue it for the next packet.
				if  <  {
					.controlFrames = append(.controlFrames, )
					break
				}
				 = append(, ackhandler.Frame{Frame: })
				 -= 
				 += 
			}
		}
		if .incrementalStreams[].Empty() && .nonIncrementalStreams[].Empty() {
			.streamMask &^= 1 << uint()
		}
	}

	// The only way to become blocked on connection-level flow control is by sending STREAM frames.
	if ,  := .connFlowController.IsNewlyBlocked();  {
		 := &wire.DataBlockedFrame{MaximumData: }
		 := .Length()
		// In case it doesn't fit, queue it for the next packet.
		if  >=  {
			 = append(, ackhandler.Frame{Frame: })
			 += 
		} else {
			.controlFrames = append(.controlFrames, )
		}
	}

	.mutex.Unlock()
	.controlFrameMutex.Unlock()

	if .Frame != nil {
		// account for the smaller size of the last STREAM frame
		 -= .Frame.Length()
		.Frame.DataLenPresent = false
		 += .Frame.Length()
	}

	return , , , ,  + 
}

// AppendControlFrames appends queued control frames (window updates,
// stream control frames, PATH_RESPONSE) without any stream data. It is
// used for ack-only packets: a congestion- or pacing-limited receiver
// must still be able to grant flow-control credit, or a pure sink
// starves its sender of MAX_DATA and the connection deadlocks.
func ( *framer) (
	 []ackhandler.Frame,
	 protocol.ByteCount,
	 monotime.Time,
	 protocol.Version,
) ([]ackhandler.Frame, protocol.ByteCount) {
	.controlFrameMutex.Lock()
	defer .controlFrameMutex.Unlock()
	return .appendControlFrames(, , , )
}

func ( *framer) (
	 []ackhandler.Frame,
	 protocol.ByteCount,
	 monotime.Time,
	 protocol.Version,
) ([]ackhandler.Frame, protocol.ByteCount) {
	var  protocol.ByteCount
	// add a PATH_RESPONSE first, but only pack a single PATH_RESPONSE per packet
	if len(.pathResponses) > 0 {
		 := .pathResponses[0]
		 := .Length()
		if  <=  {
			 = append(, ackhandler.Frame{Frame: })
			 += 
			.pathResponses = .pathResponses[1:]
		}
	}

	if .hasMaxDataFrame {
		 := .maxDataFrame.Length()
		if + <=  {
			// Fresh allocation: the retransmission queue retains the frame
			// pointer on loss, so the pending struct must not be shared.
			 = append(, ackhandler.Frame{Frame: &wire.MaxDataFrame{MaximumData: .maxDataFrame.MaximumData}})
			 += 
			.hasMaxDataFrame = false
		}
	}

	// add stream-related control frames
	for ,  := range .streamsWithControlFrames {
	:
		 :=  - 
		if  <= maxStreamControlFrameSize {
			break
		}
		, ,  := .getControlFrame()
		if ! {
			delete(.streamsWithControlFrames, )
		}
		if ! {
			continue
		}
		 = append(, )
		 += .Frame.Length()
		if  {
			// It is rare that a stream has more than one control frame to queue.
			// We don't want to spawn another loop for just to cover that case.
			goto 
		}
	}

	for len(.controlFrames) > 0 {
		 := .controlFrames[len(.controlFrames)-1]
		 := .Length()
		if + >  {
			break
		}
		 = append(, ackhandler.Frame{Frame: })
		 += 
		.controlFrames = .controlFrames[:len(.controlFrames)-1]
	}

	return , 
}

// QueuedTooManyControlFrames says if the control frame queue exceeded its maximum queue length.
// This is a hack.
// It is easier to implement than propagating an error return value in QueueControlFrame.
// The correct solution would be to queue frames with their respective structs.
// See https://github.com/quic-go/quic-go/issues/4271 for the queueing of stream-related control frames.
func ( *framer) () bool {
	return .queuedTooManyControlFrames
}

func ( *framer) ( protocol.StreamID,  streamFrameGetter) {
	.mutex.Lock()
	defer .mutex.Unlock()

	, ,  := .priority()
	if ,  := .activeStreams[];  && .generation ==  {
		return
	}
	if  {
		.incrementalStreams[].PushBack(streamQueueEntry{id: , generation: })
	} else {
		.nonIncrementalStreams[].Push(, )
	}
	.streamMask |= 1 << uint()
	.activeStreams[] = queuedStream{streamFrameGetter: , generation: }
}

func ( *framer) ( protocol.StreamID,  streamFrameGetter) {
	.mutex.Lock()
	defer .mutex.Unlock()

	, ,  := .priority()
	if ,  := .retransmissionStreams[];  {
		return
	}
	.retransmissionQueue[].PushBack()
	.retransMask |= 1 << uint()
	.retransmissionStreams[] = 
}

func ( *framer) ( protocol.StreamID,  streamControlFrameGetter) {
	.controlFrameMutex.Lock()
	defer .controlFrameMutex.Unlock()

	if ,  := .streamsWithControlFrames[]; ! {
		.streamsWithControlFrames[] = 
	}
}

// RemoveActiveStream is called when a stream completes.
func ( *framer) ( protocol.StreamID) {
	.mutex.Lock()
	defer .mutex.Unlock()

	// We don't delete the stream from the ring buffers and heaps,
	// since we'd have to find it there first.
	// Instead, we check if the stream is still in active when appending STREAM frames.
	delete(.activeStreams, )
	delete(.retransmissionStreams, )
}

func ( *framer) ( protocol.StreamID) {
	.mutex.Lock()
	defer .mutex.Unlock()

	,  := .activeStreams[]
	if ! {
		return
	}
	, ,  := .priority()
	if .generation !=  {
		// Leave the old queue entry in place. It will be discarded when it reaches
		// the front of that queue and no longer matches the stream's generation.
		if  {
			.incrementalStreams[].PushBack(streamQueueEntry{id: , generation: })
		} else {
			.nonIncrementalStreams[].Push(, )
		}
		.streamMask |= 1 << uint()
		.generation = 
		.activeStreams[] = 
	}
}

func ( *framer) (
	 protocol.ByteCount,
	 int8,
	 protocol.Version,
) (ackhandler.StreamFrame, *wire.StreamDataBlockedFrame) {
	if .nonIncrementalStreams[].Empty() || (!.lastSendWasIncremental[] && !.incrementalStreams[].Empty()) {
		return .getNextIncrementalStreamFrame(, , )
	}
	return .getNextNonIncrementalStreamFrame(, , )
}

func ( *framer) (
	 protocol.ByteCount,
	 int8,
	 protocol.Version,
) (ackhandler.StreamFrame, *wire.StreamDataBlockedFrame) {
	 := &.incrementalStreams[]
	if .Empty() {
		return ackhandler.StreamFrame{}, nil
	}
	 := .PopFront()
	,  := .activeStreams[.id]
	if ! {
		return ackhandler.StreamFrame{}, nil
	}
	, ,  := .priority()
	if  != .generation {
		return ackhandler.StreamFrame{}, nil
	}

	, ,  := .popStreamFrame(.id, , , )
	if  {
		.PushBack()
	}
	.lastSendWasIncremental[] = true
	return , 
}

func ( *framer) (
	 protocol.ByteCount,
	 int8,
	 protocol.Version,
) (ackhandler.StreamFrame, *wire.StreamDataBlockedFrame) {
	 := &.nonIncrementalStreams[]
	if .Empty() {
		return ackhandler.StreamFrame{}, nil
	}
	,  := .Peek()
	,  := .activeStreams[]
	if ! {
		.Pop()
		return ackhandler.StreamFrame{}, nil
	}
	, ,  := .priority()
	if  !=  {
		.Pop()
		return ackhandler.StreamFrame{}, nil
	}

	, ,  := .popStreamFrame(, , , )
	if ! {
		.Pop()
	}
	.lastSendWasIncremental[] = false
	return , 
}

func ( *framer) (
	 protocol.StreamID,
	 queuedStream,
	 protocol.ByteCount,
	 protocol.Version,
) (ackhandler.StreamFrame, *wire.StreamDataBlockedFrame, bool) {
	// For the last STREAM frame, we'll remove the DataLen field later.
	// Therefore, we can pretend to have more bytes available when popping
	// the STREAM frame (which will always have the DataLen set).
	 += protocol.ByteCount(quicvarint.Len(uint64()))
	, ,  := .popStreamFrame(, )
	if ! {
		delete(.activeStreams, )
	}
	// Note that the frame.Frame can be nil:
	// * if the stream was canceled after it said it had data
	// * the remaining size doesn't allow us to add another STREAM frame
	return , , 
}

func ( *framer) () {
	.mutex.Lock()
	defer .mutex.Unlock()
	.controlFrameMutex.Lock()
	defer .controlFrameMutex.Unlock()

	.streamMask = 0
	.retransMask = 0
	for  := range .incrementalStreams {
		.incrementalStreams[].Clear()
		.nonIncrementalStreams[].Clear()
		.lastSendWasIncremental[] = false
		.retransmissionQueue[].Clear()
	}
	clear(.activeStreams)
	clear(.retransmissionStreams)
	clear(.streamsWithControlFrames)

	var  int
	for ,  := range .controlFrames {
		switch .(type) {
		case *wire.MaxDataFrame, *wire.MaxStreamDataFrame, *wire.MaxStreamsFrame,
			*wire.DataBlockedFrame, *wire.StreamDataBlockedFrame, *wire.StreamsBlockedFrame:
			continue
		default:
			.controlFrames[] = .controlFrames[]
			++
		}
	}
	.controlFrames = slices.Delete(.controlFrames, , len(.controlFrames))
}