/* PlayAgain's SameBoy shim: one or two Game Boy consoles behind a flat C ABI
 * for the browser. Console 0 is the one a player sees and hears in solo play.
 * In a link session console 1 runs beside it, joined by an emulated cable:
 * the pair is stepped together one frame per call (see "the pair" below).
 *
 * Every time() SameBoy makes goes to pa_time() (patime.h is force-included),
 * so the in-game clock is whatever this shim says it is:
 *   - wall mode: the page's clock, set every tick (solo play, as on real
 *     hardware the cartridge clock keeps real time);
 *   - session mode: T0 plus console 0's emulated time (link sessions, where
 *     both homes must see the same clock).
 */
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include "Core/gb.h"
#include "Core/random.h"

#define EXPORT __attribute__((visibility("default")))
#define CONSOLES 2
#define MAX_W 256
#define MAX_H 224
#define AUDIO_RING 16384 /* stereo frames per console */
#define TICKS_PER_SECOND 8388608ull /* SameBoy counts 8 MHz ticks */

extern const unsigned char pa_dmg_boot[];
extern const unsigned int pa_dmg_boot_len;
extern const unsigned char pa_cgb_boot[];
extern const unsigned int pa_cgb_boot_len;
extern const unsigned char pa_sgb_boot[];
extern const unsigned int pa_sgb_boot_len;

typedef struct {
    GB_gameboy_t *gb;
    uint32_t *fb;
    bool vblank;
    bool muted; /* while the boot ROM runs unseen: samples are dropped */
    int16_t *ring; /* AUDIO_RING * 2 */
    uint32_t ring_read, ring_write; /* in frames, wrap at AUDIO_RING */
    double rumble;
} console_t;

static console_t C[CONSOLES];

/* ---- the pair's own state (link sessions) -------------------------------
 * What lives outside the two SameBoy states, written at the front of every
 * pair snapshot. Keep it plain data. */
#define PAIR_MAGIC 0x52494150u /* 'PAIR' */
#define PAIR_VERSION 2
#define FRAME_TICKS 140448 /* one frame in 8 MHz ticks */
#define HALF_FRAME 70224
#define GUARD_NEAR 35112 /* a quarter frame */

typedef struct {
    uint32_t magic;
    uint32_t version;
    int64_t offset;        /* console 0's ticks minus console 1's, carried across frames */
    uint64_t frame;        /* pair frames run */
    uint64_t timeline;     /* console 0's ticks since the pair powered on */
    int64_t session_t0;    /* the session clock: T0 ... */
    uint64_t session_ticks;/* ... plus console 0's emulated time */
    uint8_t bit_out[2];    /* each console's latched outgoing serial bit */
    uint8_t linked;
    uint8_t pad[5];
    uint32_t state_size[2];
} pair_header_t;

static struct {
    bool active;
    pair_header_t h;
    int presented;            /* the console this home shows and hears */
    uint32_t *presented_fb;   /* its frame, copied at its own vblank */
    int64_t vbl[2];           /* shared-timeline time of each console's last normal vblank */
    bool vbl_seen[2];
    double phase;             /* (v1 - v0) mod one frame, measured last frame */
    uint8_t *scratch;
    size_t scratch_size;
} PAIR = { .presented = -1 };
static int clock_mode; /* 0 wall, 1 session */
static double wall_seconds;
static int64_t session_t0;
static uint64_t session_ticks; /* console 0's emulated ticks since the session began */

/* ---- clock -------------------------------------------------------------- */
time_t pa_time(time_t *out)
{
    time_t t = clock_mode == 1
        ? (time_t)(session_t0 + (int64_t)(session_ticks / TICKS_PER_SECOND))
        : (time_t)wall_seconds;
    if (out) *out = t;
    return t;
}

