/* PlayAgain's link cores: two mGBA Game Boy Advance cores in one wasm
 * instance, joined by mGBA's lockstep link cable and stepped by a
 * single-threaded scheduler. Everything the pair does depends on emulated
 * state only, so two homes stay identical. MPL-2.0, like the mGBA code it
 * drives.
 *
 * Scheduling (a function of emulated state):
 *   until core 0's frame counter moves on:
 *     core 1 awake -> one slice of core 1   (it sleeps at the coordinator's cycle)
 *     else core 0 awake -> one slice of core 0
 *     else -> deadlock (reported)
 */
#include <mgba/core/core.h>
#include <mgba/core/config.h>
#include <mgba/core/log.h>
#include <mgba/core/serialize.h>
#include <mgba/core/lockstep.h>
#include <mgba/internal/gba/gba.h>
#include <mgba/internal/gba/cart/gpio.h>
#include <mgba/internal/gba/savedata.h>
#include <mgba/internal/gba/sio/lockstep.h>
#include <mgba-util/audio-buffer.h>
#include <mgba-util/audio-resampler.h>
#include <mgba-util/vfs.h>

#include <stdarg.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#define CORES 2
#define VW 256
#define VH 224
#define SCREEN_W 240
#define SCREEN_H 160
#define AUDIO_RATE 48000
#define AUDIO_FRAMES 0x4000
#define MAX_SLICES 200000
#define SNAP_MAGIC 0x4C4D4150u /* "PAML" */
#define SNAP_VERSION 1u
#define SNAP_HEADER 16

struct User {
	struct mLockstepUser d;
	int idx;
	int asleep;
};

static struct {
	struct mCore* core;
	mColor* video;
	void* rom;
	unsigned keys;
	struct mAudioBuffer out;
	struct mAudioResampler resampler;
	double sourceRate;
	struct mCoreCallbacks callbacks;
} C[CORES];

static struct GBASIOLockstepCoordinator coord;
static struct GBASIOLockstepDriver drv[CORES];
static struct User users[CORES];
static int linked = 0;
static int presented = 0;
static uint32_t presentedFb[SCREEN_W * SCREEN_H];
static uint8_t* snap = NULL;
static size_t snapSize = 0;

static void _log(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
	(void) logger;
	(void) category;
	(void) level;
	(void) format;
	(void) args;
}
static struct mLogger silent = { .log = _log, .filter = NULL };

static void _userSleep(struct mLockstepUser* u) { ((struct User*) u)->asleep = 1; }
static void _userWake(struct mLockstepUser* u) { ((struct User*) u)->asleep = 0; }
/* Core 0 is player 0 (the clock owner and link master) in every home. */
static int _userRequestedId(struct mLockstepUser* u) { return ((struct User*) u)->idx; }
static void _userPlayerIdChanged(struct mLockstepUser* u, int id) {
	(void) u;
	(void) id;
}

/* This home shows that core: its frame is copied whole at its own frame end. */
static void _frameEnded(void* context) {
	int i = (int) (intptr_t) context;
	if (i != presented) return;
	for (int y = 0; y < SCREEN_H; ++y) {
		for (int x = 0; x < SCREEN_W; ++x) presentedFb[y * SCREEN_W + x] = (uint32_t) C[i].video[y * VW + x] | 0xFF000000u;
	}
}

/* A battery's size names its save type, for a cartridge mGBA has no override for. */
static int _typeForSize(int bytes) {
	switch (bytes) {
	case 512: return GBA_SAVEDATA_EEPROM512;
	case 8192: return GBA_SAVEDATA_EEPROM;
	case 32768: return GBA_SAVEDATA_SRAM;
	case 65536: return GBA_SAVEDATA_FLASH512;
	case 131072: return GBA_SAVEDATA_FLASH1M;
	}
	return -1;
}

static int64_t _msPerFrames(struct mCore* core, uint32_t frames) {
	return (int64_t) frames * ((int64_t) core->frameCycles(core) * 1000) / core->frequency(core);
}

