/* PlayAgain's Nintendo 64 shim: the N64Wasm tree (mupen64plus-core on the
 * cached interpreter, Glide64 or Rice on WebGL2, RSP-HLE) behind a flat C ABI
 * for the browser. It replaces N64Wasm's mymain.cpp: no SDL, no keyboard or
 * joystick polling, no fonts, no menu, no main loop. The host owns all of that.
 *
 * One pa_run_frame() is one vertical interrupt (NO_LIBCO: retro_run() steps
 * the interpreter until the VI handler calls retro_return()). The picture is
 * drawn inside that call, by Glide64 through glsm onto framebuffer 0 of the
 * WebGL2 context this shim creates on the module's canvas in pa_init(). The
 * frame's sound lands in the core's own 44.1 kHz ring (pa_audio_ring).
 *
 * The clock the game's real-time clock reads is a session clock: whatever
 * pa_set_clock() said, advanced by the frames run since. Never the host's.
 */
#include <errno.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include <emscripten.h>
#include <emscripten/html5.h>
#include <libretro.h>

#include "neil.h"
#include "neil_controller.h"
#include "libretro_memory.h"
#include "api/m64p_types.h"
#include "api/m64p_plugin.h"
#include "main/main.h"
#include "main/device.h"
#include "main/savestates.h"
#include "plugin/plugin.h"
#include "r4300/r4300.h"
#include "r4300/cp0.h"
#include "r4300/cp1.h"
#include "r4300/r4300_core.h"

#define EXPORT __attribute__((visibility("default")))

/* The m64p state is a fixed layout plus an event queue of at most 1 KiB;
 * N64Wasm sizes its buffer so, and savestates_save_m64p (patched) returns the
 * bytes it wrote. */
#define STATE_MAX (16788288 + 1024)
#define AUDIO_RING_SAMPLES 64000 /* int16, interleaved stereo, 44100 Hz (audio_backend_libretro.c) */
#define AUDIO_RATE 44100
#define SCREEN_W 640 /* the viewport glsm binds every frame */
#define SCREEN_H 480

/* ---- what the tree expects mymain.cpp to define -------------------------- */
struct NeilButtons neilbuttons[NEILNUMCONTROLLERS];
struct NeilCheats neilCheats[256];
int neilCheatsLength = 0;
bool forceAngry = false;  /* Angrylion is not built */
bool ricePlugin = false;  /* Glide64 unless pa_set_renderer(1) before the ROM loads */
bool doubleSpeed = false;
bool vbuf_use_vbo = false;
bool pilotwingsFix = false;
int triangleCount = 0;
int globalTriangleTrigger = 0;
int angryVerticalResolution = 240;
int mouseRange = 40; /* the pad plugin divides by it; mouse mode is never on */
void neil_toast_message(char *message) { (void)message; } /* N64Wasm's on-screen toast: no overlay here */

/* ---- no files ---------------------------------------------------------------
 * Built with -sFILESYSTEM=0, Emscripten's stubs for these two syscalls return
 * nothing, which C reads as success: every access() would find a file and
 * every fopen() would hand back fd 0. The core has no files, so say so: each
 * path the tree tries (Rice's ini, a 64DD IPL, /proc/cpuinfo) finds nothing. */
int __syscall_openat(int dirfd, const char *path, int flags, ...)
{
    (void)dirfd; (void)path; (void)flags;
    return -ENOENT;
}
int __syscall_faccessat(int dirfd, const char *path, int amode, int flags)
{
    (void)dirfd; (void)path; (void)amode; (void)flags;
    return -ENOENT;
}

/* ---- what the tree defines without a header ------------------------------ */
extern int pad_present[4];                       /* libretronew.c: read at input plugin start */
extern uint32_t screen_width, screen_height;     /* libretronew.c */
extern struct retro_hw_render_callback hw_render; /* glsm.c */
int neilGetSoundBufferResampledAddress(void);    /* audio_backend_libretro.c */
int neilGetAudioWritePosition(void);