EXPORT void pa_set_clock(int mode, double seconds)
{
    clock_mode = mode == 1 ? 1 : 0;
    if (clock_mode == 1) { session_t0 = (int64_t)seconds; session_ticks = 0; }
    else wall_seconds = seconds;
    for (int i = 0; i < CONSOLES; i++) {
        if (C[i].gb) GB_set_rtc_mode(C[i].gb, clock_mode == 1 ? GB_RTC_MODE_ACCURATE : GB_RTC_MODE_SYNC_TO_HOST);
    }
}

/* ---- callbacks ---------------------------------------------------------- */
static int index_of(GB_gameboy_t *gb) { return gb == C[1].gb ? 1 : 0; }

static void quiet_log(GB_gameboy_t *gb, const char *m, GB_log_attributes_t a) { (void)gb; (void)m; (void)a; }

static uint32_t rgba(GB_gameboy_t *gb, uint8_t r, uint8_t g, uint8_t b)
{
    (void)gb;
    return (uint32_t)r | ((uint32_t)g << 8) | ((uint32_t)b << 16) | 0xff000000u;
}

static void on_vblank(GB_gameboy_t *gb, GB_vblank_type_t type)
{
    int i = index_of(gb);
    C[i].vblank = true;
    if (!PAIR.active) return;
    /* Only real frames say where a console's frame starts; LCD-off vblanks are synthetic. */
    if (type == GB_VBLANK_TYPE_NORMAL_FRAME) {
        PAIR.vbl[i] = i == 0 ? (int64_t)PAIR.h.timeline : (int64_t)PAIR.h.timeline - PAIR.h.offset;
        PAIR.vbl_seen[i] = true;
    }
    /* Home B shows console 1, which may run on past its vblank before the pair
     * frame ends: copy the finished frame now, never a half-drawn one. */
    if (i == PAIR.presented && PAIR.presented_fb) {
        memcpy(PAIR.presented_fb, C[i].fb, (size_t)GB_get_screen_width(gb) * GB_get_screen_height(gb) * 4);
    }
}

static void on_sample(GB_gameboy_t *gb, GB_sample_t *sample)
{
    console_t *c = &C[index_of(gb)];
    if (c->muted) return;
    uint32_t next = (c->ring_write + 1) % AUDIO_RING;
    if (next == c->ring_read) c->ring_read = (c->ring_read + 1) % AUDIO_RING; /* full: drop the oldest */
    c->ring[c->ring_write * 2] = sample->left;
    c->ring[c->ring_write * 2 + 1] = sample->right;
    c->ring_write = next;
}

static void on_rumble(GB_gameboy_t *gb, double amplitude) { C[index_of(gb)].rumble = amplitude; }

/* pa_cgb_boot is SameBoy's fast CGB boot ROM (cgb_boot_fast.bin): no
 * animation, so less to run unseen at every load. */
static void boot_rom(GB_gameboy_t *gb, GB_boot_rom_t type)
{
    switch (type) {
        case GB_BOOT_ROM_CGB_0:
        case GB_BOOT_ROM_CGB:
        case GB_BOOT_ROM_CGB_E:
        case GB_BOOT_ROM_AGB_0:
        case GB_BOOT_ROM_AGB:
            GB_load_boot_rom_from_buffer(gb, pa_cgb_boot, pa_cgb_boot_len);
            return;
        case GB_BOOT_ROM_SGB:
        case GB_BOOT_ROM_SGB2:
            GB_load_boot_rom_from_buffer(gb, pa_sgb_boot, pa_sgb_boot_len);
            return;
        default:
            GB_load_boot_rom_from_buffer(gb, pa_dmg_boot, pa_dmg_boot_len);
            return;
    }
}

static bool is_sgb(int model) { return (model & ~0xff) == 0 && (model & GB_MODEL_SGB); }