/* The cartridge clock now, in ms: mGBA's fake epoch plus emulated frames. */
static int64_t _rtcMs(int i) {
	struct mCore* core = C[i].core;
	return core->rtc.value + _msPerFrames(core, core->frameCounter(core));
}

void ml_init(void) { mLogSetDefaultLogger(&silent); }

/* Loads core i with its cartridge and battery; `epochMs` is the cartridge
 * clock at power-on, as the cartridge shows it (T0 plus its home's offset
 * east of UTC). The clock then moves with emulated frames only. A cartridge
 * mGBA has no override for gets the save type its battery's size names.
 * 1 on success; 0 on failure; -2 when the battery was not taken whole. */
int ml_load(int i, const void* rom, int romBytes, const void* battery, int batteryBytes, double epochMs) {
	if (i < 0 || i >= CORES || C[i].core) return 0;
	C[i].rom = malloc(romBytes);
	memcpy(C[i].rom, rom, romBytes);
	struct VFile* vf = VFileFromMemory(C[i].rom, romBytes);
	struct mCore* core = mCoreCreate(mPLATFORM_GBA);
	if (!core) return 0;
	mCoreInitConfig(core, NULL);
	if (!core->init(core)) return 0;
	struct mCoreOptions defaults = { .useBios = true, .skipBios = false, .volume = 0x100, .logLevel = 0 };
	mCoreConfigLoadDefaults(&core->config, &defaults);
	mCoreLoadConfig(core);
	C[i].video = calloc(VW * VH, sizeof(mColor));
	core->setVideoBuffer(core, C[i].video, VW);
	core->setAudioBufferSize(core, AUDIO_FRAMES);
	if (!core->loadROM(core, vf)) return 0;
	core->reset(core);
	struct GBA* gba = core->board;
	if (battery && batteryBytes > 0) {
		if (gba->memory.savedata.type == GBA_SAVEDATA_AUTODETECT) {
			int type = _typeForSize(batteryBytes);
			if (type < 0) return -2;
			GBASavedataForceType(&gba->memory.savedata, (enum GBASavedataType) type);
		}
		if (!core->savedataRestore(core, battery, batteryBytes, true)) return -2;
		if ((int) GBASavedataSize(&gba->memory.savedata) != batteryBytes) return -2;
	}
	core->rtc.override = RTC_FAKE_EPOCH;
	core->rtc.value = (int64_t) epochMs;
	memset(&C[i].callbacks, 0, sizeof(C[i].callbacks));
	C[i].callbacks.context = (void*) (intptr_t) i;
	C[i].callbacks.videoFrameEnded = _frameEnded;
	core->addCoreCallbacks(core, &C[i].callbacks);
	mAudioBufferInit(&C[i].out, AUDIO_FRAMES, 2);
	mAudioResamplerInit(&C[i].resampler, mINTERPOLATOR_SINC);
	C[i].sourceRate = 0;
	C[i].core = core;
	return 1;
}

/* Joins the two loaded cores on the cable: core 0 then core 1 in every home. */
int ml_link(void) {
	if (!C[0].core || !C[1].core || linked) return 0;
	GBASIOLockstepCoordinatorInit(&coord);
	for (int i = 0; i < CORES; ++i) {
		memset(&users[i], 0, sizeof(users[i]));
		users[i].idx = i;
		users[i].d.sleep = _userSleep;
		users[i].d.wake = _userWake;
		users[i].d.requestedId = _userRequestedId;
		users[i].d.playerIdChanged = _userPlayerIdChanged;
		GBASIOLockstepDriverCreate(&drv[i], &users[i].d);
		GBASIOLockstepCoordinatorAttach(&coord, &drv[i]);
	}
	for (int i = 0; i < CORES; ++i) C[i].core->setPeripheral(C[i].core, mPERIPH_GBA_LINK_PORT, &drv[i].d);
	linked = 1;
	return (int) GBASIOLockstepCoordinatorAttached(&coord);
}

