package main

import (
	"bytes"
	"fmt"
	"math"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"testing"
)

// realInput is the test binary itself, or the first repository file of at
// least 600,000 bytes when the binary holds a run of 22,050 or more of one
// byte value between offsets 100,000 and 600,000 (an inserted byte would not
// differ inside such a run and could split a ring). It fails, never skips.
func realInput(t *testing.T) []byte {
	t.Helper()
	exe, err := os.Executable()
	if err != nil {
		t.Fatal(err)
	}
	local, _ := filepath.Glob("*")
	for _, p := range append([]string{exe}, local...) {
		b, err := os.ReadFile(p)
		if err == nil && len(b) >= 600000 && !longRun(b[100000:600000], 22050) {
			return b
		}
	}
	t.Fatal("no real input: the test binary has a long run of one byte value and no repository file of 600,000 bytes qualifies")
	return nil
}

func longRun(d []byte, n int) bool {
	run := 0
	for i := range d {
		if i > 0 && d[i] == d[i-1] {
			run++
		} else {
			run = 1
		}
		if run >= n {
			return true
		}
	}
	return false
}

func flipped(b []byte, at ...int) []byte {
	c := bytes.Clone(b)
	for _, o := range at {
		c[o] ^= 1
	}
	return c
}

func TestIdenticalIsExactlyZero(t *testing.T) {
	a := realInput(t)
	res := measure(file{b: a}, file{b: bytes.Clone(a)}, 10)
	for j, v := range res.r {
		if v != 0 {
			t.Fatalf("r[%d] = %g, want exactly 0", j, v)
		}
	}
	path := filepath.Join(t.TempDir(), "null.wav")
	if err := writeWAV(path, res.pcm); err != nil {
		t.Fatal(err)
	}
	w, _ := os.ReadFile(path)
	if len(w) != 44+2*silentMax || bytes.ContainsFunc(w[44:], func(r rune) bool { return r != 0 }) {
		t.Fatalf("WAV is %d bytes with non-zero data, want %d bytes of header and zeros", len(w), 44+2*silentMax)
	}
}

func TestSubtractionEqualsDifference(t *testing.T) {
	a := file{b: realInput(t)}
	b := file{b: flipped(a.b, 100000)}
	res := measure(a, b, 10)
	d := sound(func(j int) float64 {
		if j < res.e-res.w {
			return float64(a.val(res.w+j)-b.val(res.w+j)) / 256
		}
		return 0
	}, res.t)
	worst := 0.0
	for j := range d {
		worst = max(worst, math.Abs(d[j]-res.r[j]))
	}
	if worst > 1e-9*res.peak {
		t.Fatalf("subtraction is off from the string of the difference by %g, peak %g", worst, res.peak)
	}
}

func TestSilentBeforeFirstDifference(t *testing.T) {
	a := realInput(t)
	res := measure(file{b: a}, file{b: flipped(a, 100000)}, 10)
	for j := range FS {
		if res.pcm[j] != 0 {
			t.Fatalf("sample %d = %d before the first difference", j, res.pcm[j])
		}
	}
	if res.pcm[FS] == 0 {
		t.Fatal("sample 44,100 is 0, want the pluck")
	}
}

func TestFlipPeak(t *testing.T) {
	a := realInput(t)
	res := measure(file{b: a}, file{b: flipped(a, 100000)}, 10)
	if got := fmt.Sprintf("%+.1f", 20*math.Log10(res.peak)); got != "-48.2" {
		t.Fatalf("peak %s dBFS, want -48.2", got)
	}
	top := 0
	for _, v := range res.pcm {
		top = max(top, abs(int(v)))
	}
	if top != 23197 {
		t.Fatalf("loudest sample %d, want 23197", top)
	}
}