/* ---- setup -------------------------------------------------------------- */
EXPORT int pa_init(int i, int model)
{
    if (i < 0 || i >= CONSOLES) return -1;
    console_t *c = &C[i];
    GB_random_set_enabled(false);
    if (c->gb) GB_free(c->gb);
    else {
        c->gb = GB_alloc();
        c->fb = calloc(MAX_W * MAX_H, 4);
        c->ring = calloc(AUDIO_RING * 2, sizeof(int16_t));
    }
    GB_init(c->gb, (GB_model_t)model);
    GB_set_log_callback(c->gb, quiet_log);
    GB_set_boot_rom_load_callback(c->gb, boot_rom);
    GB_set_rgb_encode_callback(c->gb, rgba);
    GB_set_vblank_callback(c->gb, on_vblank);
    GB_set_pixels_output(c->gb, c->fb);
    GB_set_palette(c->gb, &GB_PALETTE_GREY);
    GB_set_color_correction_mode(c->gb, GB_COLOR_CORRECTION_DISABLED);
    GB_set_border_mode(c->gb, is_sgb(model) ? GB_BORDER_SGB : GB_BORDER_NEVER);
    GB_set_rumble_mode(c->gb, GB_RUMBLE_CARTRIDGE_ONLY);
    GB_set_rumble_callback(c->gb, on_rumble);
    GB_set_rtc_mode(c->gb, clock_mode == 1 ? GB_RTC_MODE_ACCURATE : GB_RTC_MODE_SYNC_TO_HOST);
    /* No DC offset: an idle DAC would otherwise sit far above zero and pop on every pause. */
    GB_set_highpass_filter_mode(c->gb, GB_HIGHPASS_ACCURATE);
    /* The callback is never null: SameBoy calls it whenever a sample rate is set. */
    GB_apu_set_sample_callback(c->gb, on_sample);
    c->ring_read = c->ring_write = 0;
    c->rumble = 0;
    c->muted = false;
    return 0;
}

EXPORT int pa_model(int i) { return (int)GB_get_model(C[i].gb); }

/* What mGBA accepts as a Game Boy image: the logo's first bytes, or Sachen's. */
static bool has_logo(const uint8_t *rom)
{
    static const uint8_t nintendo[4] = {0xCE, 0xED, 0x66, 0x66};
    static const uint8_t sachen[4] = {0x7C, 0xE7, 0xC0, 0x00};
    return memcmp(rom + 0x104, nintendo, 4) == 0 || memcmp(rom + 0x104, sachen, 4) == 0;
}

EXPORT int pa_load_rom(int i, const uint8_t *rom, size_t len)
{
    if (len < 0x150 || !has_logo(rom)) return -1;
    GB_load_rom_from_buffer(C[i].gb, rom, len);
    GB_reset(C[i].gb);
    return 0;
}

EXPORT void pa_reset(int i)
{
    GB_reset(C[i].gb);
    C[i].ring_read = C[i].ring_write = 0;
}

static unsigned run_once(int i)
{
    unsigned t = GB_run(C[i].gb);
    if (i == 0 && clock_mode == 1) session_ticks += t;
    return t;
}

/* Run the boot ROM to its end unseen and unheard: the game starts at once,
 * as it did on mGBA (which skipped the BIOS). An SGB's intro animation is
 * ended first, as SameBoy's own GBS loader does. */
EXPORT void pa_skip_boot(int i)
{
    console_t *c = &C[i];
    GB_gameboy_t *gb = c->gb;
    if (gb->sgb) gb->sgb->intro_animation = GB_SGB_INTRO_ANIMATION_LENGTH;
    GB_set_rendering_disabled(gb, true);
    c->muted = true;
    /* The DMG boot ROM takes about 2.5 s; give up after 10 s of emulated time. */
    for (uint64_t ticks = 0; !gb->boot_rom_finished && ticks < 10 * TICKS_PER_SECOND;) ticks += run_once(i);
    c->muted = false;
    GB_set_rendering_disabled(gb, false);
    c->ring_read = c->ring_write = 0;
}

EXPORT void pa_set_keys(int i, uint32_t mask) { GB_set_key_mask(C[i].gb, (GB_key_mask_t)(mask & 0xff)); }

EXPORT uint32_t pa_run_frame(int i)
{
    C[i].vblank = false;
    uint32_t steps = 0;
    while (!C[i].vblank) { run_once(i); steps++; }
    return steps;
}

