package aoiprxkit

import (
	"encoding/binary"
	"fmt"
)

// DecodeL24BE decodes signed 24-bit big-endian PCM into int32 samples sign-extended to 32 bits.
func DecodeL24BE(payload []byte, channels int) ([]int32, error) {
	if channels < 1 {
		return nil, fmt.Errorf("invalid channels: %d", channels)
	}
	if len(payload)%3 != 0 {
		return nil, fmt.Errorf("payload length %d is not divisible by 3", len(payload))
	}
	totalSamples := len(payload) / 3
	if totalSamples%channels != 0 {
		return nil, fmt.Errorf("payload sample count %d is not divisible by channels %d", totalSamples, channels)
	}
	out := make([]int32, totalSamples)
	j := 0
	for i := 0; i < len(payload); i += 3 {
		v := int32(payload[i])<<16 | int32(payload[i+1])<<8 | int32(payload[i+2])
		if v&0x800000 != 0 {
			v |= ^int32(0xFFFFFF)
		}
		out[j] = v
		j++
	}
	return out, nil
}

// DecodeS32LE decodes signed 32-bit little-endian PCM into int32 samples.
func DecodeS32LE(payload []byte, channels int) ([]int32, error) {
	if channels < 1 {
		return nil, fmt.Errorf("invalid channels: %d", channels)
	}
	if len(payload)%4 != 0 {
		return nil, fmt.Errorf("payload length %d is not divisible by 4", len(payload))
	}
	totalSamples := len(payload) / 4
	if totalSamples%channels != 0 {
		return nil, fmt.Errorf("payload sample count %d is not divisible by channels %d", totalSamples, channels)
	}
	out := make([]int32, totalSamples)
	for i := 0; i < totalSamples; i++ {
		out[i] = int32(binary.LittleEndian.Uint32(payload[i*4 : i*4+4]))
	}
	return out, nil
}