/* mGBA's key mask: A 1, B 2, Select 4, Start 8, Right 16, Left 32, Up 64, Down 128, R 256, L 512. */
void ml_set_keys(int i, unsigned keys) { C[i].keys = keys; }

/* Runs until core 0's next frame. Slices run, or -1 for a deadlock, -2 past MAX_SLICES. */
int ml_run_pair_frame(void) {
	struct mCore* c0 = C[0].core;
	struct mCore* c1 = C[1].core;
	c0->setKeys(c0, C[0].keys);
	c1->setKeys(c1, C[1].keys);
	int slices = 0;
	if (!linked) {
		c0->runFrame(c0);
		c1->runFrame(c1);
	} else {
		uint32_t start = c0->frameCounter(c0);
		while (c0->frameCounter(c0) == start) {
			if (!users[1].asleep) c1->runLoop(c1);
			else if (!users[0].asleep) c0->runLoop(c0);
			else return -1;
			if (++slices > MAX_SLICES) return -2;
		}
	}
	/* The hidden core's sound is nobody's: drop it so its buffer never fills. */
	struct mCore* hidden = C[presented ^ 1].core;
	mAudioBufferClear(hidden->getAudioBuffer(hidden));
	return slices;
}

double ml_frame_rate(void) { return (double) C[0].core->frequency(C[0].core) / C[0].core->frameCycles(C[0].core); }

void ml_set_presented(int i) { presented = i; }
uint32_t* ml_presented_framebuffer(void) { return presentedFb; }

/* A hidden core skips drawing; its emulated state is the same either way. */
void ml_set_render(int i, int on) {
	struct GBA* gba = C[i].core->board;
	gba->video.frameskip = on ? 0 : 0x7FFFFFFF;
	gba->video.frameskipCounter = gba->video.frameskip;
}

/* Interleaved stereo int16 frames at 48 kHz, whatever rate the game runs its sound at. */
int ml_read_audio(int i, int16_t* dst, int maxFrames) {
	struct mCore* core = C[i].core;
	double rate = core->audioSampleRate(core);
	if (rate != C[i].sourceRate) {
		mAudioResamplerSetSource(&C[i].resampler, core->getAudioBuffer(core), rate, true);
		mAudioResamplerSetDestination(&C[i].resampler, &C[i].out, AUDIO_RATE);
		C[i].sourceRate = rate;
	}
	mAudioResamplerProcess(&C[i].resampler);
	return (int) mAudioBufferRead(&C[i].out, dst, maxFrames);
}

int ml_battery_size(int i) { return (int) GBASavedataSize(&((struct GBA*) C[i].core->board)->memory.savedata); }

/* 0 on success. Exactly the save type's size, with no clock footer. */
int ml_save_battery(int i, uint8_t* dst) {
	struct GBASavedata* savedata = &((struct GBA*) C[i].core->board)->memory.savedata;
	size_t n = GBASavedataSize(savedata);
	if (n && !savedata->data) return -1;
	if (n) memcpy(dst, savedata->data, n);
	return 0;
}

uint8_t* ml_cart_ram_ptr(int i) { return ((struct GBA*) C[i].core->board)->memory.savedata.data; }
int ml_cart_ram_size(int i) { return ml_battery_size(i); }

/* ---- pair snapshots: [magic][version][len0][len1][core 0 state][core 1 state] -
 * Each state is mGBA's named state: the raw state plus the battery, the
 * clock and the link driver's block (player 0's carries the coordinator). */