// TestStringIsSharpOfA2 drives the string with sines from 109.80 to 110.40 Hz
// and finds where the steady state gain peaks.
func TestStringIsSharpOfA2(t *testing.T) {
	const settle, hold = 10 * FS, 2 * FS
	best, bestGain := 0.0, 0.0
	for k := 0; k <= 60; k++ {
		hz := 109.80 + 0.01*float64(k)
		s := sound(func(j int) float64 { return math.Sin(2 * math.Pi * hz * float64(j) / FS) }, settle+hold)
		gain := 0.0
		for _, v := range s[settle:] {
			gain = max(gain, math.Abs(v))
		}
		if gain > bestGain {
			best, bestGain = hz, gain
		}
	}
	t.Logf("steady state gain peaks at %.2f Hz", best)
	if math.Abs(best-110.11) > 0.02 || best <= 110.05 {
		t.Fatalf("gain peaks at %.2f Hz, want 110.11 within 0.02 and above 110.05", best)
	}
	if hz, cents := tuning(); fmt.Sprintf("%.2f %+.1f", hz, cents) != "110.11 +1.8" {
		t.Fatalf("tuning %.4f Hz %+.3f cents", hz, cents)
	}
}

func TestRings(t *testing.T) {
	a := realInput(t)
	burst := bytes.Clone(a)
	copy(burst[100000:110000], a[500000:510000])
	ins := append(append(bytes.Clone(a[:100000]), a[100000]^1), a[100000:]...)
	cases := []struct {
		name     string
		b        []byte
		rings    int
		min, max float64
	}{
		{"one flip", flipped(a, 100000), 1, 0, 3.0},
		{"three flips", flipped(a, 100000, 250000, 400000), 3, 0, 3.0},
		{"burst", burst, 1, 2.0, 4.0},
		{"insertion", ins, 1, 8.0, 99},
		{"truncation", bytes.Clone(a[:100000]), 1, 8.0, 99},
	}
	for _, c := range cases {
		res := measure(file{b: a}, file{b: c.b}, 10)
		t.Logf("%s: %d rings, longest %.1f s", c.name, res.rings, res.longest)
		if res.rings != c.rings || res.longest < c.min || res.longest > c.max {
			t.Errorf("%s: %d rings, longest %.2f s; want %d, between %.1f and %.1f s", c.name, res.rings, res.longest, c.rings, c.min, c.max)
		}
	}
}

func TestPositions(t *testing.T) {
	cases := []struct {
		a, b                     string
		count, first, last, runs int
	}{
		{"ab", "abc", 2, 2, 3, 1},
		{"ab", "ab\x00", 2, 2, 3, 1}, // a NUL is not an end
		{"", "", 0, -1, -1, 0},
		{"abcd", "abXY", 2, 2, 3, 1},
		{"abcd", "xbcy", 2, 0, 3, 2},
		{"abcd", "abcd", 0, -1, -1, 0},
	}
	for _, c := range cases {
		v := compare(file{b: []byte(c.a)}, file{b: []byte(c.b)}, 10)
		if v.count != c.count || v.first != c.first || v.last != c.last || v.runs != c.runs {
			t.Errorf("%q vs %q: count %d first %d last %d runs %d", c.a, c.b, v.count, v.first, v.last, v.runs)
		}
	}
	if v := compare(file{b: []byte("a\x00")}, file{none: true}, 10); v.count != 2 || v.first != 0 || v.last != 2 {
		t.Errorf("single file: %+v, want the a and the end mark", v)
	}
	// The skip over equal chunks agrees with the plain rule, across chunk edges.
	a := realInput(t)
	for _, b := range [][]byte{
		flipped(a, chunk-1, chunk, 2*chunk-1, 200000),
		append(bytes.Clone(a[:chunk]), a[chunk-1:]...),
		bytes.Clone(a[:3*chunk]),
	} {
		want := verdict{first: -1, last: -1, lastW: -1, lmax: max(len(a), len(b))}
		fa, fb := file{b: a}, file{b: b}
		for i := 0; i <= want.lmax; i++ {
			if fa.val(i) != fb.val(i) {
				if want.first < 0 {
					want.first = i
				}
				if i == 0 || fa.val(i-1) == fb.val(i-1) {
					want.runs++
				}
				if i < recordingStart(want.first)+FS*10 {
					want.lastW = i
				}
				want.last = i
				want.count++
			}
		}
		if got := compare(fa, fb, 10); got != want {
			t.Errorf("compare %+v, plain rule %+v", got, want)
		}
	}
}

