#include <math.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <SWI-Stream.h>
#include <SWI-Prolog.h>

// bfloat16 and float8_e4m3 are no C type: an element is its bits, a uint16_t and a uint8_t.
// A bfloat16 is the high half of a float32. A float8_e4m3 is the e4m3fn of torch and of the
// safetensors dtype F8_E4M3: a sign, 4 bits of exponent biased by 7, 3 of mantissa, no
// infinity, 0x7f and 0xff not a number, the greatest 448. Both round to the nearest, ties to
// even; a bfloat16 overflows to infinity, a float8_e4m3 to not a number.

// The bits of d as a float32 rounded to odd: truncated, the last bit set when inexact, so
// that rounding them again to fewer bits is rounding d once. d is a number.
static uint32_t odd_float_bits(double d)
{
  float f = (float)d;
  uint32_t u;
  memcpy(&u, &f, 4);
  if ((double)f != d)
  {
    double m = f < 0 ? -(double)f : (double)f;
    if (m > (d < 0 ? -d : d))
    {
      u -= 1;
    }
    u |= 1;
  }
  return u;
}

static uint32_t float_bits(double d)
{
  if (d != d)
  {
    return signbit(d) ? 0xffc00000u : 0x7fc00000u;
  }
  return odd_float_bits(d);
}

static uint16_t double_bfloat16(double d)
{
  uint32_t u = float_bits(d);
  if ((u & 0x7fffffffu) > 0x7f800000u)
  {
    return (uint16_t)((u >> 16) | 0x40);
  }
  return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1)) >> 16);
}

static double bfloat16_double(uint16_t h)
{
  uint32_t u = (uint32_t)h << 16;
  float f;
  memcpy(&f, &u, 4);
  return f;
}

static uint8_t double_float8_e4m3(double d)
{
  uint32_t u = float_bits(d);
  uint32_t s = (u >> 24) & 0x80, a = u & 0x7fffffffu;
  int e = (int)(a >> 23) - 127;
  if (e > 8)                          // 512 and more, infinity, not a number
  {
    return (uint8_t)(s | 0x7f);
  }
  if (e < -10)                        // less than half the least subnormal, 2^-9
  {
    return (uint8_t)s;
  }
  uint32_t m = (a & 0x7fffffu) | 0x800000u;
  int shift = e >= -6 ? 20 : 14 - e;  // a normal keeps 4 bits of m, a subnormal counts 2^-9
  uint32_t q = m >> shift, r = m & ((1u << shift) - 1), half = 1u << (shift - 1);
  q += r > half || (r == half && (q & 1));
  uint32_t b = e >= -6 ? ((uint32_t)(e + 6) << 3) + q : q;
  return (uint8_t)(s | (b > 0x7e ? 0x7f : b));
}

static double float8_e4m3_double(uint8_t b)
{
  int e = (b >> 3) & 15, m = b & 7;
  double v;
  if ((b & 0x7f) == 0x7f)
  {
    v = NAN;
  }
  else
  {
    v = e ? ldexp(8 + m, e - 10) : ldexp(m, -9);
  }
  return b & 0x80 ? -v : v;
}

#include "buffer_types.h"

static int release_buffer(atom_t ref)
{
  void *p = PL_blob_data(ref, NULL, NULL);
  if (p)
  {
    free(p);
  }
  return TRUE;
}

// A buffer prints as <buffer>(Address,Bytes): without this hook SWI-Prolog prints the
// bytes of a PL_BLOB_NOCOPY blob in hex, megabytes of them for a tensor.
static int write_buffer(IOSTREAM *s, atom_t ref, int flags)
{
  size_t size;
  void *p = PL_blob_data(ref, &size, NULL);
  (void)flags;
  return Sfprintf(s, "<buffer>(%p,%zu)", p, size) >= 0;
}

static PL_blob_t buffer_blob = {
  PL_BLOB_MAGIC,
  PL_BLOB_UNIQUE | PL_BLOB_NOCOPY,
  "buffer",
  release_buffer,
  NULL,
  write_buffer,
  NULL,
  NULL,
  NULL
};