EXPORT uint32_t *pa_framebuffer(int i) { return C[i].fb; }
EXPORT int pa_screen_width(int i) { return (int)GB_get_screen_width(C[i].gb); }
EXPORT int pa_screen_height(int i) { return (int)GB_get_screen_height(C[i].gb); }
EXPORT double pa_frame_rate(int i) { return GB_get_usual_frame_rate(C[i].gb); }

/* ---- audio -------------------------------------------------------------- */
/* rate 0 turns sound off (SameBoy makes no samples without a rate). */
EXPORT void pa_set_audio(int i, unsigned rate)
{
    GB_set_sample_rate(C[i].gb, rate);
    C[i].ring_read = C[i].ring_write = 0;
}

EXPORT int pa_read_audio(int i, int16_t *dst, int max_frames)
{
    console_t *c = &C[i];
    int n = 0;
    while (n < max_frames && c->ring_read != c->ring_write) {
        dst[n * 2] = c->ring[c->ring_read * 2];
        dst[n * 2 + 1] = c->ring[c->ring_read * 2 + 1];
        c->ring_read = (c->ring_read + 1) % AUDIO_RING;
        n++;
    }
    return n;
}

/* ---- battery (cartridge RAM plus the RTC footer) ------------------------ */
EXPORT int pa_battery_size(int i) { return GB_save_battery_size(C[i].gb); }
EXPORT int pa_save_battery(int i, uint8_t *dst, size_t len) { return GB_save_battery_to_buffer(C[i].gb, dst, len); }
EXPORT int pa_load_battery(int i, const uint8_t *src, size_t len) { GB_load_battery_from_buffer(C[i].gb, src, len); return 0; }

/* ---- save states (SameBoy's own; they include cartridge RAM and the RTC) */
EXPORT uint32_t pa_state_size(int i) { return (uint32_t)GB_get_save_state_size(C[i].gb); }
EXPORT int pa_save_state(int i, uint8_t *dst) { GB_save_state_to_buffer(C[i].gb, dst); return 0; }
EXPORT int pa_load_state(int i, const uint8_t *src, size_t len)
{
    int r = GB_load_state_from_buffer(C[i].gb, src, len);
    C[i].ring_read = C[i].ring_write = 0;
    return r;
}

/* ---- odds and ends ------------------------------------------------------ */
EXPORT double pa_rumble(int i) { return C[i].rumble; }
EXPORT int pa_read(int i, int addr) { return GB_safe_read_memory(C[i].gb, (uint16_t)addr); }
EXPORT void pa_write(int i, int addr, int v) { GB_write_memory(C[i].gb, (uint16_t)addr, (uint8_t)v); }

/* ---- the pair: two consoles on one cable ---------------------------------
 * Link sessions: the clock is in session mode (pa_set_clock(1, T0) before
 * either pa_init), both consoles are loaded and their boot ROMs skipped, then
 * pa_pair_power_on() starts them half a frame apart. Everything the pair
 * does depends on emulated state only, so two homes stay identical. */

/* The cable: the console driving the clock latches the bit it sends (start)
 * and exchanges it with its partner's (end). */
static void serial_start(GB_gameboy_t *gb, bool bit) { PAIR.h.bit_out[index_of(gb)] = bit; }

static bool serial_end(GB_gameboy_t *gb)
{
    int i = index_of(gb);
    if (!PAIR.h.linked) return true;
    GB_gameboy_t *other = C[i ^ 1].gb;
    bool in = GB_serial_get_data_bit(other);
    GB_serial_set_data_bit(other, PAIR.h.bit_out[i]);
    return in;
}

EXPORT void pa_link(int on)
{
    PAIR.h.linked = on ? 1 : 0;
    for (int i = 0; i < CONSOLES; i++) {
        if (on) {
            GB_set_serial_transfer_bit_start_callback(C[i].gb, serial_start);
            GB_set_serial_transfer_bit_end_callback(C[i].gb, serial_end);
        }
        else {
            GB_disconnect_serial(C[i].gb);
        }
    }
}

