package main

import (
	"bufio"
	"bytes"
	"crypto/sha256"
	"errors"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"
)

type fileEntry struct {
	name string
	size int64
	wavInfo
}

// One row of a day log. All positions are frames since the day's start.
type slot struct {
	start, frames, fileFrames, fileSize, dataOffset int64
	name, software                                  string
}

type dayLog struct {
	date    string
	start   time.Time // local midnight that begins the day
	frames  int64
	refused []refusal
	slots   []slot
}

// startA is the day's first frame counted from the Unix epoch.
func (l *dayLog) startA() int64 { return l.start.Unix() * rate }

// at returns the index of the first slot that has not ended at frame rel. It is
// the slot on air when it exists and starts at or before rel.
func (l *dayLog) at(rel int64) int {
	return sort.Search(len(l.slots), func(i int) bool { return l.slots[i].start+l.slots[i].frames > rel })
}

type source struct {
	f         *os.File
	withdrawn bool
	end       int64 // absolute frame of the slot's end
}

type station struct {
	dir  string
	loc  *time.Location
	zone string
	now  func() time.Time // the one injected clock
	con  func(string)     // the console

	mu   sync.Mutex // the build mutex: every log build and every first read of a log
	logs map[string]*dayLog

	srcMu sync.Mutex // the slot-start check
	srcs  map[string]*source

	lastLog *dayLog // ticker state: the slot seen on air at the previous tick
	lastI   int
}

func newStation(dir string, loc *time.Location, zone string, now func() time.Time, con func(string)) *station {
	return &station{dir: dir, loc: loc, zone: zone, now: now, con: con, logs: map[string]*dayLog{}, srcs: map[string]*source{}}
}

// absFrame is floor(t since the epoch in ns * 44100 / 1e9), in integers. Days start
// on whole seconds, so a day's frame N is absFrame minus the day's startA.
func absFrame(t time.Time) int64 { return t.Unix()*rate + int64(t.Nanosecond())*rate/1e9 }

// ponytail: a zone whose midnight falls inside a DST gap gets Go's normalised start.
func dayStart(t time.Time, loc *time.Location) time.Time {
	y, m, d := t.In(loc).Date()
	return time.Date(y, m, d, 0, 0, 0, 0, loc)
}

func nextDay(start time.Time) time.Time {
	y, m, d := start.Date()
	return time.Date(y, m, d+1, 0, 0, 0, 0, start.Location())
}

// dayFrames is the day's length in seconds times 44100: 23 or 25 hours on a DST change.
func dayFrames(start time.Time) int64 { return int64(nextDay(start).Sub(start)/time.Second) * rate }

func title(name string) string {
	if len(name) > 4 && strings.EqualFold(name[len(name)-4:], ".wav") {
		return name[:len(name)-4]
	}
	return name
}

// scan checks every regular file in the folder whose name does not start with ".".
func scan(dir string) ([]fileEntry, []refusal, error) {
	ents, err := os.ReadDir(dir)
	if err != nil {
		return nil, nil, err
	}
	var acc []fileEntry
	var ref []refusal
	for _, e := range ents {
		name := e.Name()
		if strings.HasPrefix(name, ".") {
			continue
		}
		fi, err := os.Stat(filepath.Join(dir, name))
		if err != nil || !fi.Mode().IsRegular() {
			continue
		}
		if hasControl(name) {
			ref = append(ref, refusal{strconv.Quote(name), "name contains a control character"})
			continue
		}
		w, why := wavInfo{}, "not a WAV file"
		if f, err := os.Open(filepath.Join(dir, name)); err == nil {
			w, why = parseWAV(f, fi.Size())
			f.Close()
		}
		if why != "" {
			ref = append(ref, refusal{name, why})
			continue
		}
		acc = append(acc, fileEntry{name, fi.Size(), w})
	}
	return acc, ref, nil
}

// buildSlots applies the order rule: for pass k, files sorted ascending by
// sha256("continuity:DAY:k" NUL name), filled from frame 0 with no gap, the last
// programme cut at the day's end.
func buildSlots(date string, total int64, files []fileEntry) []slot {
	var slots []slot
	for k, pos := 0, int64(0); len(files) > 0 && pos < total; k++ {
		keys := map[string][32]byte{}
		for _, f := range files {
			keys[f.name] = sha256.Sum256([]byte(fmt.Sprintf("continuity:%s:%d\x00%s", date, k, f.name)))
		}
		order := append([]fileEntry(nil), files...)
		sort.Slice(order, func(i, j int) bool {
			a, b := keys[order[i].name], keys[order[j].name]
			return bytes.Compare(a[:], b[:]) < 0
		})
		for _, f := range order {
			if pos >= total {
				break
			}
			n := min(f.fileFrames, total-pos)
			slots = append(slots, slot{pos, n, f.fileFrames, f.size, f.dataOffset, f.name, f.software})
			pos += n
		}
	}
	return slots
}

func (s *station) logPath(date, ext string) string {
	return filepath.Join(s.dir, ".continuity", date+ext)
}

