// Photoyam's thin C ABI over LibRaw (LGPL-2.1 / CDDL-1.0), compiled together
// with LibRaw into libraw.wasm by build.sh (beside this file).
//
// One RAW at a time (the worker that hosts this module decodes a single file and
// is terminated afterwards). JS owns the input buffer (malloc'd in the wasm heap)
// and keeps it alive until rw_close(). Numbers are reported through a small
// double array (rw_info) so the JS side needs no struct layout knowledge.
//
// Output contract (rw_process): imgdata.image is left as height x width x 4
// unsigned shorts, UNFLIPPED, LINEAR (gamma 1/1), camera colour space (or sRGB
// primaries for sensors without a usable matrix), white balanced with the
// camera's multipliers normalised so the LARGEST is 1 (highlight mode 1 keeps
// every channel's headroom: nothing clips before the JS develop step).
#include <emscripten/emscripten.h>
#include <stdlib.h>
#include <string.h>
#include "libraw/libraw.h"

EM_JS(void, rw_js_progress, (int stage, int iter, int expected), {
  if (Module.onRawProgress) Module.onRawProgress(stage, iter, expected);
});

static LibRaw *R = nullptr;
static double INFO[96];
static char MAKE[96];
static char MODEL[96];

static int progress_cb(void *, enum LibRaw_progress p, int iter, int expected) {
  rw_js_progress((int)p, iter, expected);
  return 0; // never cancel: the worker is terminated instead
}

// INFO layout (keep in sync with src/ui/io/raw/raw-decode.worker.ts):
//  0 raw_width   1 raw_height   2 width   3 height   4 flip   5 colors
//  6 filters!=0  7 xtrans       8 maximum 9 black   10 iso   11 shutter
// 12 aperture   13 focal_len   14 timestamp
// 16..19 cam_mul[4]  20..23 pre_mul[4]  24..35 rgb_cam[3][4]
// 40 out width  41 out height  42 out flip  43 out colors
// 44..47 applied (normalised) multipliers   48 output colour (0 raw / 1 sRGB)
// 49 half size  50 thumb width  51 thumb height  52 thumb format
static void fill_open_info() {
  libraw_data_t &d = R->imgdata;
  INFO[0] = d.sizes.raw_width;
  INFO[1] = d.sizes.raw_height;
  INFO[2] = d.sizes.width;
  INFO[3] = d.sizes.height;
  INFO[4] = d.sizes.flip;
  INFO[5] = d.idata.colors;
  INFO[6] = d.idata.filters != 0;
  INFO[7] = d.idata.filters == 9;
  INFO[8] = d.color.maximum;
  INFO[9] = d.color.black;
  INFO[10] = d.other.iso_speed;
  INFO[11] = d.other.shutter;
  INFO[12] = d.other.aperture;
  INFO[13] = d.other.focal_len;
  INFO[14] = (double)d.other.timestamp;
  for (int i = 0; i < 4; i++) INFO[16 + i] = d.color.cam_mul[i];
  for (int i = 0; i < 4; i++) INFO[20 + i] = d.color.pre_mul[i];
  for (int r = 0; r < 3; r++)
    for (int c = 0; c < 4; c++) INFO[24 + r * 4 + c] = d.color.rgb_cam[r][c];
  INFO[50] = d.thumbnail.twidth;
  INFO[51] = d.thumbnail.theight;
  INFO[52] = d.thumbnail.tformat;
  strncpy(MAKE, d.idata.make, sizeof MAKE - 1);
  strncpy(MODEL, d.idata.model, sizeof MODEL - 1);
}

extern "C" {

EMSCRIPTEN_KEEPALIVE double *rw_info() { return INFO; }
EMSCRIPTEN_KEEPALIVE const char *rw_make() { return MAKE; }
EMSCRIPTEN_KEEPALIVE const char *rw_model() { return MODEL; }
EMSCRIPTEN_KEEPALIVE const char *rw_version() { return LibRaw::version(); }
EMSCRIPTEN_KEEPALIVE const char *rw_strerror(int code) { return libraw_strerror(code); }

EMSCRIPTEN_KEEPALIVE void rw_close() {
  if (R) {
    R->recycle();
    delete R;
    R = nullptr;
  }
}

// Identify only (cheap): sizes, colour data, maker/model. 0 on success.
EMSCRIPTEN_KEEPALIVE int rw_open(void *buf, int len) {
  rw_close();
  memset(INFO, 0, sizeof INFO);
  MAKE[0] = MODEL[0] = 0;
  R = new LibRaw(0);
  R->set_progress_handler(progress_cb, nullptr);
  int ret = R->open_buffer(buf, (size_t)len);
  if (ret != LIBRAW_SUCCESS) return ret;
  fill_open_info();
  return 0;
}

// Unpack + process into linear, white-balanced (camera multipliers) data.
// quality: LibRaw user_qual (0 linear, 1 VNG, 2 PPG, 3 AHD, 11 DHT, 12 AAHD).
EMSCRIPTEN_KEEPALIVE int rw_process(int halfSize, int quality) {
  if (!R) return LIBRAW_OUT_OF_ORDER_CALL;
  libraw_output_params_t &o = R->imgdata.params;
  o.half_size = halfSize ? 1 : 0;
  o.use_camera_wb = 1;
  o.use_auto_wb = 0;
  o.highlight = 1;          // unclip: keep headroom, the JS side reconstructs
  o.no_auto_bright = 1;
  o.gamm[0] = 1.0;          // linear output
  o.gamm[1] = 1.0;
  o.output_bps = 16;
  o.user_qual = quality;
  o.use_fuji_rotate = 1;
  // Bayer RGB(G) sensors with a colour matrix stay in camera space so the JS
  // develop step can re-white-balance before the matrix. Anything else (no
  // matrix, 4-colour CMYG, Foveon …) is converted to sRGB primaries here.
  libraw_data_t &d = R->imgdata;
  bool hasMatrix = d.color.rgb_cam[0][0] != 0 && !(d.color.rgb_cam[0][0] == 1 && d.color.rgb_cam[1][1] == 1 &&
                                                  d.color.rgb_cam[0][1] == 0 && d.color.rgb_cam[1][0] == 0);
  o.output_color = (d.idata.colors == 3 && hasMatrix) ? 0 : 1;

  int ret = R->unpack();
  if (ret != LIBRAW_SUCCESS) return ret;
  ret = R->dcraw_process();
  if (ret != LIBRAW_SUCCESS) return ret;
  // The file bytes are no longer needed (JS frees them after this returns).
  R->recycle_datastream();

  INFO[40] = d.sizes.width;
  INFO[41] = d.sizes.height;
  INFO[42] = d.sizes.flip;
  INFO[43] = d.idata.colors;
  for (int i = 0; i < 4; i++) INFO[44 + i] = d.color.pre_mul[i];
  INFO[48] = o.output_color;
  INFO[49] = o.half_size;
  return 0;
}

// height x width x 4 unsigned shorts (valid after rw_process).
EMSCRIPTEN_KEEPALIVE unsigned short *rw_image() { return R ? (unsigned short *)R->imgdata.image : nullptr; }

} // extern "C"
