package aoiprxkit

import (
	"errors"
	"fmt"
	"net"
	"time"
)

// Config defines a pragmatic RX-only subset for statically configured AES67-style RTP audio.
// It is intentionally narrower than full AES67.
type Config struct {
	MulticastGroup     string
	Port               int
	InterfaceName      string
	PayloadType        uint8
	SampleRateHz       int
	Channels           int
	Encoding           string
	PacketTime         time.Duration
	JitterDepthPackets int
	ReadBufferBytes    int
}

func DefaultConfig() Config {
	return Config{
		MulticastGroup:     "239.69.0.1",
		Port:               5004,
		PayloadType:        97,
		SampleRateHz:       48000,
		Channels:           2,
		Encoding:           "L24",
		PacketTime:         time.Millisecond,
		JitterDepthPackets: 8,
		ReadBufferBytes:    1 << 20,
	}
}

func (c Config) Validate() error {
	if ip := net.ParseIP(c.MulticastGroup); ip == nil || ip.To4() == nil {
		return fmt.Errorf("invalid IPv4 multicast group: %q", c.MulticastGroup)
	}
	ip := net.ParseIP(c.MulticastGroup).To4()
	if ip[0] < 224 || ip[0] > 239 {
		return fmt.Errorf("multicast group must be IPv4 multicast: %q", c.MulticastGroup)
	}
	if c.Port < 1 || c.Port > 65535 {
		return errors.New("port must be 1..65535")
	}
	if c.SampleRateHz <= 0 {
		return errors.New("sample rate must be > 0")
	}
	if c.Channels < 1 || c.Channels > 2 {
		return errors.New("channels must be 1 or 2")
	}
	if c.Encoding != "L24" {
		return fmt.Errorf("unsupported encoding %q: only L24 is currently supported", c.Encoding)
	}
	if c.PacketTime <= 0 {
		return errors.New("packet time must be > 0")
	}
	if c.JitterDepthPackets < 1 {
		return errors.New("jitter depth must be >= 1")
	}
	return nil
}
