///|
/// Audio container or codec format recognised by [`sniff`].
///
/// The enum deliberately separates containers that carry a single codec
/// (`Wav`, `Aiff`, `Au`, `Flac`, `Mp3`) from Ogg streams, because Ogg needs a
/// second sniffing step to tell Vorbis, Opus, and FLAC apart. `Mp4` is reported
/// for ISO-BMFF containers such as `.m4a`; the codec still has to be inspected
/// by the backend that decodes it.
#derive(Eq, Debug)
pub(all) enum AudioFormat {
  Wav
  Aiff
  Au
  Flac
  Mp3
  OggVorbis
  OggOpus
  OggFlac
  Aac
  Mp4
}

///|
/// Stable lowercase name for an [`AudioFormat`].
pub fn AudioFormat::to_name(self : AudioFormat) -> String {
  match self {
    Wav => "wav"
    Aiff => "aiff"
    Au => "au"
    Flac => "flac"
    Mp3 => "mp3"
    OggVorbis => "ogg-vorbis"
    OggOpus => "ogg-opus"
    OggFlac => "ogg-flac"
    Aac => "aac"
    Mp4 => "mp4"
  }
}

///|
/// Conventional file extension for an [`AudioFormat`].
pub fn AudioFormat::extension(self : AudioFormat) -> String {
  match self {
    Wav => "wav"
    Aiff => "aiff"
    Au => "au"
    Flac => "flac"
    Mp3 => "mp3"
    OggVorbis => "ogg"
    OggOpus => "opus"
    OggFlac => "oga"
    Aac => "aac"
    Mp4 => "m4a"
  }
}

///|
/// Canonical decoded audio.
///
/// Samples are interleaved and normalised to `[-1.0, 1.0]`: frame `f`,
/// channel `c` lives at `samples[f * channels + c]`. `Float` (f32) is the
/// common denominator of the wasm-compatible decoders in this module; 32-bit
/// integer PCM can lose its lowest bits when converted, which is documented
/// per backend rather than silently pretending to be lossless.
pub struct AudioBuffer {
  sample_rate : Int32
  channels : Int32
  samples : Array[Float]
}

///|
/// Build an audio buffer from interleaved samples.
pub fn AudioBuffer::new(
  sample_rate : Int32,
  channels : Int32,
  samples : Array[Float],
) -> AudioBuffer {
  { sample_rate, channels, samples, }
}

///|
/// An empty buffer with no format information.
pub fn AudioBuffer::empty() -> AudioBuffer {
  { sample_rate: 0, channels: 0, samples: [], }
}

///|
/// Number of sample frames (samples per channel).
pub fn AudioBuffer::frames(self : AudioBuffer) -> Int32 {
  if self.channels <= 0 {
    0
  } else {
    self.samples.length() / self.channels
  }
}

///|
/// Duration in seconds, or `0.0` when the buffer has no sample rate.
pub fn AudioBuffer::duration_seconds(self : AudioBuffer) -> Double {
  if self.sample_rate <= 0 {
    0.0
  } else {
    self.frames().to_double() / self.sample_rate.to_double()
  }
}

///|
/// Static description of a decoded stream.
#derive(Eq, Debug)
pub struct AudioInfo {
  format : AudioFormat?
  sample_rate : Int32
  channels : Int32
  frames : Int32
  duration_seconds : Double
}

///|
/// Build stream information from a decoded buffer.
pub fn AudioInfo::from_buffer(
  format : AudioFormat?,
  buffer : AudioBuffer,
) -> AudioInfo {
  {
    format,
    sample_rate: buffer.sample_rate,
    channels: buffer.channels,
    frames: buffer.frames(),
    duration_seconds: buffer.duration_seconds(),
  }
}

///|
/// A format-agnostic, pull-based decoder over an already decoded buffer.
///
/// Every backend produces an `AudioBuffer`; this type gives all of them the
/// same `info()` / `next(max_frames)` / `seek()` interface. The first version
/// buffers the whole input. True streaming adapters can be added behind the
/// same methods once a backend exposes incremental PCM.
pub struct AudioDecoder {
  priv info : AudioInfo
  priv buffer : AudioBuffer
  priv mut cursor : Int32
}

///|
/// Build a decoder over a decoded buffer.
pub fn AudioDecoder::new(
  format : AudioFormat?,
  buffer : AudioBuffer,
) -> AudioDecoder {
  { info: AudioInfo::from_buffer(format, buffer), buffer, cursor: 0, }
}

///|
/// Stream information.
pub fn AudioDecoder::info(self : AudioDecoder) -> AudioInfo {
  self.info
}

///|
/// Current position in frames.
pub fn AudioDecoder::position(self : AudioDecoder) -> Int32 {
  self.cursor
}

///|
/// Frames left before the end.
pub fn AudioDecoder::remaining_frames(self : AudioDecoder) -> Int32 {
  self.info.frames - self.cursor
}

///|
/// Whether the cursor has reached the end.
pub fn AudioDecoder::is_done(self : AudioDecoder) -> Bool {
  self.cursor >= self.info.frames
}

///|
/// Move the cursor to `frame`, clamped to `[0, frames]`.
pub fn AudioDecoder::seek(self : AudioDecoder, frame : Int32) -> Unit {
  let total = self.info.frames
  if frame <= 0 {
    self.cursor = 0
  } else if frame >= total {
    self.cursor = total
  } else {
    self.cursor = frame
  }
}

///|
/// Rewind to the first frame.
pub fn AudioDecoder::reset(self : AudioDecoder) -> Unit {
  self.cursor = 0
}

