package webrtc

import (
	"github.com/pion/rtp"
	"github.com/pion/webrtc/v4"
)

// forwardRTP reads packets from sub and writes them to the correct track
// based on payload type (H.264 → video, Opus → audio). Used by the M1
// single-source PoC where FFmpeg emits both video and audio RTP to the
// same UDP port.
func forwardRTP(done <-chan struct{}, sub <-chan *rtp.Packet,
	video, audio *webrtc.TrackLocalStaticRTP) {
	for {
		select {
		case <-done:
			return
		case pkt, ok := <-sub:
			if !ok {
				return
			}
			// Pion default H.264 PT = 102, Opus PT = 111. If the publisher
			// uses different PTs we'll revisit in M2 — for M1 PoC we
			// configure FFmpeg to these values explicitly in the publisher
			// script.
			switch pkt.PayloadType {
			case 102:
				_ = video.WriteRTP(pkt)
			case 111:
				_ = audio.WriteRTP(pkt)
			default:
				// Unknown PT — drop. Log in M3.
			}
		}
	}
}

// forwardRTPSplit is the M2 variant: it reads from two independent
// per-track channels (one video, one audio) and writes each to its
// own Pion track. This is the mode used when the restream manager
// emits two FFmpeg RTP legs on separate UDP ports. Either channel
// closing or done firing terminates the loop.
func forwardRTPSplit(done <-chan struct{},
	videoSub <-chan *rtp.Packet, audioSub <-chan *rtp.Packet,
	video, audio *webrtc.TrackLocalStaticRTP) {
	for {
		select {
		case <-done:
			return
		case pkt, ok := <-videoSub:
			if !ok {
				return
			}
			_ = video.WriteRTP(pkt)
		case pkt, ok := <-audioSub:
			if !ok {
				return
			}
			_ = audio.WriteRTP(pkt)
		}
	}
}
