package socket

import (
	
	

	
	
	
	
	
)

// RelayTransport is the magic socket's relay path: it owns a [RelayActor],
// forwards datagrams received from relays into the [MagicConn]'s recv channel
// (tagged so they surface as a [RelayMappedAddr]), and routes outgoing datagrams
// addressed to a relay mapped address to the right relay connection.
//
// It is the Go analog of the Rust RelayTransport
// (iroh/src/socket/transports/relay.rs:31). Create one with [NewRelayTransport]
// and start it with [RelayTransport.Serve]. The zero value is not usable.
type RelayTransport struct {
	sock   *Socket
	actor  *RelayActor
	recvCh chan<- recvBatch
}

// NewRelayTransport returns a RelayTransport that drives actor and delivers
// received relay datagrams to recvCh. sock supplies the relay mapped-address
// table shared with the [MagicConn]. The transport does not start the actor;
// call [RelayTransport.Serve].
func ( *Socket,  *RelayActor,  chan<- recvBatch) *RelayTransport {
	return &RelayTransport{sock: , actor: , recvCh: }
}

// Serve runs the relay actor and the recv-forwarding loop until ctx is
// cancelled. It blocks; run it in its own goroutine.
func ( *RelayTransport) ( context.Context) {
	go .actor.Run()
	.forwardRecv()
}

// forwardRecv drains datagrams from the actor and forwards each as a recvBatch
// tagged with the relay [Addr], so [MagicConn.recvAddr] rewrites it to the
// relay mapped IPv6 ULA quic-go addresses the path by.
func ( *RelayTransport) ( context.Context) {
	for {
		select {
		case <-.Done():
			return
		case ,  := <-.actor.Recv():
			if ! {
				return
			}
			.deliver(, )
		}
	}
}

// deliver forwards dm as one recvBatch whose stride is the segment size, so
// ReadFrom hands quic-go one datagram at a time (the Rust poll_recv re-batches
// the same way, iroh/src/socket/transports/relay.rs:115). The pooled Contents
// buffer is released once ReadFrom has copied out the last segment.
func ( *RelayTransport) ( context.Context,  RelayRecvDatagram) {
	 := RelayAddr(.URL, .Src)
	 := .Datagrams.Contents
	 := max(len(), 1)
	if .Datagrams.SegmentSize != 0 {
		 = int(.Datagrams.SegmentSize)
	}
	 := recvBatch{data: , stride: , info: RecvInfo{Remote: }, releaseFn: .Datagrams.Release}
	select {
	case .recvCh <- :
	case <-.Done():
		.Datagrams.Release()
	}
}

// Send routes p to the relay addressed by the relay mapped address m. It looks
// up the (relay url, endpoint id) pair m maps to and queues a datagram to the
// relay actor. It reports whether the datagram was routed; a false result means
// the address is unknown or the send queue was full, in which case the datagram
// is treated as lost (QUIC's loss recovery retransmits), matching the Rust
// blackhole-on-failure invariant (iroh/src/socket/transports.rs:1176).
func ( *RelayTransport) ( RelayMappedAddr,  []byte) bool {
	return .SendBatch(, , 0)
}

// maxRelayBatch is the largest Datagrams.Contents that fits a relay frame.
const maxRelayBatch = relayproto.MaxPacketSize - key.PublicKeySize - 3

// SendBatch is Send for a GSO-style buffer of segSize-sized datagrams (the
// last may be shorter). segSize 0 means a single datagram.
func ( *RelayTransport) ( RelayMappedAddr,  []byte,  int) bool {
	,  := .sock.LookupRelay()
	if ! {
		return false
	}
	if  <= 0 ||  >= len() {
		return .actor.Send(RelaySendItem{
			RemoteEndpoint: .EID,
			URL:            .URL,
			Datagrams:      relayproto.DatagramsFromBytes(),
		})
	}
	 := max(1, maxRelayBatch/) * 
	for len() > 0 {
		 := min(len(), )
		 := relayproto.Datagrams{Contents: bytes.Clone([:])}
		if  >  {
			.SegmentSize = uint16()
		}
		if !.actor.Send(RelaySendItem{RemoteEndpoint: .EID, URL: .URL, Datagrams: }) {
			return false
		}
		 = [:]
	}
	return true
}

// SetHomeRelay designates url as the endpoint's home relay. See
// [RelayActor.SetHomeRelay].
func ( *RelayTransport) ( netaddr.RelayURL) { .actor.SetHomeRelay() }

// InsertRelay adds or replaces a relay config in the underlying actor.
func ( *RelayTransport) ( netaddr.RelayURL,  relay.Config) (relay.Config, bool) {
	return .actor.InsertRelay(, )
}

// HasRelay reports whether url is configured. See [RelayActor.HasRelay].
func ( *RelayTransport) ( netaddr.RelayURL) bool { return .actor.HasRelay() }

// RemoveRelay removes a relay config from the underlying actor.
func ( *RelayTransport) ( netaddr.RelayURL) (relay.Config, bool) {
	return .actor.RemoveRelay()
}

// HomeRelayStatus returns a watcher over the home relay's connection status. See
// [RelayActor.HomeRelayStatus].
func ( *RelayTransport) () watch.Observer[*RelayStatus] {
	return .actor.HomeRelayStatus()
}