package main

// Every signal here is generated by the test code. None is a recording.

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

const rate = 16000

func le16(v int) []byte    { return binary.LittleEndian.AppendUint16(nil, uint16(v)) }
func le32(v uint32) []byte { return binary.LittleEndian.AppendUint32(nil, v) }

func chunk(id string, body []byte) []byte {
	b := append([]byte(id), le32(uint32(len(body)))...)
	b = append(b, body...)
	if len(body)%2 == 1 {
		b = append(b, 0)
	}
	return b
}

func fmtBody(tag, ch, rt, bits int) []byte {
	b := append(le16(tag), le16(ch)...)
	b = append(b, le32(uint32(rt))...)
	b = append(b, le32(uint32(rt*ch*bits/8))...)
	b = append(b, le16(ch*bits/8)...)
	return append(b, le16(bits)...)
}

func extBody(ch, rt, bits, sub int) []byte {
	b := append(fmtBody(0xFFFE, ch, rt, bits), le16(22)...)
	b = append(b, le16(bits)...)
	b = append(b, le32(4)...)
	b = append(b, le16(sub)...)
	return append(b, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71)
}

func pcm(s []int16) []byte {
	var b []byte
	for _, v := range s {
		b = append(b, le16(int(v))...)
	}
	return b
}

// dataRaw is a data chunk with a size field that may lie, as a pipe writes it.
func dataRaw(size uint32, s []int16) []byte {
	return append(append([]byte("data"), le32(size)...), pcm(s)...)
}

func riff(parts ...[]byte) []byte {
	body := []byte("WAVE")
	for _, p := range parts {
		body = append(body, p...)
	}
	return append(append([]byte("RIFF"), le32(uint32(len(body)))...), body...)
}

func put(t *testing.T, name string, b []byte) string {
	t.Helper()
	p := filepath.Join(t.TempDir(), name)
	if err := os.WriteFile(p, b, 0o644); err != nil {
		t.Fatal(err)
	}
	return p
}

func ramp(n int) []int16 {
	s := make([]int16, n)
	for i := range s {
		s[i] = int16(i%200 - 100)
	}
	return s
}

func TestHeaders(t *testing.T) {
	s := ramp(1000)
	f16 := chunk("fmt ", fmtBody(1, 1, rate, 16))
	cases := map[string][]byte{
		"plain":            riff(f16, chunk("data", pcm(s))),
		"extensible":       riff(chunk("fmt ", extBody(1, rate, 16, 1)), chunk("data", pcm(s))),
		"extensible FLLR":  riff(chunk("fmt ", extBody(1, rate, 16, 1)), chunk("FLLR", make([]byte, 4044)), chunk("data", pcm(s))),
		"data FFFFFFFF":    riff(f16, dataRaw(0xFFFFFFFF, s)),
		"LIST then pipe":   riff(chunk("LIST", []byte("INFOISFT\x0e\x00\x00\x00Lavf60.16.100\x00")), f16, dataRaw(0xFFFFFFFF, s)),
		"odd LIST and pad": riff(f16, chunk("LIST", []byte("abc")), chunk("data", pcm(s))),
		"data size 0":      riff(f16, dataRaw(0, s)),
		"partial frame":    riff(f16, chunk("data", append(pcm(s), 7))),
	}
	for name, b := range cases {
		in, err := openWAV(put(t, "h.wav", b))
		if err != nil {
			t.Fatalf("%s: %v", name, err)
		}
		got := make([]int16, 2000)
		n, _ := in.read(got)
		in.f.Close()
		if in.rate != rate || in.ch != 1 || n != 1000 || got[0] != s[0] || got[999] != s[999] {
			t.Errorf("%s: rate %d ch %d frames %d", name, in.rate, in.ch, n)
		}
	}
}

func TestRejections(t *testing.T) {
	d := chunk("data", pcm(ramp(100)))
	cases := []struct {
		b    []byte
		want string
	}{
		{riff(chunk("fmt ", fmtBody(1, 1, rate, 8)), d), "f.wav is 8-bit. Only 16-bit PCM is read. Convert: ffmpeg -i f.wav -c:a pcm_s16le f16.wav (on a Mac: afconvert -f WAVE -d LEI16 f.wav f16.wav) then: touch -r f.wav f16.wav"},
		{riff(chunk("fmt ", fmtBody(1, 1, rate, 24)), d), "f.wav is 24-bit."},
		{riff(chunk("fmt ", fmtBody(3, 1, rate, 32)), d), "f.wav is 32-bit float."},
		{riff(chunk("fmt ", extBody(2, rate, 32, 3)), d), "f.wav is 32-bit float."},
		{riff(chunk("fmt ", fmtBody(2, 1, rate, 4)), d), "f.wav is ADPCM."},
		{append([]byte("RF64"), riff()[4:]...), "f.wav is an RF64 file. Only plain WAV is read."},
		{[]byte("\x00\x00\x00\x20ftypM4A "), "f.wav is not a WAV file. Convert it first: ffmpeg -i f.wav -c:a pcm_s16le f16.wav"},
		{riff(chunk("fmt ", fmtBody(1, 1, rate, 16))), "f.wav holds no audio."},
	}
	for _, c := range cases {
		dir := t.TempDir()
		os.WriteFile(filepath.Join(dir, "f.wav"), c.b, 0o644)
		wd, _ := os.Getwd()
		os.Chdir(dir)
		_, err := openWAV("f.wav")
		os.Chdir(wd)
		if err == nil || !strings.HasPrefix(err.Error(), c.want) {
			t.Errorf("got %v, want %q", err, c.want)
		}
	}
	if newName("call.m4a") != "call.wav" || newName("call.WAV") != "call16.wav" || quote("my call.wav") != "'my call.wav'" {
		t.Error("conversion names")
	}
}