uint32_t ml_snapshot_size(void) {
	struct VFile* vfs[CORES];
	size_t sizes[CORES];
	for (int i = 0; i < CORES; ++i) {
		vfs[i] = VFileMemChunk(NULL, 0);
		if (!mCoreSaveStateNamed(C[i].core, vfs[i], SAVESTATE_SAVEDATA | SAVESTATE_RTC)) return 0;
		sizes[i] = vfs[i]->size(vfs[i]);
	}
	free(snap);
	snapSize = SNAP_HEADER + sizes[0] + sizes[1];
	snap = malloc(snapSize);
	uint32_t header[4] = { SNAP_MAGIC, SNAP_VERSION, (uint32_t) sizes[0], (uint32_t) sizes[1] };
	memcpy(snap, header, SNAP_HEADER);
	size_t off = SNAP_HEADER;
	for (int i = 0; i < CORES; ++i) {
		vfs[i]->seek(vfs[i], 0, SEEK_SET);
		vfs[i]->read(vfs[i], snap + off, sizes[i]);
		off += sizes[i];
		vfs[i]->close(vfs[i]);
	}
	return (uint32_t) snapSize;
}

/* Copies the snapshot ml_snapshot_size just took. */
void ml_snapshot(uint8_t* dst) { memcpy(dst, snap, snapSize); }

static int _restorePass(const uint8_t* data, size_t len) {
	uint32_t header[4];
	if (len < SNAP_HEADER) return -1;
	memcpy(header, data, SNAP_HEADER);
	if (header[0] != SNAP_MAGIC || header[1] != SNAP_VERSION) return -1;
	if ((size_t) SNAP_HEADER + header[2] + header[3] != len) return -1;
	size_t off = SNAP_HEADER;
	for (int i = 0; i < CORES; ++i) {
		struct VFile* vf = VFileMemChunk(data + off, header[2 + i]);
		bool ok = mCoreLoadStateNamed(C[i].core, vf, SAVESTATE_SAVEDATA | SAVESTATE_RTC);
		vf->close(vf);
		if (!ok) return -2 - i;
		off += header[2 + i];
	}
	return 0;
}

/* 0 on success. Two passes: on the first, core 1's raw load switches its link
 * mode and its driver queues a stray mode event into player 0's already
 * restored queue; the second finds every mode equal, so each queue ends up
 * exactly as saved. */
int ml_restore(const uint8_t* data, int len) {
	int r = _restorePass(data, (size_t) len);
	if (r) return r;
	return _restorePass(data, (size_t) len);
}

/* The snapshot's cores with today's batteries and clocks: a power cycle that
 * keeps both batteries and lets each cartridge clock run on. Each battery
 * keeps the save type it has now: a cartridge mGBA does not know settles its
 * type on first use, often after the snapshot (which then says "not yet
 * known" and would drop the battery). 0 on success, -4 if a battery did not
 * come back whole. */
int ml_restore_keep_clock(const uint8_t* data, int len) {
	int64_t now[CORES];
	void* batteries[CORES] = { NULL, NULL };
	size_t sizes[CORES] = { 0, 0 };
	enum GBASavedataType types[CORES];
	for (int i = 0; i < CORES; ++i) {
		now[i] = _rtcMs(i);
		types[i] = ((struct GBA*) C[i].core->board)->memory.savedata.type;
		sizes[i] = C[i].core->savedataClone(C[i].core, &batteries[i]);
	}
	int r = ml_restore(data, len);
	for (int i = 0; i < CORES; ++i) {
		if (!r && sizes[i]) {
			struct GBASavedata* savedata = &((struct GBA*) C[i].core->board)->memory.savedata;
			if (savedata->type != types[i]) GBASavedataForceType(savedata, types[i]);
			C[i].core->savedataRestore(C[i].core, batteries[i], sizes[i], true);
			if (GBASavedataSize(savedata) != sizes[i]) r = -4;
		}
		free(batteries[i]);
		if (r == 0 || r == -4) C[i].core->rtc.value = now[i] - _msPerFrames(C[i].core, C[i].core->frameCounter(C[i].core));
	}
	return r;
}

