package stereo

import (
	"math"
	"testing"
	"github.com/jan/fm-rds-tx/internal/audio"
)

func TestStereoEncoderEncode(t *testing.T) {
	enc := NewStereoEncoder(228000)
	frame := audio.NewFrame(1, -1)
	result := enc.Encode(frame)
	if math.Abs(result.Mono) > 1e-9 { t.Fatalf("expected mono 0, got %v", result.Mono) }
	var maxStereo float64
	for i := 0; i < 100; i++ {
		c := enc.Encode(frame)
		if math.Abs(c.Stereo) > maxStereo { maxStereo = math.Abs(c.Stereo) }
	}
	if maxStereo < 0.1 { t.Fatalf("expected non-trivial stereo, maxStereo=%.6f", maxStereo) }
}

func TestStereoEncoderMonoSignal(t *testing.T) {
	enc := NewStereoEncoder(228000)
	frame := audio.NewFrame(0.5, 0.5)
	for i := 0; i < 100; i++ {
		c := enc.Encode(frame)
		if math.Abs(c.Stereo) > 1e-12 { t.Fatalf("expected zero stereo, got %.9f", c.Stereo) }
		if math.Abs(c.Mono-0.5) > 1e-9 { t.Fatalf("expected mono=0.5, got %.9f", c.Mono) }
	}
}

func TestStereoEncoderPilotRange(t *testing.T) {
	enc := NewStereoEncoder(228000)
	frame := audio.NewFrame(0.1, -0.1)
	for i := 0; i < 1000; i++ {
		c := enc.Encode(frame)
		if c.Pilot < -1.001 || c.Pilot > 1.001 { t.Fatalf("pilot out of range: %.6f", c.Pilot) }
	}
}

func TestStereoEncoderReset(t *testing.T) {
	frame := audio.NewFrame(0.1, -0.1)
	enc := NewStereoEncoder(228000)
	initial := make([]float64, 4)
	for i := range initial { initial[i] = enc.Encode(frame).Pilot }
	enc.Reset()
	for i := range initial {
		if math.Abs(initial[i]-enc.Encode(frame).Pilot) > 1e-9 { t.Fatalf("reset failed at %d", i) }
	}
}
