package main

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"io"
	"sort"
	"strings"
	"unicode"
)

// The one accepted format: 16-bit PCM, 44100 Hz, 2 channels. One frame is 4 bytes.
const (
	rate       = 44100
	frameBytes = 4
)

type wavInfo struct {
	dataOffset int64  // byte offset of the data payload in the file
	fileFrames int64  // data size (cut at the end of the file) divided by 4
	software   string // the LIST/INFO ISFT value, or empty
}

// parseWAV walks the RIFF chunks from byte 12 and returns the file's facts, or the
// exact refusal reason.
func parseWAV(r io.ReaderAt, size int64) (wavInfo, string) {
	var w wavInfo
	head := make([]byte, 12)
	if _, err := r.ReadAt(head, 0); err != nil || string(head[0:4]) != "RIFF" || string(head[8:12]) != "WAVE" {
		return w, "not a WAV file"
	}
	var fmtc []byte
	dataSize := int64(-1)
	for pos := int64(12); pos+8 <= size; {
		ch := make([]byte, 8)
		if _, err := r.ReadAt(ch, pos); err != nil {
			break
		}
		id, n := string(ch[0:4]), int64(binary.LittleEndian.Uint32(ch[4:8]))
		body := pos + 8
		switch id {
		case "fmt ":
			if n >= 16 && body+16 <= size {
				fmtc = make([]byte, 16)
				r.ReadAt(fmtc, body)
			}
		case "data":
			if dataSize < 0 {
				w.dataOffset, dataSize = body, min(n, size-body)
			}
		case "LIST":
			if n <= 1<<16 && body+n <= size {
				b := make([]byte, n)
				r.ReadAt(b, body)
				if sw, ok := isft(b); ok {
					w.software = sw
				}
			}
		}
		pos = body + n + n%2
	}
	if fmtc == nil {
		return w, "not a WAV file"
	}
	le := binary.LittleEndian
	switch tag, ch, hz, bits := le.Uint16(fmtc[0:]), le.Uint16(fmtc[2:]), le.Uint32(fmtc[4:]), le.Uint16(fmtc[14:]); {
	case tag != 1:
		return w, fmt.Sprintf("format tag %d, want 1 (PCM)", tag)
	case ch != 2:
		return w, fmt.Sprintf("%d channels, want 2", ch)
	case hz != rate:
		return w, fmt.Sprintf("%d Hz, want 44100", hz)
	case bits != 16:
		return w, fmt.Sprintf("%d bits, want 16", bits)
	}
	switch {
	case dataSize < 0:
		return w, "no data chunk"
	case dataSize%frameBytes != 0:
		return w, fmt.Sprintf("data chunk size %d not a multiple of 4", dataSize)
	case dataSize/frameBytes < rate:
		return w, "shorter than 1 second"
	}
	w.fileFrames = dataSize / frameBytes
	return w, ""
}

// isft reads the ISFT entry of a LIST chunk of type INFO. A value with a control
// character counts as absent.
func isft(b []byte) (string, bool) {
	if len(b) < 4 || string(b[0:4]) != "INFO" {
		return "", false
	}
	for p := 4; p+8 <= len(b); {
		n := int(binary.LittleEndian.Uint32(b[p+4 : p+8]))
		if p+8+n > len(b) {
			break
		}
		if string(b[p:p+4]) == "ISFT" {
			v := string(bytes.TrimRight(b[p+8:p+8+n], "\x00"))
			if hasControl(v) {
				return "", false
			}
			return v, true
		}
		p += 8 + n + n%2
	}
	return "", false
}

func hasControl(s string) bool { return strings.IndexFunc(s, unicode.IsControl) >= 0 }

// streamHeader is the station's own 44-byte header: open-ended sizes, never a copy
// of a source file's header.
func streamHeader() []byte {
	h := make([]byte, 44)
	le := binary.LittleEndian
	copy(h[0:], "RIFF")
	le.PutUint32(h[4:], 0xFFFFFFFF)
	copy(h[8:], "WAVEfmt ")
	le.PutUint32(h[16:], 16)
	le.PutUint16(h[20:], 1)
	le.PutUint16(h[22:], 2)
	le.PutUint32(h[24:], rate)
	le.PutUint32(h[28:], rate*frameBytes)
	le.PutUint16(h[32:], frameBytes)
	le.PutUint16(h[34:], 16)
	copy(h[36:], "data")
	le.PutUint32(h[40:], 0xFFFFFFFF)
	return h
}

type refusal struct{ name, reason string }

// convertLoops builds the pasteable POSIX loops that apply to these refusals: the
// first for other formats, the second naming each lowercase .wav refused for its
// channels, rate or bit depth. Both write new files and leave the originals.
func convertLoops(refused []refusal) []string {
	var loops, wavs []string
	other := false
	for _, r := range refused {
		for _, ext := range []string{".mp3", ".flac", ".m4a"} {
			other = other || strings.HasSuffix(r.name, ext)
		}
		if strings.HasSuffix(r.name, ".wav") && (strings.HasSuffix(r.reason, "channels, want 2") ||
			strings.HasSuffix(r.reason, "Hz, want 44100") || strings.HasSuffix(r.reason, "bits, want 16")) {
			wavs = append(wavs, r.name)
		}
	}
	if other {
		loops = append(loops, `for f in *.mp3 *.flac *.m4a; do ffmpeg -i "$f" -ar 44100 -ac 2 -c:a pcm_s16le "${f%.*}.wav"; done`)
	}
	if len(wavs) > 0 {
		sort.Strings(wavs)
		for i, n := range wavs {
			wavs[i] = "'" + strings.ReplaceAll(n, "'", `'\''`) + "'"
		}
		loops = append(loops, "for f in "+strings.Join(wavs, " ")+`; do ffmpeg -i "$f" -ar 44100 -ac 2 -c:a pcm_s16le "${f%.wav}.44k.wav"; done`)
	}
	return loops
}
