package main

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

func chunk(id string, payload []byte) []byte {
	b := append([]byte(id), make([]byte, 4)...)
	binary.LittleEndian.PutUint32(b[4:], uint32(len(payload)))
	b = append(b, payload...)
	if len(payload)%2 == 1 {
		b = append(b, 0)
	}
	return b
}

func fmtChunk(tag, ch uint16, hz uint32, bits uint16) []byte {
	p := make([]byte, 16)
	le := binary.LittleEndian
	le.PutUint16(p[0:], tag)
	le.PutUint16(p[2:], ch)
	le.PutUint32(p[4:], hz)
	le.PutUint32(p[8:], hz*uint32(ch)*uint32(bits)/8)
	le.PutUint16(p[12:], ch*bits/8)
	le.PutUint16(p[14:], bits)
	return chunk("fmt ", p)
}

func listISFT(v string) []byte {
	return chunk("LIST", append([]byte("INFO"), chunk("ISFT", []byte(v+"\x00"))...))
}

func riff(chunks ...[]byte) []byte {
	body := []byte("WAVE")
	for _, c := range chunks {
		body = append(body, c...)
	}
	return append(chunk("RIFF", body)[:8], body...)
}

// pcm makes frames that can be recognised later: frame i of file id is
// [i, i>>8, i>>16, id].
func pcm(frames int, id byte) []byte {
	b := make([]byte, frames*4)
	for i := 0; i < frames; i++ {
		b[4*i], b[4*i+1], b[4*i+2], b[4*i+3] = byte(i), byte(i>>8), byte(i>>16), id
	}
	return b
}

// writeWAV writes a valid station file; with software set it carries ffmpeg's layout.
func writeWAV(t *testing.T, dir, name string, frames int, id byte, software string) {
	t.Helper()
	cs := [][]byte{fmtChunk(1, 2, 44100, 16)}
	if software != "" {
		cs = append(cs, listISFT(software))
	}
	cs = append(cs, chunk("data", pcm(frames, id)))
	if err := os.WriteFile(filepath.Join(dir, name), riff(cs...), 0o644); err != nil {
		t.Fatal(err)
	}
}

func parse(b []byte) (wavInfo, string) { return parseWAV(bytes.NewReader(b), int64(len(b))) }

func TestDataOffsetLIST(t *testing.T) {
	sec := pcm(44100, 1)
	w, why := parse(riff(fmtChunk(1, 2, 44100, 16), listISFT("Lavf62.12.101"), chunk("data", sec)))
	if why != "" || w.dataOffset != 78 || w.software != "Lavf62.12.101" || w.fileFrames != 44100 {
		t.Fatalf("ffmpeg layout: %+v %q, want offset 78 and Lavf62.12.101", w, why)
	}
	b := riff(fmtChunk(1, 2, 44100, 16), listISFT("Lavf62.12.101"), chunk("JUNK", []byte{1, 2, 3}), chunk("data", sec))
	w, why = parse(b)
	if why != "" || w.dataOffset != 78+12 || w.fileFrames != 44100 || !bytes.Equal(b[w.dataOffset:w.dataOffset+4], sec[:4]) {
		t.Fatalf("odd JUNK before data: %+v %q, want offset 90 (pad byte honoured)", w, why)
	}
	if _, why = parse(riff(fmtChunk(1, 2, 44100, 16), chunk("data", make([]byte, 6)))); why != "data chunk size 6 not a multiple of 4" {
		t.Fatalf("got %q", why)
	}
}

func TestRefusals(t *testing.T) {
	sec := chunk("data", pcm(44100, 1))
	cut := riff(fmtChunk(1, 2, 44100, 16), chunk("data", pcm(44101, 1)))
	binary.LittleEndian.PutUint32(cut[40:], 1<<30) // a data size that runs past the end
	for _, c := range []struct {
		b    []byte
		want string
	}{
		{[]byte("ID3\x04 not audio at all"), "not a WAV file"},
		{riff(sec), "not a WAV file"},
		{riff(fmtChunk(3, 2, 44100, 32), sec), "format tag 3, want 1 (PCM)"},
		{riff(fmtChunk(1, 1, 44100, 16), sec), "1 channels, want 2"},
		{riff(fmtChunk(1, 2, 48000, 16), sec), "48000 Hz, want 44100"},
		{riff(fmtChunk(1, 2, 44100, 24), sec), "24 bits, want 16"},
		{riff(fmtChunk(1, 2, 44100, 16)), "no data chunk"},
		{riff(fmtChunk(1, 2, 44100, 16), chunk("data", pcm(44099, 1))), "shorter than 1 second"},
		{append(cut, 9, 9), "data chunk size 176406 not a multiple of 4"},
		{cut, ""},
	} {
		if _, why := parse(c.b); why != c.want {
			t.Errorf("got %q, want %q", why, c.want)
		}
	}
	if w, _ := parse(cut); w.fileFrames != 44101 {
		t.Errorf("cut data: %d frames, want 44101", w.fileFrames)
	}
	dir := t.TempDir()
	writeWAV(t, dir, "a\x01b.wav", 44100, 1, "")
	if _, ref, _ := scan(dir); len(ref) != 1 || ref[0].reason != "name contains a control character" || ref[0].name != `"a\x01b.wav"` {
		t.Errorf("control character: %+v", ref)
	}
}

func TestConvertLoops(t *testing.T) {
	second := func(ref []refusal) string {
		for _, l := range convertLoops(ref) {
			if strings.Contains(l, ".44k.wav") {
				return l
			}
		}
		return ""
	}
	got := second([]refusal{
		{"mono.wav", "1 channels, want 2"},
		{"it's.wav", "48000 Hz, want 44100"},
		{"deep.wav", "24 bits, want 16"},
		{"broken.wav", "not a WAV file"},
		{"Talk.WAV", "1 channels, want 2"},
		{"talk.mp3", "not a WAV file"},
	})
	want := `for f in 'deep.wav' 'it'\''s.wav' 'mono.wav'; do ffmpeg -i "$f" -ar 44100 -ac 2 -c:a pcm_s16le "${f%.wav}.44k.wav"; done`
	if got != want {
		t.Fatalf("second loop:\n got %s\nwant %s", got, want)
	}
	loops := convertLoops([]refusal{{"talk.mp3", "not a WAV file"}, {"broken.wav", "not a WAV file"}, {"Talk.WAV", "1 channels, want 2"}})
	if len(loops) != 1 || loops[0] != `for f in *.mp3 *.flac *.m4a; do ffmpeg -i "$f" -ar 44100 -ac 2 -c:a pcm_s16le "${f%.*}.wav"; done` {
		t.Fatalf("with no .wav refused for format, only the first loop: %q", loops)
	}
	if loops := convertLoops([]refusal{{"notes.txt", "not a WAV file"}}); len(loops) != 0 {
		t.Fatalf("no loop applies: %q", loops)
	}
}

func TestStreamHeader(t *testing.T) {
	want := "52494646ffffffff57415645666d74201000000001000200" + "44ac000010b102000400100064617461ffffffff"
	if got := hex.EncodeToString(streamHeader()); got != want {
		t.Fatalf("header %s", got)
	}
}
