// SPDX-License-Identifier: GPL-3.0-or-later
// PlayAgain's Nintendo 3DS core: a flat C interface around Panda3DS (with the panda3ds-wasm patches and PlayAgain's), in place
// of that port's web/web_main.cpp. The caller owns the loop: it calls pa_run_frame once per emulated frame (60 a second). One
// thread; the OpenGL ES renderer draws both screens into a WebGL2 context on Module.canvas, an OffscreenCanvas when the core
// runs in panda3ds-worker.js (the way it ships) or a page's canvas. The README's "C API" is the contract; keep the two in step.
#include <emscripten.h>
#include <emscripten/html5.h>
#include <emscripten/html5_webgl.h>

#include <cstdio>
#include <filesystem>
#include <fstream>
#include <memory>
#include <string>
#include <vector>

#include "PICA/gpu.hpp"
#include "PICA/regs.hpp"
#include "emulator.hpp"
#include "io_file.hpp"
#include "opengl.hpp"
#include "screen_layout.hpp"
#include "services/hid.hpp"

namespace fs = std::filesystem;

extern u64 paUnalignedDraws;  // draw_acceleration.cpp (panda3ds-92e53d2-pa.patch)

namespace {
	std::unique_ptr<Emulator> emu;
	std::vector<u8> screens[2];  // [0] top 400x240, [1] bottom 320x240, RGBA8
	u32 frames = 0;
	int layoutRect[4] = {40, 240, 320, 240};
	std::string titleId;  // 16 lowercase hex digits once a game is loaded, else empty
	std::string saveDir;  // the game's folder under /pa/3ds/saves/, else empty
	// The session clock (pa_set_clock): local wall time at boot in ms since 1970. Until the page sets it, 2000-01-01 00:00.
	u64 sessionClockMs = 946684800000ull;

	// The settings the browser build runs with, written where Panda3DS looks for its config.toml (getAppDataRoot is /pa/3ds/, see
	// panda3ds-92e53d2-pa.patch) unless the caller wrote one there first. The shader JIT targets x64/arm64 hosts only; textures
	// are hashed (as the libretro core does: without it glyphs the game draws into a texture at run time show stale, so text came
	// out scrambled); sound is on, into the DSP's sample ring that pa_read_audio drains (the build has no audio device of its own).
	void writeConfig() {
		std::error_code ec;
		fs::create_directories("/pa/3ds", ec);
		if (fs::exists("/pa/3ds/config.toml", ec)) return;
		std::ofstream("/pa/3ds/config.toml") << "[GPU]\nRenderer = \"opengl\"\nEnableShaderJIT = false\nHashTextures = true\nScreenLayout = \"Default\"\nTopScreenSize = 0.5\n"
												"[Audio]\nEnableAudio = true\nDSPEmulation = \"HLE\"\n"
												"[General]\nEnableDiscordRPC = false\nPrintAppVersion = false\n";
	}

	// Converts the screen the guest last presented into RGBA (framebuffers are stored rotated: column major, y flipped).
	int convertScreen(bool top) {
		using namespace PICA::ExternalRegs;
		auto& out = screens[top ? 0 : 1];
		const u32 w = top ? 400 : 320, h = 240;
		out.resize(w * h * 4);
		GPU& gpu = emu->getGPU();
		auto& r = gpu.getExtRegisters();
		const u32 sel = r[top ? Framebuffer0Select : Framebuffer1Select] & 1;
		const u32 addr = r[top ? (sel ? Framebuffer0ASecondAddr : Framebuffer0AFirstAddr) : (sel ? Framebuffer1ASecondAddr : Framebuffer1AFirstAddr)];
		const u32 fmt = r[top ? Framebuffer0Config : Framebuffer1Config] & 7;
		static const int bpp[] = {4, 3, 2, 2, 2, 2, 2, 2};
		const u8* fb = gpu.getPointerPhys<u8>(addr, w * h * bpp[fmt]);
		if (!fb) {
			std::fill(out.begin(), out.end(), 0);
			return 0;
		}
		for (u32 x = 0; x < w; x++) {
			for (u32 y = 0; y < h; y++) {
				const u8* p = fb + (x * h + (h - 1 - y)) * bpp[fmt];
				u8 R = 0, G = 0, B = 0;
				switch (fmt) {
					case 0: R = p[3]; G = p[2]; B = p[1]; break;
					case 1: B = p[0]; G = p[1]; R = p[2]; break;
					case 2: {
						u16 v = p[0] | p[1] << 8;
						R = (v >> 11) * 255 / 31;
						G = ((v >> 5) & 63) * 255 / 63;
						B = (v & 31) * 255 / 31;
						break;
					}
					default: break;
				}
				u8* o = &out[(y * w + x) * 4];
				o[0] = R; o[1] = G; o[2] = B; o[3] = 255;
			}
		}
		return 1;
	}
}  // namespace