func TestSheetFits(t *testing.T) {
	dir := t.TempDir()
	a := realInput(t)
	write := func(name string, b []byte) string {
		p := filepath.Join(dir, name)
		if err := os.WriteFile(p, b, 0o644); err != nil {
			t.Fatal(err)
		}
		return p
	}
	real := write("real.bin", a)
	same := write("same.bin", a)
	flip := write("flip1.bin", flipped(a, 100000))
	long := write(strings.Repeat("n", 52)+".bin", flipped(a, 100000))
	wavOut := filepath.Join(dir, "null.wav")
	header := regexp.MustCompile(`^NULL TEST {18}\d{4}-\d\d-\d\d {18}Form NT-1$`)
	cases := map[string][]string{
		"identical":     {"-q", "-o", wavOut, real, same},
		"different":     {"-q", "-o", wavOut, real, flip},
		"single file":   {"-q", "-o", wavOut, "README.md"},
		"-q without -o": {"-q", real, flip},
		"long name":     {"-q", "-o", wavOut, long, real},
	}
	for name, args := range cases {
		var out, errs bytes.Buffer
		code, play := run(args, &out, &errs)
		lines := strings.Split(strings.TrimSuffix(out.String(), "\n"), "\n")
		if code == 2 || play != "" || errs.Len() > 0 || len(lines) != 20 {
			t.Fatalf("%s: exit %d, play %q, stderr %q, %d lines", name, code, play, errs.String(), len(lines))
		}
		for _, l := range lines {
			if len(l) > 64 || strings.ContainsFunc(l, func(r rune) bool { return r < ' ' || r > '~' }) {
				t.Errorf("%s: line over 64 columns or not ASCII: %q", name, l)
			}
		}
		if !header.MatchString(lines[0]) {
			t.Errorf("%s: line 1 is %q", name, lines[0])
		}
		if name == "-q without -o" && lines[15] != "File       not written" {
			t.Errorf("-q without -o: %q", lines[15])
		}
		if name == "long name" && !strings.HasPrefix(lines[2], "A          ..."+strings.Repeat("n", 23)+".bin ") {
			t.Errorf("long name: %q", lines[2])
		}
	}
}

func TestWavHeader(t *testing.T) {
	want := []byte("RIFF\x28\x00\x00\x00WAVEfmt \x10\x00\x00\x00\x01\x00\x01\x00\x44\xac\x00\x00\x88\x58\x01\x00\x02\x00\x10\x00data\x04\x00\x00\x00")
	got := wav([]int16{1, -1})
	if !bytes.Equal(got[:44], want) || !bytes.Equal(got[44:], []byte{1, 0, 0xff, 0xff}) {
		t.Fatalf("header % x", got)
	}
}

func TestSingleFileHasNoDC(t *testing.T) {
	b, err := os.ReadFile("README.md")
	if err != nil {
		t.Fatal(err)
	}
	res := measure(file{b: b}, file{none: true}, 10)
	sum, top := 0, 0
	for _, v := range res.pcm {
		sum += int(v)
		top = max(top, abs(int(v)))
	}
	mean := math.Abs(float64(sum)) / float64(len(res.pcm))
	if mean >= 0.01*float64(top) || res.pcm[0] == 0 {
		t.Fatalf("mean %.1f against peak %d, first sample %d", mean, top, res.pcm[0])
	}
}
