package customermedia

import (
	"context"
	"encoding/binary"
	"math"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"
)

func TestVideoSamplingCoversStartAndEndWithinLimits(t *testing.T) {
	for _, duration := range []float64{0.5, 5, 31, 120} {
		at := frameTimes(duration)
		if len(at) < 2 || len(at) > 12 || at[0] != 0 || at[len(at)-1] >= duration || at[len(at)-1] < duration-0.2 {
			t.Fatal(duration, at)
		}
	}
	if frameTimes(math.Inf(1)) != nil || frameTimes(math.NaN()) != nil {
		t.Fatal("non-finite duration accepted")
	}
}

func TestSilentAudioDoesNotBecomeFabricatedTranscript(t *testing.T) {
	data := make([]byte, 44+32000)
	copy(data[:4], "RIFF")
	copy(data[12:16], "fmt ")
	binary.LittleEndian.PutUint32(data[16:20], 16)
	copy(data[36:40], "data")
	binary.LittleEndian.PutUint32(data[40:44], 32000)
	if !silentWAV(data) {
		t.Fatal("silence accepted")
	}
	for i := 44; i+1 < len(data); i += 2 {
		binary.LittleEndian.PutUint16(data[i:i+2], 1000)
	}
	if silentWAV(data) {
		t.Fatal("audible input rejected")
	}
}

// Real local decoding is opt-in and uses prepared fixtures, with no API call.
func TestLocalCustomerSpeechAndVideo(t *testing.T) {
	if os.Getenv("CHATLOOP_RUN_MEDIA_TEST") != "1" {
		t.Skip("requires local FFmpeg, Whisper and fixtures")
	}
	root, _ := filepath.Abs("../..")
	t.Setenv("CHATLOOP_WHISPER_MODEL", filepath.Join(root, "data/media-runtime/"+modelName))
	Start(context.Background())
	deadline := time.Now().Add(10 * time.Second)
	for !Status().Speech && time.Now().Before(deadline) {
		time.Sleep(50 * time.Millisecond)
	}
	if !Status().Speech {
		t.Fatal(Status())
	}
	data, err := os.ReadFile(filepath.Join(root, ".tmp/product-ui-20261009/voice.ogg"))
	if err != nil {
		t.Fatal(err)
	}
	transcript, err := Transcribe(context.Background(), data)
	if err != nil || !strings.Contains(strings.ToLower(transcript), "harga") {
		t.Fatal("speech", transcript, err)
	}
	t.Log("speech transcript:", transcript)
	data, err = os.ReadFile(filepath.Join(root, ".tmp/product-ui-20261009/video.mp4"))
	if err != nil {
		t.Fatal(err)
	}
	video, err := ReadVideo(context.Background(), data)
	if err != nil || len(video.Frames) < 2 || video.Transcript == "" {
		t.Fatal("video", len(video.Frames), video.Transcript, err)
	}
	t.Logf("video: %.1fs, %d frames, audio transcript present", video.Duration, len(video.Frames))
	if _, err := Transcribe(context.Background(), []byte("not audio")); err == nil {
		t.Fatal("invalid audio accepted")
	}
}