EXPORT void pa_set_render(int i, int on) { GB_set_rendering_disabled(C[i].gb, !on); }

EXPORT void pa_set_presented(int i)
{
    if (!PAIR.presented_fb) PAIR.presented_fb = calloc(MAX_W * MAX_H, 4);
    PAIR.presented = i;
}

EXPORT uint32_t *pa_presented_framebuffer(void) { return PAIR.presented_fb; }

/* Consoles powered on on the same tick never link: each sits on its own
 * vblank, then console 0 runs half a frame first. */
static int guard_on = 1;

EXPORT void pa_pair_power_on(void)
{
    guard_on = 1;
    pa_run_frame(0);
    pa_run_frame(1);
    PAIR.h.magic = PAIR_MAGIC;
    PAIR.h.version = PAIR_VERSION;
    PAIR.h.offset = -HALF_FRAME;
    PAIR.h.frame = 0;
    PAIR.h.timeline = 0;
    PAIR.active = true;
}

static bool internal_transfer(int i)
{
    /* SC bit 7: a transfer is pending; bit 0: this console drives the clock.
     * An armed external-clock wait (0x80) is no transfer in flight. */
    return (GB_safe_read_memory(C[i].gb, 0xFF02) & 0x81) == 0x81;
}

/* The phase guard: LCD on/off moves the consoles' relative phase, and two
 * consoles near phase 0 lock up the link. When the phase comes within a
 * quarter frame of 0 and no internal-clock transfer is running, move it back
 * to half a frame. Emulated state only, so both homes do the same. */
static void guard(void)
{
    if (!PAIR.vbl_seen[0] || !PAIR.vbl_seen[1]) return; /* an LCD is off: no phase this frame */
    int64_t d = (PAIR.vbl[1] - PAIR.vbl[0]) % FRAME_TICKS;
    if (d < 0) d += FRAME_TICKS;
    PAIR.phase = (double)d;
    if (!guard_on) return;
    int64_t near = d < FRAME_TICKS - d ? d : FRAME_TICKS - d;
    if (near >= GUARD_NEAR) return;
    if (internal_transfer(0) || internal_transfer(1)) return;
    /* Console 0 runs (HALF_FRAME - d) more ticks before console 1 resumes. */
    PAIR.h.offset -= HALF_FRAME - d;
}

EXPORT uint32_t pa_run_pair_frame(void)
{
    C[0].vblank = C[1].vblank = false;
    PAIR.vbl_seen[0] = PAIR.vbl_seen[1] = false;
    uint32_t steps = 0;
    while (!C[0].vblank || !C[1].vblank) {
        if (PAIR.h.offset <= 0) {
            unsigned t = run_once(0);
            PAIR.h.offset += t;
            PAIR.h.timeline += t;
        }
        else {
            PAIR.h.offset -= run_once(1);
        }
        steps++;
    }
    PAIR.h.frame++;
    guard();
    return steps;
}

EXPORT double pa_phase(void) { return PAIR.phase; }
EXPORT double pa_offset(void) { return (double)PAIR.h.offset; }
EXPORT void pa_set_offset(double ticks) { PAIR.h.offset = (int64_t)ticks; }
/* Tests: turns the phase guard off until the next power-on. */
EXPORT void pa_set_guard(int on) { guard_on = on ? 1 : 0; }
/* Tests: moves console 1 ahead by `ticks` (the phase falls by as much). */
EXPORT void pa_debug_shift(double ticks) { PAIR.h.offset += (int64_t)ticks; }

/* ---- pair snapshots ------------------------------------------------------ */
EXPORT uint32_t pa_pair_snapshot_size(void)
{
    return (uint32_t)(sizeof(pair_header_t) + GB_get_save_state_size(C[0].gb) + GB_get_save_state_size(C[1].gb));
}

