package main

import (
	"bytes"
	"crypto/sha256"
	"fmt"
	"os"
	"path/filepath"
	"sort"
	"strings"
	"sync"
	"testing"
	"time"
)

// testStation is a station on a folder with a settable clock and a captured console.
type testStation struct {
	*station
	cmu   sync.Mutex // guards the test clock and console
	clock time.Time
	lines []string
}

func newTest(t *testing.T, dir string, loc *time.Location, at time.Time) *testStation {
	ts := &testStation{clock: at}
	ts.station = newStation(dir, loc, loc.String(), func() time.Time {
		ts.cmu.Lock()
		defer ts.cmu.Unlock()
		return ts.clock
	}, func(msg string) {
		ts.cmu.Lock()
		defer ts.cmu.Unlock()
		ts.lines = append(ts.lines, msg)
	})
	return ts
}

func (ts *testStation) set(t time.Time) {
	ts.cmu.Lock()
	ts.clock = t
	ts.cmu.Unlock()
}

func (ts *testStation) console() string {
	ts.cmu.Lock()
	defer ts.cmu.Unlock()
	return strings.Join(ts.lines, "\n")
}

// folder holds three short files (2.5, 3 and 4 s) and one ffmpeg-made file.
func folder(t *testing.T) string {
	dir := t.TempDir()
	writeWAV(t, dir, "a.wav", 110250, 'a', "")
	writeWAV(t, dir, "b.wav", 132300, 'b', "")
	writeWAV(t, dir, "c.wav", 176400, 'c', "")
	writeWAV(t, dir, "d.wav", 88200, 'd', "Lavf62.12.101")
	os.WriteFile(filepath.Join(dir, "talk.mp3"), []byte("ID3"), 0o644)
	return dir
}

func mustDay(t *testing.T, s *testStation, at time.Time) *dayLog {
	t.Helper()
	l, err := s.day(dayStart(at, s.loc))
	if err != nil {
		t.Fatal(err)
	}
	return l
}

func md5ish(t *testing.T, path string) string {
	b, err := os.ReadFile(path)
	if err != nil {
		t.Fatal(err)
	}
	return fmt.Sprintf("%x", sha256.Sum256(b))
}

func TestOrder(t *testing.T) {
	dir := folder(t)
	at := time.Date(2026, 10, 13, 9, 0, 0, 0, time.UTC)
	l := mustDay(t, newTest(t, dir, time.UTC, at), at)
	names := []string{"a.wav", "b.wav", "c.wav", "d.wav"}
	for k := 0; k < 2; k++ {
		sort.Slice(names, func(i, j int) bool {
			ki := sha256.Sum256([]byte(fmt.Sprintf("continuity:2026-10-13:%d\x00%s", k, names[i])))
			kj := sha256.Sum256([]byte(fmt.Sprintf("continuity:2026-10-13:%d\x00%s", k, names[j])))
			return bytes.Compare(ki[:], kj[:]) < 0
		})
		for i, n := range names {
			if got := l.slots[4*k+i].name; got != n {
				t.Fatalf("pass %d row %d: %s, want %s", k, i, got, n)
			}
		}
	}
	pos := int64(0)
	for _, sl := range l.slots {
		if sl.start != pos {
			t.Fatalf("gap or overlap at %d", sl.start)
		}
		pos += sl.frames
	}
	last := l.slots[len(l.slots)-1]
	if pos != 86400*rate || l.frames != 86400*rate || last.frames > last.fileFrames {
		t.Fatalf("day ends at %d, want %d, last %+v", pos, 86400*rate, last)
	}
	if len(l.refused) != 1 || l.refused[0] != (refusal{"talk.mp3", "not a WAV file"}) {
		t.Fatalf("refused %+v", l.refused)
	}
	b, _ := os.ReadFile(filepath.Join(dir, ".continuity", "2026-10-13.tsv"))
	head := "# continuity 2\n# day 2026-10-13\n# zone UTC\n# frames 3810240000\n# rule sha256(\"continuity:DAY:PASS\" NUL name) ascending\n# refused talk.mp3\tnot a WAV file\n"
	if !strings.HasPrefix(string(b), head) || !strings.Contains(string(b), "\t78\td.wav\tLavf62.12.101\n") || !strings.Contains(string(b), "\t44\ta.wav\t\n") {
		t.Fatalf("log:\n%s", b[:400])
	}
}

// A file added after the day was built first plays from the next midnight; a
// restart mid-day reads the same frozen log.
func TestFrozen(t *testing.T) {
	dir := folder(t)
	at := time.Date(2026, 10, 13, 15, 0, 0, 0, time.UTC)
	mustDay(t, newTest(t, dir, time.UTC, at), at)
	path := filepath.Join(dir, ".continuity", "2026-10-13.tsv")
	before := md5ish(t, path)
	writeWAV(t, dir, "zz.wav", 44100, 'z', "")

	again := newTest(t, dir, time.UTC, at.Add(time.Hour)) // a restart
	l := mustDay(t, again, at)
	if md5ish(t, path) != before {
		t.Fatal("today's log was rewritten")
	}
	for _, sl := range l.slots {
		if sl.name == "zz.wav" {
			t.Fatal("zz.wav entered a frozen day")
		}
	}
	tomorrow := mustDay(t, again, at.Add(24*time.Hour))
	found := false
	for _, sl := range tomorrow.slots[:5] {
		found = found || sl.name == "zz.wav"
	}
	if !found {
		t.Fatal("zz.wav is not in the first pass of the next day")
	}
}