static foreign_t c_buffer_alloc(term_t t, term_t count, term_t zero_t)
{
  if (!PL_is_variable(t))
  {
    PL_uninstantiation_error(t);
    return FALSE;
  }
  size_t size;

  if (PL_get_size_ex(count, &size))
  {
    void *p = malloc(size);

    if (p)
    {
      int zero;
      if (!PL_get_bool_ex(zero_t, &zero))
      {
        free(p);
        return FALSE;
      }
      if (zero)
      {
        memset(p, 0, size);
      }
      if (PL_unify_blob(t, p, size, &buffer_blob))
      {
        return TRUE;
      } else {
        free(p);
      }
    } else {
      PL_resource_error("memory");
    }
  }
  return FALSE;
}

static foreign_t c_buffer_size(term_t t, term_t count)
{
  PL_blob_t *blob_type;
  if (!PL_is_blob(t, &blob_type) || blob_type != &buffer_blob)
  {
    PL_type_error("buffer", t);
    return FALSE;
  }
  size_t size;
  if (PL_get_blob(t, NULL, &size, NULL)) {
    if (PL_unify_uint64(count, size)) {
      return TRUE;
    }
  }
  return FALSE;
}

static foreign_t c_buffer_free(term_t t)
{
  PL_blob_t *blob_type;
  if (!PL_is_blob(t, &blob_type) || blob_type != &buffer_blob)
  {
    PL_type_error("buffer", t);
    return FALSE;
  }
  atom_t atom;
  if (!PL_get_atom_ex(t, &atom))
  {
    return FALSE;
  }
  PL_free_blob(atom);
  return TRUE;
}

static foreign_t c_buffer_set(term_t t, term_t type_t, term_t i, term_t v)
{
  atom_t type;
  size_t size;
  void *buffer;
  PL_blob_t *blob_type;
  size_t offset;

  if (PL_get_atom_ex(type_t, &type)
      && PL_get_size_ex(i, &offset)
      && PL_get_blob(t, &buffer, &size, &blob_type)
      && blob_type == &buffer_blob)
  {
    return set(buffer, size, type, offset, v);
  }
  PL_type_error("buffer", t);
  return FALSE;
}

static foreign_t c_buffer_load(term_t t, term_t type_t, term_t i, term_t v)
{
  atom_t type;
  size_t offset, size;
  void *buffer;
  PL_blob_t *blob_type;

  if (PL_get_atom_ex(type_t, &type)
      && PL_get_size_ex(i, &offset)
      && PL_get_blob(t, &buffer, &size, &blob_type)
      && blob_type == &buffer_blob)
  {
    return load(buffer, size, type, offset, v);
  }
  PL_type_error("buffer", t);
  return FALSE;
}

static foreign_t c_buffer_type_size(term_t type_t, term_t size)
{
  atom_t type;
  size_t size_;
  if (PL_get_atom_ex(type_t, &type))
  {
    return atom_size(type, &size_) && PL_unify_uint64(size, size_);
  }
  return FALSE;
}

// The size arguments of the compound from the argument offset.
static foreign_t c_buffer_from_compound(term_t t, term_t type_t, term_t offset_t, term_t it_size, term_t comp)
{
  atom_t type, name;
  size_t arity, size, buffer_size, type_size, comp_offset;
  void *buffer;
  PL_blob_t *blob_type;

  if (PL_get_atom_ex(type_t, &type)
      && atom_size(type, &type_size)
      && PL_get_blob(t, &buffer, &buffer_size, &blob_type)
      && blob_type == &buffer_blob
      && PL_get_size_ex(offset_t, &comp_offset)
      && PL_get_size_ex(it_size, &size)
      && PL_get_compound_name_arity(comp, &name, &arity))
  {
    term_t arg = PL_new_term_ref();
    for (size_t i = 0; i < size; i++)
    {
      if (!PL_get_arg(comp_offset + i + 1, comp, arg) || !set(buffer, buffer_size, type, i, arg)) {
        return FALSE;
      }
    }
    return TRUE;
  }
  return FALSE;
}