EXPORT int pa_pair_snapshot(uint8_t *dst)
{
    PAIR.h.session_t0 = session_t0;
    PAIR.h.session_ticks = session_ticks;
    PAIR.h.state_size[0] = (uint32_t)GB_get_save_state_size(C[0].gb);
    PAIR.h.state_size[1] = (uint32_t)GB_get_save_state_size(C[1].gb);
    memcpy(dst, &PAIR.h, sizeof(PAIR.h));
    GB_save_state_to_buffer(C[0].gb, dst + sizeof(PAIR.h));
    GB_save_state_to_buffer(C[1].gb, dst + sizeof(PAIR.h) + PAIR.h.state_size[0]);
    return 0;
}

static int restore(const uint8_t *src, uint32_t len, bool keep_clock)
{
    pair_header_t h;
    if (len < sizeof(h)) return -1;
    memcpy(&h, src, sizeof(h));
    if (h.magic != PAIR_MAGIC || h.version != PAIR_VERSION) return -2;
    if (sizeof(h) + (uint64_t)h.state_size[0] + h.state_size[1] > len) return -3;
    /* The clock first: the core may read time() while loading. */
    if (!keep_clock) { session_t0 = h.session_t0; session_ticks = h.session_ticks; }
    int r0 = GB_load_state_from_buffer(C[0].gb, src + sizeof(h), h.state_size[0]);
    int r1 = GB_load_state_from_buffer(C[1].gb, src + sizeof(h) + h.state_size[0], h.state_size[1]);
    if (r0 || r1) return -10 - (r0 ? 1 : 0) - (r1 ? 2 : 0);
    uint64_t timeline = PAIR.h.timeline;
    PAIR.h = h;
    if (keep_clock) {
        PAIR.h.session_t0 = session_t0;
        PAIR.h.session_ticks = session_ticks;
        PAIR.h.timeline = timeline;
    }
    PAIR.active = true;
    C[0].ring_read = C[0].ring_write = C[1].ring_read = C[1].ring_write = 0;
    pa_link(h.linked); /* the cable callbacks are not in a SameBoy state */
    return 0;
}

EXPORT int pa_pair_restore(const uint8_t *src, uint32_t len) { return restore(src, len, false); }
/* A power cycle of the pair: the snapshot's consoles, today's clock. */
EXPORT int pa_pair_restore_keep_clock(const uint8_t *src, uint32_t len) { return restore(src, len, true); }

/* ---- what the homes compare ---------------------------------------------- */
static uint64_t fnv(uint64_t h, const uint8_t *p, size_t n)
{
    for (size_t k = 0; k < n; k++) { h ^= p[k]; h *= 1099511628211ull; }
    return h;
}

/* Game-visible state of both consoles: work RAM, cartridge RAM, CPU registers.
 * Never the full states: a console that does not render differs in a few
 * picture bytes. */
EXPORT uint32_t pa_pair_digest(void)
{
    uint64_t h = 14695981039346656037ull;
    for (int i = 0; i < CONSOLES; i++) {
        size_t n = 0;
        uint16_t bank = 0;
        uint8_t *p = GB_get_direct_access(C[i].gb, GB_DIRECT_ACCESS_RAM, &n, &bank);
        h = fnv(h, p, n);
        p = GB_get_direct_access(C[i].gb, GB_DIRECT_ACCESS_CART_RAM, &n, &bank);
        if (p && n) h = fnv(h, p, n);
        GB_registers_t *r = GB_get_registers(C[i].gb);
        h = fnv(h, (const uint8_t *)r->registers, sizeof(r->registers));
    }
    return (uint32_t)(h ^ (h >> 32));
}

EXPORT uint8_t *pa_cart_ram_ptr(int i)
{
    size_t n = 0;
    uint16_t bank = 0;
    return GB_get_direct_access(C[i].gb, GB_DIRECT_ACCESS_CART_RAM, &n, &bank);
}

EXPORT int pa_cart_ram_size(int i)
{
    size_t n = 0;
    uint16_t bank = 0;
    return GB_get_direct_access(C[i].gb, GB_DIRECT_ACCESS_CART_RAM, &n, &bank) ? (int)n : 0;
}