/* ---- digest: what the games can see ---------------------------------------
 * Battery, link driver block, EWRAM + IWRAM, VRAM + OAM + palette, CPU
 * registers of both cores. Never the raw state: after a load its sound
 * bookkeeping differs forever though the games do not. */
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 *= 0x100000001b3ULL;
	}
	return h;
}

uint32_t ml_digest(void) {
	uint64_t h = 0xcbf29ce484222325ULL;
	for (int i = 0; i < CORES; ++i) {
		struct GBA* gba = C[i].core->board;
		size_t n = GBASavedataSize(&gba->memory.savedata);
		if (n && gba->memory.savedata.data) h = _fnv(h, gba->memory.savedata.data, n);
		if (linked) {
			void* state = NULL;
			size_t size = 0;
			drv[i].d.saveState(&drv[i].d, &state, &size);
			if (state) {
				h = _fnv(h, state, size);
				free(state);
			}
		}
		h = _fnv(h, (const uint8_t*) gba->memory.wram, 256 * 1024);
		h = _fnv(h, (const uint8_t*) gba->memory.iwram, 32 * 1024);
		h = _fnv(h, (const uint8_t*) gba->video.vram, 96 * 1024);
		h = _fnv(h, (const uint8_t*) gba->video.oam.raw, 1024);
		h = _fnv(h, (const uint8_t*) gba->video.palette, 1024);
		h = _fnv(h, (const uint8_t*) gba->cpu->gprs, 16 * 4);
	}
	return (uint32_t) (h ^ (h >> 32));
}

/* ---- tests only ------------------------------------------------------------ */

/* Reads the cartridge clock through its GPIO pins as a game does (Pokémon's
 * siirtc.c: command 0x65, then seven BCD bytes: year, month, day, weekday,
 * hour, minute, second). Drives the clock chip: never inside a session.
 * 0 on success; -1 for a cartridge with no clock. */
int ml_debug_rtc(int i, uint8_t* out) {
	struct GBACartridgeHardware* hw = &((struct GBA*) C[i].core->board)->memory.hw;
	if (!hw->gpioBase || !(hw->devices & HW_RTC)) return -1;
	GBAHardwareGPIOWrite(hw, GPIO_REG_CONTROL, 1);
	GBAHardwareGPIOWrite(hw, GPIO_REG_DATA, 1);
	GBAHardwareGPIOWrite(hw, GPIO_REG_DATA, 5);
	GBAHardwareGPIOWrite(hw, GPIO_REG_DIRECTION, 7);
	for (int k = 0; k < 8; ++k) {
		unsigned bit = (0x65 >> (7 - k)) & 1;
		for (int r = 0; r < 3; ++r) GBAHardwareGPIOWrite(hw, GPIO_REG_DATA, (bit << 1) | 4);
		GBAHardwareGPIOWrite(hw, GPIO_REG_DATA, (bit << 1) | 5);
	}
	GBAHardwareGPIOWrite(hw, GPIO_REG_DIRECTION, 5);
	for (int b = 0; b < 7; ++b) {
		unsigned value = 0;
		for (int k = 0; k < 8; ++k) {
			for (int r = 0; r < 4; ++r) GBAHardwareGPIOWrite(hw, GPIO_REG_DATA, 4);
			GBAHardwareGPIOWrite(hw, GPIO_REG_DATA, 5);
			value = (value >> 1) | (((hw->pinState >> 1) & 1) << 7);
		}
		out[b] = (uint8_t) value;
	}
	GBAHardwareGPIOWrite(hw, GPIO_REG_DATA, 1);
	GBAHardwareGPIOWrite(hw, GPIO_REG_DATA, 1);
	return 0;
}

/* Core i's work RAM, for probe cartridges' results and test bots: region 0
 * is EWRAM (256 KiB at 0x02000000), 1 is IWRAM (32 KiB at 0x03000000). */
uint8_t* ml_debug_memory(int i, int region) {
	struct GBA* gba = C[i].core->board;
	return (uint8_t*) (region ? gba->memory.iwram : gba->memory.wram);
}
