package main

import (
	"encoding/binary"
	"fmt"
	"math"
	"syscall"
	"time"
)

// bell is one tolling bell, minor-third profile, relative to the prime f0.
// These are starting values for tuning by ear; only the constants change.
var bell = []struct{ ratio, amp, tau float64 }{
	{0.5, 0.35, 1.6},     // hum
	{1.0, 1.00, 0.8},     // prime
	{1.183, 0.70, 0.676}, // tierce
	{1.506, 0.45, 0.531}, // quint
	{2.0, 0.90, 0.4},     // nominal
	{2.514, 0.35, 0.318},
	{2.662, 0.30, 0.301},
	{3.011, 0.25, 0.266},
}

const (
	f0   = 261.63   // Hz, the prime
	flat = 0.943874 // 2^(-1/12), one semitone down
	rate = 22050    // samples per second

	gap        = 8820  // 0.4 s between strikes, in samples
	tail       = 35280 // 1.6 s after the last strike
	strokeLen  = 70560 // 3.2 s, one stroke buffer
	attack     = 0.004 * rate
	strokeFade = 4410  // 0.2 s raised cosine at the end of every stroke
	pealFade   = 13230 // 0.6 s raised cosine at the end of every peal

	// gain is fixed, never a per-peal normalisation. The loudest moment of
	// any peal is a flat last stroke struck into the ringing of the ones
	// before it: 3.9986 unscaled, in the 69 stroke peal as in the 9. This
	// puts it at 0.9 of full scale. TestPeak measures it again whenever the
	// table above changes.
	gain = 0.9 / 3.9987

	maxMinutes = 60
)

// ending is what the kernel reported: an exit code, or the signal that killed it.
type ending struct {
	code int
	sig  syscall.Signal
}

func (e ending) failed() bool { return e.sig != 0 || e.code != 0 }

// strokeCount gives the prelude (9 ended on its own, 3 killed) and one stroke
// for each full minute, at most 60.
func strokeCount(e ending, elapsed time.Duration) (prelude, minutes int) {
	prelude = 9
	if e.sig != 0 {
		prelude = 3
	}
	return prelude, min(maxMinutes, int(elapsed/time.Minute))
}

// strikes gives each stroke's offset in samples: the prelude 0.4 s apart,
// one beat of rest, then the minutes 0.4 s apart.
func strikes(prelude, minutes int) []int {
	at := make([]int, 0, prelude+minutes)
	for i := 0; i < prelude; i++ {
		at = append(at, gap*i)
	}
	for j := 1; j <= minutes; j++ {
		at = append(at, gap*(prelude+j))
	}
	return at
}

// stroke renders one strike of the bell at pitch times the table, 3.2 s long.
// Each partial is a phasor turned and decayed by one complex multiply per
// sample, so there is no per-sample sin or exp. The tau values stay those of
// the table, so a flat stroke moves in pitch only.
func stroke(pitch float64) []float64 {
	buf := make([]float64, strokeLen)
	for _, p := range bell {
		w := 2 * math.Pi * f0 * p.ratio * pitch / rate
		r := math.Exp(-1 / (p.tau * rate))
		cr, ci := r*math.Cos(w), r*math.Sin(w)
		zr, zi := 1.0, 0.0
		for n := range buf {
			buf[n] += p.amp * zi
			zr, zi = zr*cr-zi*ci, zr*ci+zi*cr
		}
	}
	for n := 0; float64(n) < attack; n++ {
		buf[n] *= float64(n) / attack
	}
	fadeOut(buf[len(buf)-strokeFade:])
	return buf
}

// fadeOut applies a raised cosine from 1 to exactly 0 at the last sample.
func fadeOut(s []float64) {
	last := float64(len(s) - 1)
	for k := range s {
		s[k] *= 0.5 * (1 + math.Cos(math.Pi*float64(k)/last))
	}
}