/* ---- state ---------------------------------------------------------------- */
static EMSCRIPTEN_WEBGL_CONTEXT_HANDLE gl_ctx;
static bool loaded;   /* pa_load_rom succeeded */
static bool running;  /* the first frame ran: the device exists, states and the digest are valid */
static int64_t clock_base;      /* unix seconds the host set */
static uint64_t clock_frames;   /* frames run since */
static struct tm clock_tm;

static int frame_rate_hz(void)
{
    return loaded ? getRegionTiming() : 60; /* 50 for PAL, else 60 */
}

/* The core's RTC hook (si/af_rtc.c), replacing plugin/get_time_using_C_localtime.c:
 * UTC, from the session clock, never the host's time or zone. */
const struct tm *get_time_using_C_localtime(void *user_data)
{
    (void)user_data;
    time_t t = (time_t)(clock_base + (int64_t)(clock_frames / (uint64_t)frame_rate_hz()));
    gmtime_r(&t, &clock_tm);
    return &clock_tm;
}

/* The canvas is Module.canvas (an HTMLCanvasElement on a page, an
 * OffscreenCanvas in a worker): Emscripten 6 resolves "#canvas" through
 * specialHTMLTargets, then document.querySelector, and a worker has no
 * document. */
EM_JS(int, pa_bind_canvas, (void), {
    if (!Module['canvas']) return 0;
    specialHTMLTargets['#canvas'] = Module['canvas'];
    return 1;
});

static uintptr_t current_framebuffer(void)
{
    return 0; /* the canvas; an FBO once present() is split from step() */
}

/* ---- lifecycle ----------------------------------------------------------- */

/* Creates the WebGL2 context on the module's canvas (Module.canvas, "#canvas")
 * and initialises the libretro side. width/height size the canvas; glsm's
 * viewport is 640x480 from its bottom-left corner, so pass 640, 480. 0 on
 * success, -1/-2 when WebGL2 is unavailable, -3 without Module.canvas. */
EXPORT int pa_init(int width, int height)
{
    if (gl_ctx) return 0;
    if (!pa_bind_canvas()) return -3;
    EmscriptenWebGLContextAttributes attrs;
    emscripten_webgl_init_context_attributes(&attrs);
    attrs.majorVersion = 2;
    attrs.minorVersion = 0;
    attrs.alpha = EM_FALSE;
    attrs.depth = EM_TRUE;
    attrs.stencil = EM_FALSE;
    attrs.antialias = EM_FALSE;
    attrs.premultipliedAlpha = EM_FALSE;
    attrs.preserveDrawingBuffer = EM_TRUE; /* a frame without a swap keeps the last picture */
    attrs.powerPreference = EM_WEBGL_POWER_PREFERENCE_HIGH_PERFORMANCE;
    attrs.enableExtensionsByDefault = EM_TRUE;
    emscripten_set_canvas_element_size("#canvas", width > 0 ? width : SCREEN_W, height > 0 ? height : SCREEN_H);
    gl_ctx = emscripten_webgl_create_context("#canvas", &attrs);
    if (gl_ctx <= 0) { gl_ctx = 0; return -1; }
    if (emscripten_webgl_make_context_current(gl_ctx) != EMSCRIPTEN_RESULT_SUCCESS) return -2;
    hw_render.get_current_framebuffer = current_framebuffer;
    retro_init();
    return 0;
}

/* 0: Glide64 (the default), 1: Rice. Only before pa_load_rom. */
EXPORT void pa_set_renderer(int rice)
{
    if (!loaded) ricePlugin = rice != 0;
}

/* The cartridge image in any byte order (.z64, .v64, .n64); the core keeps
 * its own copy. 0 on success. */
EXPORT int pa_load_rom(const uint8_t *data, int len)
{
    if (!gl_ctx || loaded || !data || len < 4096) return -1;
    if (!retro_load_game_new((uint8_t *)data, len, false, false, false)) return -2;
    loaded = true;
    return 0;
}

/* One VI. Returns 1 when the game swapped a new picture onto the canvas
 * during this frame, 0 when it did not, -1 when the core has stopped. */