///|
/// Return at most `max_frames` interleaved samples and advance the cursor.
///
/// `None` means the cursor is at the end, or `max_frames <= 0`.
pub fn AudioDecoder::next(
  self : AudioDecoder,
  max_frames : Int32,
) -> Array[Float]? {
  let total = self.info.frames
  if max_frames <= 0 || self.cursor >= total {
    return None
  }
  let available = total - self.cursor
  let count = if max_frames < available { max_frames } else { available }
  let channels = self.buffer.channels
  let start = self.cursor * channels
  let end = start + count * channels
  let chunk : Array[Float] = []
  let mut index = start
  while index < end {
    chunk.push(self.buffer.samples[index])
    index = index + 1
  }
  self.cursor = self.cursor + count
  Some(chunk)
}

///|
/// Like [`AudioDecoder::next`], but wraps the chunk in an `AudioBuffer`.
pub fn AudioDecoder::next_buffer(
  self : AudioDecoder,
  max_frames : Int32,
) -> AudioBuffer? {
  match self.next(max_frames) {
    Some(samples) =>
      Some(
        AudioBuffer::new(self.buffer.sample_rate, self.buffer.channels, samples),
      )
    None => None
  }
}

///|
/// Failure modes shared by every backend.
#derive(Eq, Debug)
pub(all) enum AudioError {
  /// The bytes were recognised, but no backend in the current package set
  /// can decode this format.
  UnsupportedFormat(AudioFormat)
  /// The magic bytes did not match any known format.
  UnknownFormat
  /// The bytes are malformed, truncated, or violate the format specification.
  InvalidData(String)
  /// The backend recognised the format but failed while decoding.
  DecodeFailed(String)
}

///|
/// Human-readable explanation of an [`AudioError`].
pub fn AudioError::message(self : AudioError) -> String {
  match self {
    UnsupportedFormat(format) => "unsupported audio format: " + format.to_name()
    UnknownFormat => "unrecognised audio format"
    InvalidData(message) => "invalid audio data: " + message
    DecodeFailed(message) => "decode failed: " + message
  }
}

///|
/// Compare `text` with `bytes` starting at `offset`.
fn ascii_at(bytes : Bytes, offset : Int32, text : Bytes) -> Bool {
  let length = text.length()
  if offset < 0 || bytes.length() < offset + length {
    return false
  }
  let mut index = 0
  while index < length {
    if bytes[offset + index] != text[index] {
      return false
    }
    index = index + 1
  }
  true
}

///|
/// Search for an ASCII marker in the first `limit` bytes.
fn contains_ascii(bytes : Bytes, needle : Bytes, limit : Int32) -> Bool {
  let length = needle.length()
  if length == 0 {
    return true
  }
  let end = if bytes.length() < limit { bytes.length() } else { limit }
  let mut offset = 0
  while offset + length <= end {
    if ascii_at(bytes, offset, needle) {
      return true
    }
    offset = offset + 1
  }
  false
}

///|
/// MPEG audio frame sync: 11 set bits, a valid version, and a layer other
/// than "reserved".
fn looks_like_mpeg_audio(bytes : Bytes) -> Bool {
  if bytes.length() < 2 {
    return false
  }
  let first = bytes[0].to_int()
  let second = bytes[1].to_int()
  if first == 0xFF && (second & 0xE0) == 0xE0 {
    let version = (second >> 3) & 0x03
    let layer = (second >> 1) & 0x03
    version != 1 && layer != 0
  } else {
    false
  }
}

///|
/// ADTS sync word used by raw AAC streams.
fn looks_like_adts(bytes : Bytes) -> Bool {
  bytes.length() >= 2 &&
  bytes[0].to_int() == 0xFF &&
  (bytes[1].to_int() & 0xF6) == 0xF0
}

///|
/// Detect a supported audio format from its leading bytes.
///
/// This is a pure magic-number check: it never allocates, never reads beyond
/// the input, and is safe on truncated files. Ogg streams additionally look
/// for `OpusHead`, the RFC 5334 `\x7fFLAC` mapping marker, or `vorbis` in the
/// first 256 bytes.
pub fn sniff(bytes : Bytes) -> AudioFormat? {
  if (
      ascii_at(bytes, 0, b"RIFF") ||
      ascii_at(bytes, 0, b"RF64") ||
      ascii_at(bytes, 0, b"BW64")
    ) &&
    ascii_at(bytes, 8, b"WAVE") {
    return Some(Wav)
  }
  if ascii_at(bytes, 0, b"FORM") &&
    (ascii_at(bytes, 8, b"AIFF") || ascii_at(bytes, 8, b"AIFC")) {
    return Some(Aiff)
  }
  if ascii_at(bytes, 0, b".snd") {
    return Some(Au)
  }
  if ascii_at(bytes, 0, b"fLaC") {
    return Some(Flac)
  }
  if ascii_at(bytes, 0, b"OggS") {
    if contains_ascii(bytes, b"OpusHead", 256) {
      return Some(OggOpus)
    }
    // Check the binary FLAC mapping marker before the ASCII `vorbis` search:
    // a FLAC comment block can legitimately contain the word "vorbis".
    if contains_ascii(bytes, b"\x7fFLAC", 256) {
      return Some(OggFlac)
    }
    if contains_ascii(bytes, b"vorbis", 256) {
      return Some(OggVorbis)
    }
    return None
  }
  if ascii_at(bytes, 0, b"ID3") {
    return Some(Mp3)
  }
  if ascii_at(bytes, 4, b"ftyp") {
    return Some(Mp4)
  }
  if looks_like_mpeg_audio(bytes) {
    return Some(Mp3)
  }
  if looks_like_adts(bytes) {
    return Some(Aac)
  }
  None
}