// peal lays the strokes out and mixes them at the fixed gain. Each stroke is
// rendered once and added at its offset; what falls past the end is dropped.
// When flatLast is set the final stroke is the flat one.
func peal(prelude, minutes int, flatLast bool) []float64 {
	at := strikes(prelude, minutes)
	out := make([]float64, at[len(at)-1]+tail)
	normal, last := scaled(stroke(1)), []float64(nil)
	if flatLast {
		last = scaled(stroke(flat))
	}
	for i, a := range at {
		s := normal
		if last != nil && i == len(at)-1 {
			s = last
		}
		s = s[:min(len(s), len(out)-a)]
		dst := out[a:][:len(s)]
		for k := range s {
			dst[k] += s[k]
		}
	}
	fadeOut(out[len(out)-pealFade:])
	return out
}

func scaled(s []float64) []float64 {
	for k := range s {
		s[k] *= gain
	}
	return s
}

// wav encodes the peal as 22050 Hz mono 16-bit PCM with one LIST INFO ICMT line.
func wav(samples []float64, comment string) []byte {
	le := binary.LittleEndian
	icmt := append([]byte(comment), 0)
	pad := len(icmt) % 2
	list := 4 + 8 + len(icmt) + pad
	data := 2 * len(samples)

	b := make([]byte, 0, 12+24+8+list+8+data)
	b = append(b, "RIFF"...)
	b = le.AppendUint32(b, uint32(4+24+8+list+8+data))
	b = append(b, "WAVEfmt "...)
	b = le.AppendUint32(b, 16)
	b = le.AppendUint16(b, 1) // PCM
	b = le.AppendUint16(b, 1) // mono
	b = le.AppendUint32(b, rate)
	b = le.AppendUint32(b, rate*2)
	b = le.AppendUint16(b, 2)
	b = le.AppendUint16(b, 16)
	b = append(b, "LIST"...)
	b = le.AppendUint32(b, uint32(list))
	b = append(b, "INFOICMT"...)
	b = le.AppendUint32(b, uint32(len(icmt)))
	b = append(b, icmt...)
	b = append(b, make([]byte, pad)...)
	b = append(b, "data"...)
	b = le.AppendUint32(b, uint32(data))
	b = append(b, make([]byte, data)...)
	pcm := b[len(b)-data:]
	for i, x := range samples {
		v := math.Round(x * 32767)
		if v > 32767 {
			v = 32767
		} else if v < -32768 {
			v = -32768
		}
		le.PutUint16(pcm[2*i:], uint16(int16(v)))
	}
	return b
}

var sigNames = map[syscall.Signal]string{
	syscall.SIGHUP: "SIGHUP", syscall.SIGINT: "SIGINT", syscall.SIGQUIT: "SIGQUIT",
	syscall.SIGILL: "SIGILL", syscall.SIGTRAP: "SIGTRAP", syscall.SIGABRT: "SIGABRT",
	syscall.SIGBUS: "SIGBUS", syscall.SIGFPE: "SIGFPE", syscall.SIGKILL: "SIGKILL",
	syscall.SIGUSR1: "SIGUSR1", syscall.SIGSEGV: "SIGSEGV", syscall.SIGUSR2: "SIGUSR2",
	syscall.SIGPIPE: "SIGPIPE", syscall.SIGALRM: "SIGALRM", syscall.SIGTERM: "SIGTERM",
	syscall.SIGXCPU: "SIGXCPU", syscall.SIGXFSZ: "SIGXFSZ",
}

// record is the plain record of a run: duration, status, strokes. It never
// holds the command. paint marks the one word that may be coloured.
func record(e ending, elapsed time.Duration, strokes int, paint func(string) string) string {
	s := int(elapsed / time.Second)
	var d string
	switch {
	case s < 60:
		d = fmt.Sprintf("%d s", s)
	case s < 3600:
		d = fmt.Sprintf("%d min %d s", s/60, s%60)
	default:
		d = fmt.Sprintf("%d h %d min", s/3600, s%3600/60)
	}
	status := "exit " + fmt.Sprint(e.code)
	switch {
	case e.sig != 0 && sigNames[e.sig] != "":
		status = "killed by " + paint(sigNames[e.sig])
	case e.sig != 0:
		status = "killed by " + paint(fmt.Sprintf("signal %d", int(e.sig)))
	case e.code != 0:
		status = "exit " + paint(fmt.Sprint(e.code))
	}
	return fmt.Sprintf("tailors: %s, %s, %d strokes", d, status, strokes)
}

func plain(s string) string { return s }