EXPORT int pa_run_frame(void)
{
    if (!loaded || stop) return -1;
    resetReadyToSwap();
    retro_run();
    running = true;
    clock_frames++;
    if (stop) return -1;
    return getReadyToSwap() ? 1 : 0;
}

/* A hard reset: the console powers on again at the first interrupt of the next frame. */
EXPORT void pa_reset(void)
{
    if (running) retro_reset_new();
}

EXPORT void pa_set_clock(double unix_seconds)
{
    clock_base = (int64_t)unix_seconds;
    clock_frames = 0;
}

EXPORT int pa_frame_rate(void) { return frame_rate_hz(); }
EXPORT int pa_screen_width(void) { return (int)screen_width; }
EXPORT int pa_screen_height(void) { return (int)screen_height; }

/* ---- pads ------------------------------------------------------------------
 * PlayAgain's 16-bit mask (BUTTON_BIT order): up=0 down=1 left=2 right=3 a=4
 * b=5 x=6 y=7 start=8 select=9 l1=10 r1=11 l2=12 r2=13 (l3/r3 unused). The
 * N64 pad per the design (§8): a=A b=B x=C-up y=C-left l1=L r1=R l2=Z
 * r2=C-down select=C-right; the d-pad is the d-pad, start is Start. */
EXPORT void pa_set_pad(int port, int mask)
{
    if (port < 0 || port >= NEILNUMCONTROLLERS) return;
    struct NeilButtons *b = &neilbuttons[port];
    b->upKey = (mask >> 0) & 1;
    b->downKey = (mask >> 1) & 1;
    b->leftKey = (mask >> 2) & 1;
    b->rightKey = (mask >> 3) & 1;
    b->aKey = (mask >> 4) & 1;
    b->bKey = (mask >> 5) & 1;
    b->cbUp = (mask >> 6) & 1;
    b->cbLeft = (mask >> 7) & 1;
    b->startKey = (mask >> 8) & 1;
    b->cbRight = (mask >> 9) & 1;
    b->lKey = (mask >> 10) & 1;
    b->rKey = (mask >> 11) & 1;
    b->zKey = (mask >> 12) & 1;
    b->cbDown = (mask >> 13) & 1;
    b->selectKey = 0; /* the N64 has none */
}

/* The analogue stick, -32768..32767 on each axis, y positive downwards (the
 * SDL convention mymain used; the pad plugin folds it into the N64's +-80). */
EXPORT void pa_set_axes(int port, int x, int y)
{
    if (port < 0 || port >= NEILNUMCONTROLLERS) return;
    if (x < -32767) x = -32767; else if (x > 32767) x = 32767;
    if (y < -32767) y = -32767; else if (y > 32767) y = 32767;
    neilbuttons[port].axis0 = x;
    neilbuttons[port].axis1 = y;
}

/* Whether a controller is plugged into the port (all four are at boot; a game
 * like F-Zero only sees pads present from power-on). */
EXPORT void pa_set_present(int port, int on)
{
    if (port < 0 || port >= 4) return;
    pad_present[port] = on ? 1 : 0;
    Controls[port].Present = on ? 1 : 0;
}

/* ---- sound -------------------------------------------------------------------
 * The core resamples every AI DMA to 44.1 kHz into a ring of 64000 int16
 * (interleaved L R), as N64Wasm's page reads it: the reader keeps its own
 * position and consumes up to the write position, wrapping at 64000. */
EXPORT int16_t *pa_audio_ring(void) { return (int16_t *)(intptr_t)neilGetSoundBufferResampledAddress(); }
EXPORT int pa_audio_ring_len(void) { return AUDIO_RING_SAMPLES; }
EXPORT int pa_audio_write_pos(void) { return neilGetAudioWritePosition(); }
EXPORT int pa_audio_rate(void) { return AUDIO_RATE; }

/* ---- save states ----------------------------------------------------------------
 * mupen64plus's own m64p state, as it writes it, then what lives outside it:
 * the game's save memory (pa_save_ram_ptr's bytes) and the session clock, then
 * a footer. The m64p bytes come first and unchanged, so a bare m64p state from
 * another frontend still loads (it keeps the current save memory and clock). */