func win(rms float64) window {
	return window{sumsq: uint64(math.Round(rms * rms * 320)), n: 320, peak: 100}
}

func TestFloorP10(t *testing.T) {
	var w []window
	for i := 1; i <= 21; i++ {
		w = append(w, win(float64(i*10)))
	}
	if got := floorLSB(w); math.Abs(got-30) > 0.01 { // 21 windows: index floor(0.1*20) = 2
		t.Errorf("p10 of 21: %v", got)
	}
	if got := floorLSB(w[:20]); math.Abs(got-20) > 0.01 { // 20 windows: index floor(0.1*19) = 1
		t.Errorf("p10 of 20: %v", got)
	}
	for i := 0; i < 30; i++ {
		w = append(w, window{n: 320, peak: 1}) // gated windows do not count
	}
	if got := floorLSB(w); math.Abs(got-30) > 0.01 {
		t.Errorf("p10 with gated: %v", got)
	}
	if floorLSB(w[21:]) != 1 || floorLSB([]window{{sumsq: 4, n: 320, peak: 2}}) != 1 {
		t.Error("floor must never be below 1 LSB")
	}
}

// signal builds generated test audio: "t" tone, "n" noise, "z" exact zero.
func signal(parts ...any) []int16 {
	var s []int16
	seed := uint32(1)
	for i := 0; i < len(parts); i += 2 {
		kind, sec := parts[i].(string), parts[i+1].(float64)
		for j := 0; j < int(math.Round(sec*rate)); j++ {
			switch kind {
			case "t":
				s = append(s, int16(math.Round(0.3*32767*math.Sin(2*math.Pi*440*float64(j)/rate))))
			case "n":
				seed = seed*1664525 + 1013904223
				s = append(s, int16(int(seed>>16)%61-30))
			default:
				s = append(s, 0)
			}
		}
	}
	return s
}

func minutesOf(t *testing.T, s []int16, args ...string) (string, string, int) {
	t.Helper()
	p := put(t, "call.wav", riff(chunk("fmt ", fmtBody(1, 1, rate, 16)), chunk("data", pcm(s))))
	var out, errb bytes.Buffer
	code := run(append(args, p), &out, &errb)
	return strings.Join(strings.Fields(out.String()), " "), errb.String(), code
}

func TestToneAndZero(t *testing.T) {
	o := filepath.Join(t.TempDir(), "g.wav")
	doc, _, code := minutesOf(t, signal("t", 5.0, "z", 6.0, "t", 5.0), "-o", o)
	for _, want := range []string{
		"Quiet digital zero only: the floor is above -30 dBFS.",
		" 1. 00:00:05.0 6.0 s -inf 0% no ",
		"Dead air 6.0 s of 16.0 s (37.5%) in 1 pause.",
		"No room tone 1 pause, 6.0 s: digital zero in the file. Not copied.",
	} {
		if !strings.Contains(doc, want) {
			t.Errorf("missing %q in %s", want, doc)
		}
	}
	if _, err := os.Stat(o); code != 0 || err == nil || strings.Contains(doc, "Room tone g.wav") {
		t.Error("nothing should be written")
	}
}

func TestRoomTone(t *testing.T) {
	o := filepath.Join(t.TempDir(), "g.wav")
	doc, _, code := minutesOf(t, signal("t", 1.0, "n", 3.0, "t", 1.0, "z", 2.5, "t", 1.0, "n", 1.0, "t", 1.0, "n", 2.2, "t", 0.5), "-o", o)
	for _, want := range []string{
		" 1. 00:00:01.0 3.0 s", "100% yes", " 2. 00:00:05.0 2.5 s -inf 0% no ", " 3. 00:00:10.5 2.2 s",
		"in 3 pauses.", "Longest 3.0 s, item 1, at 00:00:01.0.", "Room tone " + o + ", 5.0 s, 2 pauses.",
	} {
		if !strings.Contains(doc, want) {
			t.Errorf("missing %q in %s", want, doc)
		}
	}
	st, err := os.Stat(o)
	// (3.0 - 0.10) + (2.2 - 0.10) - 0.010 = 4.99 s
	if code != 0 || err != nil || st.Size() != 44+int64(math.Round(4.99*rate))*2 {
		t.Errorf("gaps length: %v %v", st, err)
	}
	_, msg, code := minutesOf(t, signal("n", 3.0), "-o", o)
	if code != 2 || msg != "minutes: "+o+" already exists. Nothing was overwritten.\n" {
		t.Errorf("overwrite: %d %q", code, msg)
	}
}