// The canvas is Module.canvas: Emscripten finds "#canvas" through specialHTMLTargets (a worker has no document), as the PSP core does.
EM_JS(int, pa_bind_canvas, (void), {
	if (!Module['canvas']) return 0;
	specialHTMLTargets['#canvas'] = Module['canvas'];
	return 1;
});

// Save states (pa_state_loaded): Emscripten's counter for new GL object names, read, or raised to at least `atLeast`.
EM_JS(int, pa_js_gl_counter, (int atLeast), {
	if (atLeast > GL.counter) GL.counter = atLeast;
	return GL.counter;
});
// Grows the module's memory to at least `bytes` (the views follow), so a larger memory image fits.
EM_JS(void, pa_js_reserve, (double bytes), {
	if (bytes > HEAPU8.length) {
		wasmMemory.grow(Math.ceil((bytes - HEAPU8.length) / 65536));
		updateMemoryViews();
	}
});

extern "C" {

// A WebGL2 context on Module.canvas, whose drawing buffer becomes width x height, and the emulator behind it. preserve != 0 keeps
// the picture readable after the frame (a page that reads its own canvas; the worker takes each frame as an ImageBitmap instead).
// Returns 1; 0 without WebGL2, -1 if GLES would not load, -3 without Module.canvas. Call once, before anything else.
EMSCRIPTEN_KEEPALIVE int pa_init(int width, int height, int preserve) {
	if (!pa_bind_canvas()) return -3;
	writeConfig();
	emu = std::make_unique<Emulator>();
	EmscriptenWebGLContextAttributes a;
	emscripten_webgl_init_context_attributes(&a);
	a.majorVersion = 2;
	a.minorVersion = 0;
	a.alpha = false;
	a.depth = true;
	a.stencil = true;
	a.antialias = false;
	a.preserveDrawingBuffer = preserve != 0;
	a.powerPreference = EM_WEBGL_POWER_PREFERENCE_HIGH_PERFORMANCE;
	a.enableExtensionsByDefault = true;
	emscripten_set_canvas_element_size("#canvas", width, height);
	const EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context("#canvas", &a);
	if (ctx <= 0) {
		std::printf("[pa] WebGL2 context creation failed (%d)\n", static_cast<int>(ctx));
		return 0;
	}
	emscripten_webgl_make_context_current(ctx);
	if (!gladLoadGLES2Loader(reinterpret_cast<GLADloadproc>(emscripten_webgl_get_proc_address))) {
		std::printf("[pa] glad could not load GLES2\n");
		return -1;
	}
	emu->getRenderer()->setupGLES();
	emu->setOutputSize(static_cast<u32>(width), static_cast<u32>(height));
	emu->initGraphicsContext(nullptr);
	emu->getMemory().setSessionClock(sessionClockMs);
	return 1;
}

// The guest's clock (the RTC games read, and so their saves' timestamps): utcMs = ms since 1970 UTC at boot, tzOffsetMinutes = the
// local offset east of UTC (JavaScript: -new Date().getTimezoneOffset()). From then on it advances with emulated time only, so a
// session runs the same whatever the host's clock does. Call before pa_load; without it the clock starts at 2000-01-01 00:00.
EMSCRIPTEN_KEEPALIVE void pa_set_clock(double utcMs, int tzOffsetMinutes) {
	const double local = utcMs + double(tzOffsetMinutes) * 60000.0;
	sessionClockMs = local > 0 ? static_cast<u64>(local) : 0;
	if (emu) emu->getMemory().setSessionClock(sessionClockMs);
}

// Loads a decrypted .3ds/.cci/.cxi/.3dsx/.elf from the module's file system (the worker mounts the picked file with WORKERFS: it is
// read where the game asks, never copied) and makes it ready to run; no guest code runs until pa_run_frame. Its folder is
// /pa/3ds/saves/<title ID>/ (pa_save_dir); homebrew without a title ID gets saves/homebrew-<file name>/. Titles that look for the
// DSP firmware on the SD card get a zero-filled stand-in there (SDMC/3ds/dspfirm.cdc, not a save), as the panda3ds-wasm page does.
// Returns 1 on success, 0 if the file is not a game Panda3DS can start (an encrypted dump, say).
EMSCRIPTEN_KEEPALIVE int pa_load(const char* path) {
	titleId.clear();
	saveDir.clear();
	if (!emu->loadROM(path)) return 0;
	emu->getMemory().setSessionClock(sessionClockMs);
	const std::optional<u64> programID = emu->getMemory().getProgramID();
	if (programID.has_value() && *programID != 0) {
		char hex[17];
		std::snprintf(hex, sizeof(hex), "%016llx", static_cast<unsigned long long>(*programID));
		titleId = hex;
	}
	saveDir = IOFile::getAppData().lexically_normal().string();
	while (saveDir.size() > 1 && saveDir.back() == '/') saveDir.pop_back();
	const fs::path sdmc3ds = fs::path(saveDir) / "SDMC" / "3ds";
	std::error_code ec;
	fs::create_directories(sdmc3ds, ec);
	if (!fs::exists(sdmc3ds / "dspfirm.cdc", ec)) {
		std::vector<char> zeros(262144, 0);
		std::ofstream(sdmc3ds / "dspfirm.cdc", std::ios::binary).write(zeros.data(), static_cast<std::streamsize>(zeros.size()));
	}
	emu->resume();
	frames = 0;
	return 1;
}

// The loaded game's title (program) ID from its NCCH header, as 16 lowercase hex digits ("0004000000033500"); "" before a load or
// for homebrew without one.
EMSCRIPTEN_KEEPALIVE const char* pa_title_id() { return titleId.c_str(); }

// The loaded game's folder in the module's file system, e.g. "/pa/3ds/saves/0004000000033500"; "" before a load. Its SaveData/ and
// FormatInfo/ (and SDMC/, the SD card, where ext data lives) are the game's saves; the caller writes them in after pa_load and
// before the first pa_run_frame, and reads them back between frames.
EMSCRIPTEN_KEEPALIVE const char* pa_save_dir() { return saveDir.c_str(); }

// One emulated frame: publish the input state (once per frame, as the SDL frontend does), run the CPU to the next VBlank
// (268,111,856 / 60 ticks) and draw both screens. Returns 1 while the game runs.
EMSCRIPTEN_KEEPALIVE int pa_run_frame() {
	emu->getServiceManager().getHID().updateInputs(emu->getTicks());
	emu->runFrame();
	frames++;
	return emu->running ? 1 : 0;
}

// Buttons as HID::Keys bits (A=1<<0, B, Select, Start, Right, Left, Up, Down, R, L, X, Y=1<<11, ZL=1<<14, ZR=1<<15); the circle
// pad's direction bits belong to pa_set_circle.
EMSCRIPTEN_KEEPALIVE void pa_set_keys(u32 mask) {
	auto& hid = emu->getServiceManager().getHID();
	hid.releaseKey(0xFFFFu & ~mask);
	hid.pressKey(0xFFFFu & mask);
}
// Circle pad, -156..156 on each axis (up is positive).
EMSCRIPTEN_KEEPALIVE void pa_set_circle(int x, int y) {
	auto& hid = emu->getServiceManager().getHID();
	hid.setCirclepadX(static_cast<s16>(x));
	hid.setCirclepadY(static_cast<s16>(y));
}
// Touch in bottom-screen pixels (0..319, 0..239).
EMSCRIPTEN_KEEPALIVE void pa_set_touch(int x, int y, int down) {
	auto& hid = emu->getServiceManager().getHID();
	if (down) hid.setTouchScreenPress(static_cast<u16>(x), static_cast<u16>(y));
	else hid.releaseTouchScreen();
}

// Screen layout for a width x height drawing buffer (the canvas is resized to it): layout 0 = one above the other, 2 = side by
// side; topShare = the top screen's share. The bottom screen's rectangle in it is read back with pa_layout_rect (0 x, 1 y,
// 2 width, 3 height), for mapping touches.
EMSCRIPTEN_KEEPALIVE void pa_layout(int width, int height, int layout, float topShare) {
	auto& cfg = emu->getConfig();
	cfg.screenLayout = static_cast<ScreenLayout::Layout>(layout);
	cfg.topScreenSize = topShare;
	emscripten_set_canvas_element_size("#canvas", width, height);
	emu->setOutputSize(static_cast<u32>(width), static_cast<u32>(height));
	ScreenLayout::WindowCoordinates c;
	ScreenLayout::calculateCoordinates(c, static_cast<u32>(width), static_cast<u32>(height), topShare, cfg.screenLayout);
	layoutRect[0] = static_cast<int>(c.bottomScreenX);
	layoutRect[1] = static_cast<int>(c.bottomScreenY);
	layoutRect[2] = static_cast<int>(c.bottomScreenWidth);
	layoutRect[3] = static_cast<int>(c.bottomScreenHeight);
}
EMSCRIPTEN_KEEPALIVE int pa_layout_rect(int i) { return layoutRect[i & 3]; }

// Sound: copies up to maxFrames stereo frames (interleaved s16, left first) of what the DSP has made since the last call, oldest
// first, into out (room for maxFrames * 2 samples) and returns how many it copied. The DSP keeps at most 8192 frames (250 ms);
// when the caller falls behind, the oldest are dropped. Rate: pa_audio_rate().
EMSCRIPTEN_KEEPALIVE int pa_read_audio(s16* out, int maxFrames) {
	if (!emu || !out || maxFrames <= 0) return 0;
	auto& ring = emu->getDSP()->getSamples();
	return static_cast<int>(ring.pop(out, static_cast<usize>(maxFrames) * 2) / 2);
}
// The DSP's output rate in frames a second: one 160-sample audio frame every 160 * 8192 CPU ticks, 268,111,856 / 8192 = 32728.498046875.
EMSCRIPTEN_KEEPALIVE double pa_audio_rate() { return 268111856.0 / 8192.0; }

// The guest's last presented framebuffer of one screen as RGBA (top 400x240, bottom 320x240), read from emulated VRAM (what the
// guest wrote, not what the GL renderer drew), or 0 if there is none yet.
EMSCRIPTEN_KEEPALIVE const u8* pa_screen(int top) { return convertScreen(top != 0) ? screens[top ? 0 : 1].data() : nullptr; }

// Statistics: frames run since pa_load; guest CPU ticks (268,111,856 a second); draws whose vertices the CPU had to shade because
// WebGL could not fetch their layout (an attribute stride that is not a multiple of its type's size).
EMSCRIPTEN_KEEPALIVE u32 pa_frame_count() { return frames; }
EMSCRIPTEN_KEEPALIVE double pa_ticks() { return emu ? static_cast<double>(emu->getTicks()) : 0.0; }
EMSCRIPTEN_KEEPALIVE double pa_cpu_vertex_draws() { return static_cast<double>(paUnalignedDraws); }

// The guest's clock as the game reads it now: local wall time in ms since 1970, the session clock plus the emulated time since
// boot (what Memory::timeSince3DSEpoch gives the guest, less its 1900 epoch; see panda3ds-92e53d2-pa.patch).
EMSCRIPTEN_KEEPALIVE double pa_guest_clock() {
	return emu ? static_cast<double>(emu->getMemory().sessionClockMs + emu->getTicks() * 1000ull / 268111856ull) : 0.0;
}

// --- save states: the module's memory as an image (the README's "Save states") ---
// Panda3DS has no serialiser, and this build has one thread and no host state the emulated machine depends on outside
// its memory but three things: the compiled guest blocks (WebAssembly modules, in JavaScript), the GL objects (in the
// browser) and the open files (Emscripten's streams). So a state is the whole linear memory, taken between frames, and
// loading one is: a fresh module that ran pa_init and pa_load for the same game, its memory overwritten with the image
// (panda3ds-worker.js, which also puts the game's files and open streams back), then pa_state_loaded, which drops what
// the image says about the other two: the JIT's block cache is cleared (every block is translated again as it runs) and
// the renderer's GL objects are made again (deinit + init, the path a lost context takes on other ports, with the caches
// PlayAgain's patch makes it forget; what was in the render targets is gone until the game draws its next frame). An image opens only in the build that made it.

// Emscripten's GL name counter: the worker stores it with an image and raises it before pa_state_loaded, so the objects
// made then never take a name the image still holds (and would delete).
EMSCRIPTEN_KEEPALIVE int pa_gl_counter(int atLeast) { return pa_js_gl_counter(atLeast); }
// Room for an image of `bytes`.
EMSCRIPTEN_KEEPALIVE void pa_heap_reserve(double bytes) { pa_js_reserve(bytes); }
// After the memory was overwritten with an image: see above. Returns 1.
EMSCRIPTEN_KEEPALIVE int pa_state_loaded() {
	emu->getCPU().clearCache();
	emu->deinitGraphicsContext();
	emu->initGraphicsContext(nullptr);
	return emu->running ? 1 : 0;
}
}

int main() { return 0; }
