package main

import (
	"bytes"
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strconv"
	"testing"
	"time"
)

func TestMidnightBuild(t *testing.T) {
	// The ticker builds tomorrow's log at 23:59:00, not before.
	early := folder(t)
	tomorrow := filepath.Join(early, ".continuity", "2026-10-14.tsv")
	e := newTest(t, early, time.UTC, time.Date(2026, 10, 13, 23, 58, 59, 900000000, time.UTC))
	if err := e.startUp(); err != nil {
		t.Fatal(err)
	}
	if _, err := os.Stat(tomorrow); err == nil {
		t.Fatal("tomorrow's log was built before 23:59:00")
	}
	e.set(time.Date(2026, 10, 13, 23, 59, 0, 0, time.UTC))
	e.tick()
	if _, err := os.Stat(tomorrow); err != nil {
		t.Fatal("tomorrow's log is not built at 23:59:00")
	}

	// A start inside the last minute builds it at start-up.
	dir := folder(t)
	at := time.Date(2026, 10, 13, 23, 59, 59, 900000000, time.UTC)
	s := newTest(t, dir, time.UTC, at)
	if err := s.startUp(); err != nil {
		t.Fatal(err)
	}
	if _, err := os.Stat(filepath.Join(dir, ".continuity", "2026-10-14.tsv")); err != nil {
		t.Fatal("tomorrow's log is not built at 23:59:59.9")
	}
	old, next := mustDay(t, s, at), mustDay(t, s, at.Add(time.Second))
	// 0.2 s from 23:59:59.9: the last 0.1 s of the old day, then frame 0 of the new.
	b, err := s.render(absFrame(at), 8820)
	if err != nil {
		t.Fatal(err)
	}
	w := append(want(old, 86400*rate-4410, 4410), want(next, 0, 4410)...)
	if !bytes.Equal(b, w) {
		t.Fatal("the read across midnight has a gap or the wrong frames")
	}

	// The build mutex is held while the new day's log is half written: the
	// stream waits, then reads the complete log.
	dir2 := folder(t)
	s2 := newTest(t, dir2, time.UTC, at.Add(-2*time.Minute))
	mustDay(t, s2, at)
	s2.station.mu.Lock()
	os.WriteFile(filepath.Join(dir2, ".continuity", "2026-10-14.tsv"), []byte("# continuity 2\n# day 2026-10-14\n"), 0o644)
	got := make(chan []byte)
	go func() { // the stream reaching frame 0 of the new day
		b, _ := s2.render(next.startA(), 4410)
		got <- b
	}()
	select {
	case <-got:
		t.Fatal("the stream did not wait for the build")
	case <-time.After(200 * time.Millisecond):
	}
	if err := s2.writeLog(dayStart(at.Add(time.Second), time.UTC)); err != nil {
		t.Fatal(err)
	}
	s2.station.mu.Unlock()
	if b := <-got; !bytes.Equal(b, want(next, 0, 4410)) {
		t.Fatal("after the wait the stream did not read the complete log")
	}
}

// liveClock is the real clock moved to a chosen instant, plus a settable jump.
func liveClock(ts *testStation, base time.Time) func(time.Duration) {
	t0 := time.Now()
	var jump time.Duration
	ts.station.now = func() time.Time {
		ts.cmu.Lock()
		defer ts.cmu.Unlock()
		return base.Add(time.Since(t0) + jump)
	}
	return func(d time.Duration) {
		ts.cmu.Lock()
		jump += d
		ts.cmu.Unlock()
	}
}

func TestStream(t *testing.T) {
	dir := folder(t)
	base := time.Date(2026, 10, 13, 11, 0, 0, 0, time.UTC)
	s := newTest(t, dir, time.UTC, base)
	jump := liveClock(s, base)
	l := mustDay(t, s, base)
	srv := httptest.NewServer(s.mux())
	defer srv.Close()

	req, _ := http.NewRequest("GET", srv.URL+"/stream.wav", nil)
	req.Header.Set("Range", "bytes=1000-")
	before := absFrame(s.now()) - l.startA()
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	defer res.Body.Close()
	after := absFrame(s.now()) - l.startA()
	h := res.Header
	if res.StatusCode != 200 || h.Get("Content-Type") != "audio/wav" || h.Get("Cache-Control") != "no-store" ||
		h.Get("Accept-Ranges") != "none" || res.ContentLength != -1 || h.Get("X-Continuity-Day") != "2026-10-13" {
		t.Fatalf("%d %v", res.StatusCode, h)
	}
	frame, _ := strconv.ParseInt(h.Get("X-Continuity-Frame"), 10, 64)
	if frame < before || frame > after {
		t.Fatalf("X-Continuity-Frame %d is not the clock (%d..%d)", frame, before, after)
	}
	body := make([]byte, 44+4*22050)
	if _, err := io.ReadFull(res.Body, body); err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(body[:44], streamHeader()) || !bytes.Equal(body[44:], want(l, frame, 22050)) {
		t.Fatal("the stream is not the station header followed by the slots at the clock")
	}

	// A clock jump of more than 5 seconds closes the stream.
	jump(6 * time.Second)
	done := make(chan error)
	go func() { _, err := io.Copy(io.Discard, res.Body); done <- err }()
	select {
	case <-done:
	case <-time.After(2 * time.Second):
		t.Fatal("the stream stayed open after a 6 s jump")
	}
	if c := s.console(); !bytes.Contains([]byte(c), []byte("listener joined")) || !bytes.Contains([]byte(c), []byte("listener left")) {
		t.Fatalf("console %q", c)
	}
}
