package main

import (
	"errors"
	"flag"
	"fmt"
	"io"
	"math"
	"os"
	"path/filepath"
	"strings"
)

const notice = `minutes: records the silences in a recording, and only those.

  minutes [flags] recording.wav

  -min SECONDS   shortest pause that gets a minute (default 2.0)
  -above DB      loudness over the noise floor that still counts
                 as quiet (default 6.0)
  -o FILE        where the pauses are joined (default gaps.wav)

Reads 16-bit PCM WAV, mono or stereo, at any sample rate. For
other formats, convert and keep the date (Dated: reads it):
  ffmpeg -i call.m4a -c:a pcm_s16le call.wav
  or, on a Mac: afconvert -f WAVE -d LEI16 call.m4a call.wav
  touch -r call.m4a call.wav

Prints the numbered pauses, the total dead air and the longest
gap. Writes the pauses that hold room tone to gaps.wav.

normal is dead
`

func main() { os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) }

func run(args []string, stdout, stderr io.Writer) int {
	fail := func(code int, format string, a ...any) int {
		fmt.Fprintf(stderr, "minutes: "+format+"\n", a...)
		return code
	}
	fs := flag.NewFlagSet("minutes", flag.ContinueOnError)
	fs.SetOutput(io.Discard)
	minSec := fs.Float64("min", 2.0, "")
	above := fs.Float64("above", 6.0, "")
	out := fs.String("o", "gaps.wav", "")
	if err := fs.Parse(args); err != nil {
		if errors.Is(err, flag.ErrHelp) {
			fmt.Fprint(stdout, notice)
			return 0
		}
		return fail(2, "%v.", err)
	}
	switch {
	case fs.NArg() == 0:
		fmt.Fprint(stdout, notice)
		return 0
	case fs.NArg() > 1 && strings.HasPrefix(fs.Arg(1), "-"):
		return fail(2, "flags go before the recording.")
	case fs.NArg() > 1:
		return fail(2, "one recording at a time.")
	case !(*minSec >= 0.5):
		return fail(2, "-min must be at least 0.5.")
	case math.IsInf(*minSec, 1):
		return fail(2, "-min must be a number of seconds.")
	case !(*above >= 0 && *above <= 40):
		return fail(2, "-above must be between 0 and 40.")
	}
	path := fs.Arg(0)

	in, err := openWAV(path)
	if err != nil {
		return fail(2, "%v", err)
	}
	defer in.f.Close()
	if _, err := os.Lstat(*out); err == nil {
		return fail(2, "%s already exists. Nothing was overwritten.", quote(*out))
	}
	wins, frames, err := measure(in)
	if err != nil {
		return fail(2, "%s cannot be read (%v).", quote(path), err)
	}
	if frames == 0 {
		return fail(2, "%s holds no audio.", quote(path))
	}
	res := analyze(wins, in.rate, in.ch, *minSec, *above)

	var spans []span
	for _, p := range res.pauses {
		if p.copied {
			spans = append(spans, span{p.startFrame, p.startFrame + p.frames})
		}
	}
	gaps := joinedFrames(in.rate, spans)
	if gaps > 0 {
		if 36+gaps*int64(2*in.ch) > math.MaxUint32 {
			return fail(1, "%s would be larger than a WAV can hold (4 GiB). Nothing was written.", quote(*out))
		}
		if err := create(*out, in, spans); err != nil {
			return fail(1, "%s could not be written (%v).", quote(*out), err)
		}
	}

	st, err := in.f.Stat()
	if err != nil {
		return fail(2, "%s cannot be read (%v).", quote(path), err)
	}
	writeDoc(stdout, doc{
		name: filepath.Base(path), dated: st.ModTime().Local().Format("2006-01-02"), out: *out,
		rate: in.rate, ch: in.ch, frames: frames, minSec: *minSec, above: *above,
		res: res, gapsFrames: gaps,
	})
	return 0
}

// create writes a new file and never replaces one; a failed write leaves nothing.
func create(path string, in *wavIn, spans []span) error {
	f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
	if err != nil {
		return errors.Unwrap(err)
	}
	err = writeGaps(in, spans, f)
	if cerr := f.Close(); err == nil {
		err = cerr
	}
	if err != nil {
		os.Remove(path)
	}
	return err
}

// newName is where a conversion should go: call.m4a to call.wav, and
// call.wav to call16.wav, so no message ever says to overwrite the input.
func newName(path string) string {
	ext := filepath.Ext(path)
	stem := strings.TrimSuffix(path, ext)
	if strings.EqualFold(ext, ".wav") {
		return stem + "16.wav"
	}
	return stem + ".wav"
}

// quote makes a file name safe to paste into a shell, and leaves plain ones alone.
func quote(s string) string {
	if s != "" && strings.Trim(s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-/+,:@") == "" {
		return s
	}
	return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