func TestWording(t *testing.T) {
	p := pause{frames: 2 * rate, level: math.Inf(-1)}
	cases := []struct {
		n          int
		dead, lost string
	}{
		{0, "in 0 pauses.", "No pause of 2.0 s or longer was found at these settings."},
		{1, "in 1 pause.", "No room tone 1 pause, 2.0 s: digital zero in the file."},
		{2, "in 2 pauses.", "No room tone 2 pauses, 4.0 s: digital zero in the file."},
	}
	for _, c := range cases {
		var b bytes.Buffer
		d := doc{name: "x.wav", out: "gaps.wav", rate: rate, ch: 1, frames: 60 * rate, minSec: 2, above: 6}
		for i := 0; i < c.n; i++ {
			d.res.pauses = append(d.res.pauses, p)
		}
		writeDoc(&b, d)
		s := strings.Join(strings.Fields(b.String()), " ")
		if !strings.Contains(s, c.dead) || !strings.Contains(s, c.lost) {
			t.Errorf("%d pauses: %s", c.n, s)
		}
		for _, l := range strings.Split(b.String(), "\n") {
			if len(l) > lineMax {
				t.Errorf("line over %d columns: %q", lineMax, l)
			}
		}
	}
}

func TestDur(t *testing.T) {
	for s, want := range map[float64]string{18.2: "18.2 s", 59.96: "1 min 00 s", 60: "1 min 00 s", 2467: "41 min 07 s", 7421: "2 h 03 min 41 s", 3599.6: "1 h 00 min 00 s"} {
		if got := dur(s); got != want {
			t.Errorf("dur(%v) = %q, want %q", s, got, want)
		}
	}
	if got := wrap("1 h 00 min 00 s of 1 h 00 min 00 s (100.0%) in 1 pause.", 48); got[1] != "1 pause." {
		t.Errorf("a count must keep its noun: %q", got)
	}
	if clock(int64(12.29*rate), rate) != "00:00:12.2" {
		t.Error("start must truncate")
	}
}

func TestDeterministic(t *testing.T) {
	s := signal("t", 1.0, "n", 2.5, "t", 0.5, "z", 2.0, "t", 0.5, "n", 4.0, "t", 0.3)
	o := filepath.Join(t.TempDir(), "g.wav")
	a, _, _ := minutesOf(t, s, "-o", o)
	ga, _ := os.ReadFile(o)
	os.Remove(o)
	b, _, _ := minutesOf(t, s, "-o", o)
	gb, _ := os.ReadFile(o)
	if a != b || !bytes.Equal(ga, gb) || len(ga) == 0 {
		t.Errorf("two runs differ: %d %d\n%s\n%s", len(ga), len(gb), a, b)
	}
}

// A constant +1000 joined to a constant -1000 would step by 2000 unfaded.
func TestCrossfadeStep(t *testing.T) {
	s := make([]int16, 2*8000)
	for i := range s {
		s[i] = 1000
		if i >= 8000 {
			s[i] = -1000
		}
	}
	in, err := openWAV(put(t, "pm.wav", riff(chunk("fmt ", fmtBody(1, 1, rate, 16)), chunk("data", pcm(s)))))
	if err != nil {
		t.Fatal(err)
	}
	spans := []span{{0, 8000}, {8000, 16000}}
	var b bytes.Buffer
	if err := writeGaps(in, spans, &b); err != nil {
		t.Fatal(err)
	}
	out := b.Bytes()[44:]
	n := len(out) / 2
	if int64(n) != joinedFrames(rate, spans) || n != 2*(8000-1600)-160 {
		t.Fatalf("length %d", n)
	}
	step, prev := 0, 0
	for i := 0; i < n; i++ {
		v := int(int16(binary.LittleEndian.Uint16(out[2*i:])))
		if i > 0 {
			step = max(step, abs(v-prev))
		}
		prev = v
	}
	first := int16(binary.LittleEndian.Uint16(out))
	if step >= 20 || first != 0 || prev != 0 {
		t.Errorf("largest step %d, ends %d %d", step, first, prev)
	}
}

func abs(v int) int {
	if v < 0 {
		return -v
	}
	return v
}