// The size elements of the buffer from the element offset.
static foreign_t c_buffer_to_compound(term_t t, term_t type_t, term_t offset_t, term_t it_size, term_t name_t, term_t comp_out)
{
  atom_t type, name;
  size_t buffer_size, size, type_size, offset_elements;
  void *buffer;
  PL_blob_t *blob_type;

  if (PL_get_atom_ex(type_t, &type)
      && PL_get_atom_ex(name_t, &name)
      && atom_size(type, &type_size)
      && PL_get_blob(t, &buffer, &buffer_size, &blob_type)
      && blob_type == &buffer_blob
      && PL_get_size_ex(offset_t, &offset_elements)
      && PL_get_size_ex(it_size, &size))
  {
    size_t byte_offset = offset_elements * type_size;
    if (byte_offset > buffer_size) {
      return FALSE;
    }
    // load() checks its bounds against the rest of the buffer
    buffer = (char *)buffer + byte_offset;
    buffer_size -= byte_offset;

    term_t args = PL_new_term_refs(size);
    
    for (size_t offset = 0; offset < size; offset++)
    {
      if (!load(buffer, buffer_size, type, offset, args + offset)) {
        return FALSE;
      }
    }
    
    // name() for no elements: PL_cons_functor_v() would make the atom name.
    if (size == 0) {
      return PL_unify_compound(comp_out, PL_new_functor(name, 0));
    }
    term_t comp = PL_new_term_ref();
    if (!PL_cons_functor_v(comp, PL_new_functor(name, size), args)) {
      return FALSE;
    }
    return PL_unify(comp_out, comp);
  }
  return FALSE;
}

static foreign_t c_buffer_pointer(term_t t, term_t offset_t, term_t p)
{
  size_t offset, size;
  void *buffer;
  PL_blob_t *blob_type;
  if (PL_get_uint64_ex(offset_t, &offset)
      && PL_get_blob(t, &buffer, &size, &blob_type)
      && blob_type == &buffer_blob
      && offset <= size
      && PL_unify_pointer(p, (void*)((char*)(buffer)+offset)))
  {
    return TRUE;
  }
  return FALSE;
}


// The first Bytes bytes of the buffer, written to a binary stream.
static foreign_t c_buffer_write(term_t stream_t, term_t t, term_t bytes_t)
{
  IOSTREAM *s;
  size_t size, bytes;
  void *buffer;
  PL_blob_t *blob_type;

  if (!PL_get_size_ex(bytes_t, &bytes))
  {
    return FALSE;
  }
  if (!PL_get_blob(t, &buffer, &size, &blob_type) || blob_type != &buffer_blob)
  {
    return PL_type_error("buffer", t);
  }
  if (bytes > size)
  {
    return PL_domain_error("buffer_bytes", bytes_t);
  }
  if (!PL_get_stream(stream_t, &s, SIO_OUTPUT))
  {
    return FALSE;
  }
  size_t written = bytes ? Sfwrite(buffer, 1, bytes, s) : 0;
  if (written != bytes && !Sferror(s))
  {
    Sseterr(s, SIO_FERR, "short write");
  }
  return PL_release_stream(s);
}

// A new buffer holding the next Bytes bytes of a binary stream; fails, unifying
// nothing, when the stream ends before them.
static foreign_t c_buffer_read(term_t stream_t, term_t bytes_t, term_t t)
{
  IOSTREAM *s;
  size_t bytes;

  if (!PL_is_variable(t))
  {
    return PL_uninstantiation_error(t);
  }
  if (!PL_get_size_ex(bytes_t, &bytes) || !PL_get_stream(stream_t, &s, SIO_INPUT))
  {
    return FALSE;
  }
  void *p = malloc(bytes ? bytes : 1);
  if (!p)
  {
    PL_release_stream(s);
    return PL_resource_error("memory");
  }
  size_t got = bytes ? Sfread(p, 1, bytes, s) : 0;
  if (!PL_release_stream(s))
  {
    free(p);
    return FALSE;
  }
  if (got != bytes)
  {
    free(p);
    return FALSE;
  }
  if (PL_unify_blob(t, p, bytes, &buffer_blob))
  {
    return TRUE;
  }
  free(p);
  return FALSE;
}

#define MINMAX(CT, T, LO, HI)                       \
  do {                                              \
    const CT *e = (const CT *)buffer;               \
    T lo = e[0], hi = e[0];                         \
    for (size_t i = 1; i < n; i++)                  \
    {                                               \
      if (e[i] < lo) lo = e[i];                     \
      if (e[i] > hi) hi = e[i];                     \
    }                                               \
    *(LO) = lo; *(HI) = hi;                         \
  } while (0)