func TestMidnight(t *testing.T) {
	end := time.Date(2026, 10, 13, 23, 59, 59, 999999999, time.UTC)
	if d := dayStart(end, time.UTC); d.Day() != 13 {
		t.Fatalf("%v", d)
	}
	next := end.Add(time.Nanosecond)
	if d := dayStart(next, time.UTC); d.Day() != 14 || !d.Equal(next) {
		t.Fatalf("%v", d)
	}
	half := next.Add(500 * time.Millisecond)
	if f := absFrame(half) - dayStart(half, time.UTC).Unix()*rate; f != 22050 {
		t.Fatalf("frame at 00:00:00.5 is %d, want 22050", f)
	}
	if f := absFrame(end) - dayStart(end, time.UTC).Unix()*rate; f != 86400*rate-1 {
		t.Fatalf("last frame %d", f)
	}
}

func dstDay(t *testing.T, date string, seconds int64) {
	berlin, err := time.LoadLocation("Europe/Berlin")
	if err != nil {
		t.Fatal(err)
	}
	start, _ := time.ParseInLocation("2006-01-02", date, berlin)
	s := newTest(t, folder(t), berlin, start.Add(12*time.Hour))
	l := mustDay(t, s, start)
	last := l.slots[len(l.slots)-1]
	if dayFrames(start) != seconds*rate || l.frames != seconds*rate || last.start+last.frames != seconds*rate {
		t.Fatalf("%s: %d frames, want %d s", date, l.frames, seconds)
	}
	// The listings print wall-clock start times: 05:00 real time after midnight
	// reads 06:00 on the spring day and 04:00 on the autumn day.
	v := s.view(l, (5*3600+10)*rate, true, false, 0)
	want := map[int64]string{82800: "06:00:00", 90000: "04:00:00"}[seconds]
	if v.Open.Start[:2] != want[:2] {
		t.Fatalf("%s: slot on air at 5 h starts %s, want hour %s", date, v.Open.Start, want[:2])
	}
}

func TestDSTSpring(t *testing.T) { dstDay(t, "2026-03-29", 82800) }
func TestDSTAutumn(t *testing.T) { dstDay(t, "2026-10-25", 90000) }

func TestWithdrawn(t *testing.T) {
	dir := folder(t)
	at := time.Date(2026, 10, 13, 10, 0, 0, 0, time.UTC)
	s := newTest(t, dir, time.UTC, at)
	l := mustDay(t, s, at)
	rel := absFrame(at) - l.startA()
	cur := l.at(rel)
	// The slot on air keeps its open file when the file goes; the next slot of
	// that file is withdrawn once, in writing, and plays silence.
	s.tick()
	name := l.slots[cur].name
	os.Remove(filepath.Join(dir, name))
	b, err := s.render(absFrame(at), 4410)
	if err != nil || !bytes.Equal(b, want(l, rel, 4410)) {
		t.Fatalf("the slot on air lost its audio: %v", err)
	}
	next := cur + 1
	for l.slots[next].name != name {
		next++
	}
	sl := l.slots[next]
	s.set(l.start.Add(time.Duration(sl.start*1e9/rate) + time.Millisecond))
	s.tick()
	s.tick()
	b, _ = s.render(l.startA()+sl.start+100, 4410)
	if !bytes.Equal(b, make([]byte, len(b))) {
		t.Fatal("a withdrawn slot is not silence")
	}
	again := newTest(t, dir, time.UTC, s.now()) // a restart inside the withdrawn slot
	again.startUp()
	rec, _ := os.ReadFile(filepath.Join(dir, ".continuity", "2026-10-13.withdrawn"))
	if string(rec) != fmt.Sprintf("%d\tmissing\n", sl.start) {
		t.Fatalf("withdrawn record %q", rec)
	}
	s.set(l.start.Add(time.Duration((sl.start+sl.frames)*1e9/rate) + time.Millisecond))
	v := s.view(l, absFrame(s.now())-l.startA(), true, true, 0)
	seen := false
	for _, r := range v.Rows {
		switch {
		case r.Frame == sl.start:
			seen = r.Note == "Withdrawn. Silence, "+length(sl.frames)+"."
		case strings.Contains(r.Note, "Withdrawn"):
			t.Fatalf("a row the station did not see withdrawn says so: %+v", r)
		}
	}
	if !seen {
		t.Fatal("the withdrawn slot is not listed as withdrawn")
	}
	// A changed size withdraws too.
	other := "a.wav"
	if name == other {
		other = "b.wav"
	}
	f, _ := os.OpenFile(filepath.Join(dir, other), os.O_APPEND|os.O_WRONLY, 0)
	f.Write([]byte{0, 0, 0, 0})
	f.Close()
	i := next + 1
	for l.slots[i].name != other {
		i++
	}
	s.set(l.start.Add(time.Duration(l.slots[i].start*1e9/rate) + time.Millisecond))
	s.tick()
	rec, _ = os.ReadFile(filepath.Join(dir, ".continuity", "2026-10-13.withdrawn"))
	if string(rec) != fmt.Sprintf("%d\tmissing\n%d\tsize\n", sl.start, l.slots[i].start) {
		t.Fatalf("size record %q", rec)
	}
}

// want is what a slot plays from frame rel: frame i of a test file is
// [i, i>>8, i>>16, first letter of its name].
func want(l *dayLog, rel, n int64) []byte {
	var b []byte
	for k := int64(0); k < n; k++ {
		sl := l.slots[l.at(rel+k)]
		f := rel + k - sl.start
		b = append(b, byte(f), byte(f>>8), byte(f>>16), sl.name[0])
	}
	return b
}