func (s *station) writeLog(start time.Time) error {
	date := start.Format("2006-01-02")
	files, refused, err := scan(s.dir)
	if err != nil {
		return err
	}
	total := dayFrames(start)
	var b strings.Builder
	fmt.Fprintf(&b, "# continuity 2\n# day %s\n# zone %s\n# frames %d\n", date, s.zone, total)
	b.WriteString("# rule sha256(\"continuity:DAY:PASS\" NUL name) ascending\n")
	sort.Slice(refused, func(i, j int) bool { return refused[i].name < refused[j].name })
	for _, r := range refused {
		fmt.Fprintf(&b, "# refused %s\t%s\n", r.name, r.reason)
	}
	for _, sl := range buildSlots(date, total, files) {
		fmt.Fprintf(&b, "%d\t%d\t%d\t%d\t%d\t%s\t%s\n", sl.start, sl.frames, sl.fileFrames, sl.fileSize, sl.dataOffset, sl.name, sl.software)
	}
	if err := os.MkdirAll(filepath.Join(s.dir, ".continuity"), 0o755); err != nil {
		return err
	}
	tmp := s.logPath(date, ".tsv.tmp")
	if err := os.WriteFile(tmp, []byte(b.String()), 0o644); err != nil {
		return err
	}
	return os.Rename(tmp, s.logPath(date, ".tsv"))
}

func readLog(path string, start time.Time) (*dayLog, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	l := &dayLog{date: start.Format("2006-01-02"), start: start}
	sc := bufio.NewScanner(f)
	for sc.Scan() {
		line := sc.Text()
		if v, ok := strings.CutPrefix(line, "# frames "); ok {
			l.frames, _ = strconv.ParseInt(v, 10, 64)
		} else if v, ok := strings.CutPrefix(line, "# refused "); ok {
			name, reason, _ := strings.Cut(v, "\t")
			l.refused = append(l.refused, refusal{name, reason})
		} else if line != "" && !strings.HasPrefix(line, "#") {
			c := strings.Split(line, "\t")
			if len(c) != 7 {
				return nil, fmt.Errorf("%s: a row without seven columns", path)
			}
			var n [5]int64
			for i := range n {
				if n[i], err = strconv.ParseInt(c[i], 10, 64); err != nil {
					return nil, fmt.Errorf("%s: %v", path, err)
				}
			}
			l.slots = append(l.slots, slot{n[0], n[1], n[2], n[3], n[4], c[5], c[6]})
		}
	}
	return l, sc.Err()
}

// day returns the frozen log of the day that begins at start. Whoever needs a log
// that does not exist yet builds it under the build mutex; anyone else waits, then
// reads the file. The file is never rewritten and is the only source of the day.
func (s *station) day(start time.Time) (*dayLog, error) {
	date := start.Format("2006-01-02")
	s.mu.Lock()
	defer s.mu.Unlock()
	if l := s.logs[date]; l != nil {
		return l, nil
	}
	path := s.logPath(date, ".tsv")
	if _, err := os.Stat(path); errors.Is(err, fs.ErrNotExist) {
		if err := s.writeLog(start); err != nil {
			return nil, err
		}
	}
	l, err := readLog(path, start)
	if err != nil {
		return nil, err
	}
	s.srcMu.Lock()
	for f := range s.withdrawn(date) {
		if i := l.at(f); i < len(l.slots) && l.slots[i].start == f {
			s.srcs[date+"/"+strconv.FormatInt(f, 10)] = &source{withdrawn: true, end: l.startA() + f + l.slots[i].frames}
		}
	}
	s.srcMu.Unlock()
	for d, old := range s.logs { // ponytail: keep about a week in memory, older days are read from disk
		if old.start.Before(start.AddDate(0, 0, -8)) {
			delete(s.logs, d)
		}
	}
	s.logs[date] = l
	return l, nil
}

// withdrawn reads the day's append-only record of slots that played silence.
func (s *station) withdrawn(date string) map[int64]bool {
	set := map[int64]bool{}
	b, _ := os.ReadFile(s.logPath(date, ".withdrawn"))
	for _, line := range strings.Split(string(b), "\n") {
		if f, _, ok := strings.Cut(line, "\t"); ok {
			if n, err := strconv.ParseInt(f, 10, 64); err == nil {
				set[n] = true
			}
		}
	}
	return set
}

// source is the slot-start check, made once per slot by whichever of the ticker and
// a stream reaches the slot first. It returns the slot's open file, or nil for
// silence. A missing file or a changed size withdraws the slot and is written down.
func (s *station) source(l *dayLog, i int) *os.File {
	sl := l.slots[i]
	key := l.date + "/" + strconv.FormatInt(sl.start, 10)
	s.srcMu.Lock()
	defer s.srcMu.Unlock()
	if src := s.srcs[key]; src != nil {
		return src.f
	}
	src := &source{end: l.startA() + sl.start + sl.frames}
	why := ""
	if f, err := os.Open(filepath.Join(s.dir, sl.name)); err != nil {
		why = "missing"
	} else if fi, err := f.Stat(); err != nil || fi.Size() != sl.fileSize {
		f.Close()
		why = "size"
	} else {
		src.f = f
	}
	if why != "" {
		src.withdrawn = true
		if w, err := os.OpenFile(s.logPath(l.date, ".withdrawn"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644); err == nil {
			fmt.Fprintf(w, "%d\t%s\n", sl.start, why)
			w.Close()
		}
	}
	s.srcs[key] = src
	return src.f
}

// closeEnded closes the files of slots that ended more than 30 s ago. No stream can
// be that far behind: it is closed at 5 s.
func (s *station) closeEnded(nowA int64) {
	s.srcMu.Lock()
	defer s.srcMu.Unlock()
	for k, src := range s.srcs {
		if src.f != nil && nowA-src.end > 30*rate {
			src.f.Close()
			src.f = nil
		}
		if nowA-src.end > 3600*rate {
			delete(s.srcs, k)
		}
	}
}