// The least and the greatest of the first N elements of an integer or bool buffer, N > 0.
static foreign_t c_buffer_minmax(term_t t, term_t type_t, term_t n_t, term_t min_t, term_t max_t)
{
  atom_t type;
  size_t n, size, type_size;
  void *buffer;
  PL_blob_t *blob_type;

  if (!PL_get_atom_ex(type_t, &type) || !PL_get_size_ex(n_t, &n))
  {
    return FALSE;
  }
  if (!PL_get_blob(t, &buffer, &size, &blob_type) || blob_type != &buffer_blob)
  {
    return PL_type_error("buffer", t);
  }
  if (!atom_size(type, &type_size))
  {
    return PL_domain_error("buffer_type", type_t);
  }
  if (n == 0 || n > size / type_size)
  {
    return PL_domain_error("buffer_elements", n_t);
  }
  int64_t slo, shi;
  uint64_t ulo, uhi;
  if (type == ATOM_bool)        { MINMAX(_Bool, int64_t, &slo, &shi); }
  else if (type == ATOM_int8)   { MINMAX(int8_t, int64_t, &slo, &shi); }
  else if (type == ATOM_int16)  { MINMAX(int16_t, int64_t, &slo, &shi); }
  else if (type == ATOM_int32)  { MINMAX(int32_t, int64_t, &slo, &shi); }
  else if (type == ATOM_int64)  { MINMAX(int64_t, int64_t, &slo, &shi); }
  else if (type == ATOM_uint8)  { MINMAX(uint8_t, uint64_t, &ulo, &uhi); goto unsigned_result; }
  else if (type == ATOM_uint16) { MINMAX(uint16_t, uint64_t, &ulo, &uhi); goto unsigned_result; }
  else if (type == ATOM_uint32) { MINMAX(uint32_t, uint64_t, &ulo, &uhi); goto unsigned_result; }
  else if (type == ATOM_uint64) { MINMAX(uint64_t, uint64_t, &ulo, &uhi); goto unsigned_result; }
  else
  {
    return PL_domain_error("integer_buffer_type", type_t);
  }
  return PL_unify_int64(min_t, slo) && PL_unify_int64(max_t, shi);
unsigned_result:
  return PL_unify_uint64(min_t, ulo) && PL_unify_uint64(max_t, uhi);
}

// The first Bytes bytes of one buffer copied into another.
static foreign_t c_buffer_copy(term_t from_t, term_t to_t, term_t bytes_t)
{
  void *from, *to;
  size_t from_size, to_size, bytes;
  PL_blob_t *type;

  if (!PL_get_size_ex(bytes_t, &bytes))
  {
    return FALSE;
  }
  if (!PL_get_blob(from_t, &from, &from_size, &type) || type != &buffer_blob)
  {
    return PL_type_error("buffer", from_t);
  }
  if (!PL_get_blob(to_t, &to, &to_size, &type) || type != &buffer_blob)
  {
    return PL_type_error("buffer", to_t);
  }
  if (bytes > from_size || bytes > to_size)
  {
    return PL_domain_error("buffer_bytes", bytes_t);
  }
  memcpy(to, from, bytes);
  return TRUE;
}

// element(type, buffer, i): the ith element of a buffer of any type, as a double or an int64.
static int element_double(atom_t type, const void *b, size_t i, double *v)
{
  if (type == ATOM_float16)      *v = ((const _Float16 *)b)[i];
  else if (type == ATOM_float32) *v = ((const float *)b)[i];
  else if (type == ATOM_float64) *v = ((const double *)b)[i];
  else if (type == ATOM_bfloat16) *v = bfloat16_double(((const uint16_t *)b)[i]);
  else if (type == ATOM_float8_e4m3) *v = float8_e4m3_double(((const uint8_t *)b)[i]);
  else if (type == ATOM_bool)    *v = ((const _Bool *)b)[i];
  else if (type == ATOM_int8)    *v = ((const int8_t *)b)[i];
  else if (type == ATOM_int16)   *v = ((const int16_t *)b)[i];
  else if (type == ATOM_int32)   *v = ((const int32_t *)b)[i];
  else if (type == ATOM_int64)   *v = (double)((const int64_t *)b)[i];
  else if (type == ATOM_uint8)   *v = ((const uint8_t *)b)[i];
  else if (type == ATOM_uint16)  *v = ((const uint16_t *)b)[i];
  else if (type == ATOM_uint32)  *v = ((const uint32_t *)b)[i];
  else if (type == ATOM_uint64)  *v = (double)((const uint64_t *)b)[i];
  else return FALSE;
  return TRUE;
}