#define SAVE_RAM_SIZE ((int)offsetof(save_memory_data, disk))
#define PA_STATE_MAGIC 0x34364150u /* "PA64" */
#define PA_STATE_VERSION 1u

typedef struct {
    uint32_t magic;
    uint32_t version;
    int64_t clock_base;
    uint64_t clock_frames;
    uint32_t m64p_size;
    uint32_t save_ram_size;
} pa_state_footer_t; /* 32 bytes, little-endian */

EXPORT int pa_state_size(void) { return STATE_MAX + SAVE_RAM_SIZE + (int)sizeof(pa_state_footer_t); }

/* Writes the state into out (pa_state_size() bytes at most); returns the bytes written. */
EXPORT int pa_save_state(uint8_t *out)
{
    if (!running || !out) return -1;
    int n = savestates_save_m64p(out, STATE_MAX);
    if (n <= 0) return -2;
    memcpy(out + n, &saved_memory, SAVE_RAM_SIZE);
    pa_state_footer_t f = { PA_STATE_MAGIC, PA_STATE_VERSION, clock_base, clock_frames, (uint32_t)n, (uint32_t)SAVE_RAM_SIZE };
    memcpy(out + n + SAVE_RAM_SIZE, &f, sizeof f);
    return n + SAVE_RAM_SIZE + (int)sizeof f;
}

/* Loads a state from pa_save_state (or a bare m64p state). The cartridge must
 * be the one the state was taken on (mupen64plus checks its MD5). A load
 * before the first frame runs that frame first: the console must exist. */
EXPORT int pa_load_state(const uint8_t *in, int len)
{
    if (!loaded || !in || len <= 0) return -1;
    if (!running && pa_run_frame() < 0) return -1;
    pa_state_footer_t f;
    int m64p_size = len;
    bool ours = false;
    if (len > (int)sizeof f) {
        memcpy(&f, in + len - sizeof f, sizeof f);
        ours = f.magic == PA_STATE_MAGIC && f.version == PA_STATE_VERSION && f.save_ram_size == (uint32_t)SAVE_RAM_SIZE &&
            (uint64_t)f.m64p_size + f.save_ram_size + sizeof f == (uint64_t)len;
        if (ours) m64p_size = (int)f.m64p_size;
    }
    if (!savestates_load_m64p(in, (size_t)m64p_size)) return -2;
    if (ours) {
        memcpy(&saved_memory, in + m64p_size, SAVE_RAM_SIZE);
        clock_base = f.clock_base;
        clock_frames = f.clock_frames;
    }
    return 0;
}

/* ---- the game's own save --------------------------------------------------------
 * saved_memory, as the core keeps it (libretro_memory.h): eeprom 0x800 at 0,
 * then mempack[4] of 0x8000 at 0x800, sram 0x8000 at 0x20800, flashram
 * 0x20000 at 0x28800; 0x48800 bytes in all (the 64DD disk after it is not
 * exported). Write it after pa_load_rom (which formats it) and before the game
 * reads it; the core reads and writes it in place. */
EXPORT uint8_t *pa_save_ram_ptr(void) { return (uint8_t *)&saved_memory; }
EXPORT int pa_save_ram_size(void) { return SAVE_RAM_SIZE; }

/* The core counts 30 frames from the game's last EEPROM, SRAM, FlashRAM or
 * Controller Pak write and then calls this (patched libretronew.c), where
 * N64Wasm wrote game.savememory. */
static int save_ram_settled;
void pa_save_ram_settled(void) { save_ram_settled = 1; }

/* 1 once a save has settled since the last call, then 0 until the next. */
EXPORT int pa_save_ram_dirty(void)
{
    int dirty = save_ram_settled;
    save_ram_settled = 0;
    return dirty;
}

/* RDRAM, 8 MiB, as the core keeps it: one host uint32 per guest word (word
 * order native, so HEAPU32[(ptr + a) >> 2] is the guest's word at a). Read only. */
EXPORT const uint32_t *pa_rdram_ptr(void) { return g_rdram; }

