#!/usr/bin/env bash

die() {
  echo "Error: $*" >&2
  exit 1
}

require_command() {
  command -v "$1" >/dev/null 2>&1 || die "missing required command: $1"
}

timestamp_to_seconds() {
  local timestamp="$1"

  awk -v ts="$timestamp" '
    function fail() {
      printf "invalid timestamp: %s\n", ts > "/dev/stderr"
      exit 1
    }
    BEGIN {
      n = split(ts, parts, ":")
      if (n < 1 || n > 3) {
        fail()
      }
      total = 0
      for (i = 1; i <= n; i++) {
        if (parts[i] !~ /^[0-9]+([.][0-9]+)?$/) {
          fail()
        }
        total = total * 60 + parts[i]
      }
      printf "%.6f\n", total
    }
  '
}

math() {
  local expression="$1"
  awk "BEGIN { value = $expression; printf \"%.6f\\n\", value }"
}

assert_non_negative_number() {
  local label="$1"
  local value="$2"

  awk -v v="$value" 'BEGIN { exit !(v ~ /^[0-9]+([.][0-9]+)?$/) }' || die "$label must be a non-negative number"
}

assert_positive_number() {
  local label="$1"
  local value="$2"

  assert_non_negative_number "$label" "$value"
  awk -v v="$value" 'BEGIN { exit !(v > 0) }' || die "$label must be positive"
}

ensure_parent_dir() {
  mkdir -p "$(dirname "$1")"
}

has_stream() {
  local input_file="$1"
  local selector="$2"

  ffprobe -v error -select_streams "$selector" -show_entries stream=index -of csv=p=0 "$input_file" |
    sed -n '1p' |
    grep -q .
}

ffprobe_stream_field() {
  local input_file="$1"
  local selector="$2"
  local field="$3"

  ffprobe -v error -select_streams "$selector" -show_entries "stream=$field" -of default=nk=1:nw=1 "$input_file" |
    sed -n '1p'
}

ffprobe_format_field() {
  local input_file="$1"
  local field="$2"

  ffprobe -v error -show_entries "format=$field" -of default=nk=1:nw=1 "$input_file" |
    sed -n '1p'
}

normalized_extension() {
  printf '%s' "${1##*.}" | tr '[:upper:]' '[:lower:]'
}

escape_filter_value() {
  printf '%s' "$1" | sed "s/\\\\/\\\\\\\\/g; s/:/\\\\:/g; s/'/\\\\\\\\'/g; s/,/\\\\,/g; s/\\[/\\\\[/g; s/\\]/\\\\]/g"
}

concat_list_path() {
  printf "%s" "$1" | sed "s/'/'\\\\''/g"
}