// The ith integer element as an int32; fails out of range or for a floating type.
static int element_int32(atom_t type, const void *b, size_t i, int32_t *v)
{
  int64_t x;
  if (type == ATOM_bool)        x = ((const _Bool *)b)[i];
  else if (type == ATOM_int8)   x = ((const int8_t *)b)[i];
  else if (type == ATOM_int16)  x = ((const int16_t *)b)[i];
  else if (type == ATOM_int32)  x = ((const int32_t *)b)[i];
  else if (type == ATOM_int64)  x = ((const int64_t *)b)[i];
  else if (type == ATOM_uint8)  x = ((const uint8_t *)b)[i];
  else if (type == ATOM_uint16) x = ((const uint16_t *)b)[i];
  else if (type == ATOM_uint32) x = ((const uint32_t *)b)[i];
  else if (type == ATOM_uint64)
  {
    uint64_t u = ((const uint64_t *)b)[i];
    if (u > INT32_MAX) return FALSE;
    x = (int64_t)u;
  }
  else return FALSE;
  if (x < INT32_MIN || x > INT32_MAX) return FALSE;
  *v = (int32_t)x;
  return TRUE;
}

// A new buffer of N elements of float32 or int32, converted from a buffer of any type: floats
// round to float32, integers must fit int32.
static foreign_t c_buffer_convert(term_t from_t, term_t from_type_t, term_t n_t, term_t to_type_t, term_t to_t)
{
  atom_t from_type, to_type;
  size_t n, size, from_size;
  void *from;
  PL_blob_t *blob_type;

  if (!PL_get_atom_ex(from_type_t, &from_type) || !PL_get_atom_ex(to_type_t, &to_type)
      || !PL_get_size_ex(n_t, &n))
  {
    return FALSE;
  }
  if (!PL_get_blob(from_t, &from, &size, &blob_type) || blob_type != &buffer_blob)
  {
    return PL_type_error("buffer", from_t);
  }
  if (!atom_size(from_type, &from_size))
  {
    return PL_domain_error("buffer_type", from_type_t);
  }
  if (to_type != ATOM_float32 && to_type != ATOM_int32)
  {
    return PL_domain_error("float32_or_int32", to_type_t);
  }
  if (n > size / from_size)
  {
    return PL_domain_error("buffer_elements", n_t);
  }
  void *to = malloc(n ? n * 4 : 1);
  if (!to)
  {
    return PL_resource_error("memory");
  }
  for (size_t i = 0; i < n; i++)
  {
    if (to_type == ATOM_float32)
    {
      double d;
      if (!element_double(from_type, from, i, &d)) { free(to); return PL_domain_error("buffer_type", from_type_t); }
      ((float *)to)[i] = (float)d;
    }
    else if (!element_int32(from_type, from, i, &((int32_t *)to)[i]))
    {
      free(to);
      return PL_domain_error("int32", from_t);
    }
  }
  if (PL_unify_blob(to_t, to, n * 4, &buffer_blob))
  {
    return TRUE;
  }
  free(to);
  return FALSE;
}

install_t install_buffer(void)
{
  install_types();
  PL_register_foreign("c_buffer_alloc", 3, c_buffer_alloc, 0);
  PL_register_foreign("c_buffer_size", 2, c_buffer_size, 0);
  PL_register_foreign("c_buffer_free", 1, c_buffer_free, 0);
  PL_register_foreign("c_buffer_load", 4, c_buffer_load, 0);
  PL_register_foreign("c_buffer_set", 4, c_buffer_set, 0);
  PL_register_foreign("c_buffer_type_size", 2, c_buffer_type_size, 0);
  PL_register_foreign("c_buffer_from_compound", 5, c_buffer_from_compound, 0);
  PL_register_foreign("c_buffer_to_compound", 6, c_buffer_to_compound, 0);
  PL_register_foreign("c_buffer_pointer", 3, c_buffer_pointer, 0);
  PL_register_foreign("c_buffer_write", 3, c_buffer_write, 0);
  PL_register_foreign("c_buffer_read", 3, c_buffer_read, 0);
  PL_register_foreign("c_buffer_minmax", 5, c_buffer_minmax, 0);
  PL_register_foreign("c_buffer_copy", 3, c_buffer_copy, 0);
  PL_register_foreign("c_buffer_convert", 5, c_buffer_convert, 0);
}