/* ---- Netplay: the GPU never writes RDRAM ------------------------------------------
 * Glide64 can copy the frame it drew back into RDRAM (CopyFrameBuffer, for
 * games that read their own picture). Those are the GPU's pixels, which
 * differ between two homes' GPUs. The worker turns this off for a lockstep
 * session (patched Framebuffer_glide64.c returns at once); solo play keeps it. */
int pa_gpu_readback = 1;

EXPORT void pa_set_gpu_readback(int on) { pa_gpu_readback = on != 0; }

/* ---- digest -------------------------------------------------------------------------
 * FNV-1a over the CPU (CP0's 32 registers, the PC, the 32 GPRs, hi and lo, CP1's
 * 32 FPRs and FCR31) and PIF RAM, then XXH64 of the whole of RDRAM (8 MiB). The
 * TLB lookup tables and the RSP's memory follow from those and are left out. */
static uint32_t fnv(uint32_t h, const void *p, size_t n)
{
    const uint8_t *b = (const uint8_t *)p;
    while (n--) { h ^= *b++; h *= 16777619u; }
    return h;
}

#define XXH_P1 UINT64_C(0x9E3779B185EBCA87)
#define XXH_P2 UINT64_C(0xC2B2AE3D27D4EB4F)
#define XXH_P3 UINT64_C(0x165667B19E3779F9)
#define XXH_P4 UINT64_C(0x85EBCA77C2B2AE63)
#define XXH_P5 UINT64_C(0x27D4EB2F165667C5)

static inline uint64_t rotl64(uint64_t x, int r) { return (x << r) | (x >> (64 - r)); }
static inline uint64_t xxh_round(uint64_t acc, uint64_t lane) { return rotl64(acc + lane * XXH_P2, 31) * XXH_P1; }
static inline uint64_t xxh_merge(uint64_t acc, uint64_t v) { return (acc ^ xxh_round(0, v)) * XXH_P1 + XXH_P4; }

/* XXH64 (seed 0) of n bytes, n a multiple of 32: the stripes, then the merge
 * and the avalanche. Little-endian loads: wasm is little-endian everywhere. */
static uint64_t xxh64_stripes(const uint8_t *p, size_t n)
{
    uint64_t v1 = XXH_P1 + XXH_P2, v2 = XXH_P2, v3 = 0, v4 = UINT64_C(0) - XXH_P1;
    for (const uint8_t *end = p + n; p < end; p += 32) {
        uint64_t l[4];
        memcpy(l, p, sizeof l);
        v1 = xxh_round(v1, l[0]);
        v2 = xxh_round(v2, l[1]);
        v3 = xxh_round(v3, l[2]);
        v4 = xxh_round(v4, l[3]);
    }
    uint64_t h = rotl64(v1, 1) + rotl64(v2, 7) + rotl64(v3, 12) + rotl64(v4, 18);
    h = xxh_merge(xxh_merge(xxh_merge(xxh_merge(h, v1), v2), v3), v4);
    h += (uint64_t)n;
    h ^= h >> 33; h *= XXH_P2;
    h ^= h >> 29; h *= XXH_P3;
    h ^= h >> 32;
    return h;
}

EXPORT uint32_t pa_digest(void)
{
    if (!running) return 0;
    uint32_t h = 2166136261u;
    h = fnv(h, r4300_cp0_regs(), CP0_REGS_COUNT * sizeof(uint32_t));
    h = fnv(h, r4300_pc(), sizeof(uint32_t));
    h = fnv(h, r4300_regs(), 32 * sizeof(int64_t));
    h = fnv(h, r4300_mult_hi(), sizeof(int64_t));
    h = fnv(h, r4300_mult_lo(), sizeof(int64_t));
    h = fnv(h, r4300_cp1_regs(), 32 * sizeof(int64_t));
    h = fnv(h, r4300_cp1_fcr31(), sizeof(uint32_t));
    h = fnv(h, g_dev.si.pif.ram, PIF_RAM_SIZE);
    const uint64_t rdram = xxh64_stripes((const uint8_t *)g_rdram, RDRAM_MAX_SIZE);
    return fnv(h, &rdram, sizeof rdram);
}
