/* PlayAgain's melonDS shim: one Nintendo DS behind a flat C ABI for the
 * browser, single-threaded, software-rendered, booted on FreeBIOS with
 * melonDS's generated firmware unless the player hands over their own DS
 * BIOS and firmware (pa_set_bios). Nothing Nintendo's ships in the core.
 *
 * This file is two things:
 *   1. melonDS's Platform (src/Platform.h) for Emscripten: no files, no
 *      threads, no wall clock. Everything the core asks the host for is
 *      answered from this shim's own state, so a frame depends on emulated
 *      state and the inputs alone — two homes stepping the same inputs stay
 *      identical.
 *   2. The pa_* functions the adapter drives: load, power on, inputs, one
 *      frame at a time, the two screens, sound, save states, the cartridge
 *      save, a digest for lockstep comparison, local multiplayer queues.
 *
 * Screens: pa_fb_top()/pa_fb_bottom() are 256×192 u32 pixels, one byte each
 * of R, G, B, A in memory (u32 0xAABBGGRR little-endian; A = 0xFF), ready
 * for an ImageData. melonDS renders BGRA; the swap happens here, once per
 * frame, so the adapter copies and never converts.
 *
 * Keys: pa_set_keys takes melonDS's SetKeyMask word, active-low: a clear bit
 * is a pressed key, 0xFFF is nothing pressed. Bits: 0 A, 1 B, 2 Select,
 * 3 Start, 4 Right, 5 Left, 6 Up, 7 Down, 8 R, 9 L, 10 X, 11 Y.
 *
 * Clock: pa_set_clock(unix seconds) seeds the RTC at the next power-on (or
 * at once, while running); the RTC then advances with emulated time only.
 *
 * BIOS: pa_set_bios hands melonDS the player's own ARM9/ARM7 BIOS and
 * firmware (any part left out stays FreeBIOS / the generated firmware).
 * They go in when the next cart is inserted or at the next power-on, and
 * every boot stays a direct boot. Never set, the DS is exactly the
 * FreeBIOS one pa_init made.
 */
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <memory>
#include <string>
#include <vector>

#include "Args.h"
#include "FreeBIOS.h"
#include "GPU_Soft.h"
#include "NDS.h"
#include "NDSCart.h"
#include "Platform.h"
#include "RTC.h"
#include "SPI.h"
#include "SPI_Firmware.h"
#include "SPU.h"
#include "Savestate.h"
#include "frontend/mic_blow.h"
#define XXH_STATIC_LINKING_ONLY
#include "xxhash/xxhash.h"

using namespace melonDS;

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

namespace {

constexpr int W = 256;
constexpr int H = 192;
constexpr uint64_t CYCLES_PER_FRAME = 560190;
constexpr uint64_t CYCLES_PER_SECOND = 33513982;
/* 33513982 / 560190 Hz = 59.8260982... Hz, as a micro-Hz integer. */
constexpr uint32_t FRAME_RATE_UHZ = 59826098;
constexpr unsigned MIC_RING = 16384; /* mono s16 samples at 47.6 kHz */
constexpr int MP_PAYLOAD_MAX = 2048;

std::unique_ptr<NDS> nds;
int sample_rate = 48000;
uint32_t fb[2][W * H];
uint64_t emu_cycles;      /* emulated time since pa_init, for GetMSCount/GetUSCount */
bool clock_set;
int64_t clock_seconds;    /* the session clock the RTC is seeded from */
char16_t user_name[10];
int user_name_len;
int user_language = Firmware::Language::English;
bool user_set;
uint32_t keys = 0xFFF;
bool touch_down;
int touch_x, touch_y;
bool lid_closed;
bool sram_dirty;
int16_t mic_ring[MIC_RING];
unsigned mic_r, mic_w;
bool mic_blow_on;
unsigned blow_pos;
bool rumbling;
uint64_t rumble_until_ms;
int stop_reason = -1;     /* -1 while running, else a Platform::StopReason */
uint32_t cached_state_size;

/* ---- the player's own BIOS and firmware (pa_set_bios) -------------------
 * An empty part is melonDS's own: FreeBIOS for a BIOS, the generated
 * firmware for the firmware. Kept here until the DS takes them (the next
 * cart inserted, or the next power-on). */
constexpr u32 FIRMWARE_SIZES[] = { 0x20000, 0x40000, 0x80000 }; /* 128 KiB DSi/3DS, 256 KiB DS, 512 KiB iQue */
std::vector<u8> own_arm9, own_arm7, own_fw;
bool bios_pending;        /* asked for since the DS last took it */
bool own_in_ds[3];        /* what the DS holds now: ARM9, ARM7, firmware are the player's */
bool cart_area_rekeyed;   /* melonDS re-encrypted the inserted cart's (decrypted) secure area */

/* ---- local multiplayer: in-process queues --------------------------------
 * Frames the core sends go to the TX queue (pa_mp_pop_tx drains it); frames
 * the host delivers go through pa_mp_push_rx. One format both ways, a
 * 20-byte header then the payload (the DS-style TX header + 802.11 frame):
 *   u32 magic 'PAMP'  u16 sender  u16 type  u16 aid  u16 len  u64 timestamp
 * type: 0 packet, 1 cmd (host → clients), 2 reply (client → host), 3 ack. */
constexpr uint32_t MP_MAGIC = 0x504D4150u; /* 'PAMP' */
constexpr int MP_HEADER = 20;
int mp_instance;
bool mp_active;
std::deque<std::vector<uint8_t>> mp_tx, mp_rx_packets, mp_rx_replies;

uint16_t rd16(const uint8_t* p) { return (uint16_t)(p[0] | (p[1] << 8)); }
uint64_t rd64(const uint8_t* p)
{
    uint64_t v = 0;
    for (int i = 7; i >= 0; i--) v = (v << 8) | p[i];
    return v;
}
void wr16(uint8_t* p, uint16_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); }
void wr32(uint8_t* p, uint32_t v) { for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> (8 * i)); }
void wr64(uint8_t* p, uint64_t v) { for (int i = 0; i < 8; i++) p[i] = (uint8_t)(v >> (8 * i)); }

int mp_send(uint16_t type, uint16_t aid, const u8* data, int len, u64 timestamp)
{
    if (len < 0 || len > MP_PAYLOAD_MAX) return 0;
    std::vector<uint8_t> f(MP_HEADER + len);
    wr32(&f[0], MP_MAGIC);
    wr16(&f[4], (uint16_t)mp_instance);
    wr16(&f[6], type);
    wr16(&f[8], aid);
    wr16(&f[10], (uint16_t)len);
    wr64(&f[12], timestamp);
    if (len) memcpy(&f[MP_HEADER], data, (size_t)len);
    mp_tx.push_back(std::move(f));
    return len;
}

int mp_recv(u8* data, u64* timestamp)
{
    if (mp_rx_packets.empty()) return 0;
    std::vector<uint8_t> f = std::move(mp_rx_packets.front());
    mp_rx_packets.pop_front();
    int len = rd16(&f[10]);
    if (len) memcpy(data, &f[MP_HEADER], (size_t)len);
    if (timestamp) *timestamp = rd64(&f[12]);
    return len;
}

uint64_t emu_ms() { return emu_cycles * 1000 / CYCLES_PER_SECOND; }

struct Sema { int count; };
struct Mtx { int unused; };

void apply_inputs()
{
    nds->SetKeyMask(keys);
    if (touch_down) nds->TouchScreen((u16)touch_x, (u16)touch_y);
    else nds->ReleaseScreen();
    nds->SetLidClosed(lid_closed);
}

void apply_clock()
{
    if (!clock_set) return;
    time_t t = (time_t)clock_seconds;
    struct tm tm;
    gmtime_r(&t, &tm);
    nds->RTC.SetDateTime(tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
}

/* Both copies of the user settings in the generated firmware: the name the
 * game greets, and the language it picks. */
void apply_user()
{
    if (!user_set) return;
    Firmware& fw = nds->GetFirmware();
    for (Firmware::UserData& ud : fw.GetUserData()) {
        memset(ud.Nickname, 0, sizeof(ud.Nickname));
        for (int i = 0; i < user_name_len; i++) ud.Nickname[i] = user_name[i];
        ud.NameLength = (u16)user_name_len;
        ud.Settings = (u16)((ud.Settings & ~0x7) | (user_language & 0x7));
    }
    fw.UpdateChecksums();
}

/* After a frame: the front buffers, swapped to RGBA bytes. */
void copy_screens()
{
    void* top = nullptr;
    void* bottom = nullptr;
    if (!nds->GPU.GetFramebuffers(&top, &bottom) || !top || !bottom) return;
    const uint32_t* src[2] = { (const uint32_t*)top, (const uint32_t*)bottom };
    for (int s = 0; s < 2; s++) {
        for (int i = 0; i < W * H; i++) {
            uint32_t v = src[s][i]; /* 0xAARRGGBB */
            fb[s][i] = 0xFF000000u | ((v & 0xFFu) << 16) | (v & 0xFF00u) | ((v >> 16) & 0xFFu);
        }
    }
}

uint32_t snapshot_size()
{
    Savestate s(24u << 20); /* grows if a state needs more */
    if (s.Error) return 0;
    if (!nds->DoSavestate(&s) || s.Error) return 0;
    return s.Length();
}

uint32_t rd32(const uint8_t* p) { return p[0] | (p[1] << 8) | (p[2] << 16) | ((uint32_t)p[3] << 24); }

/* melonDS reads and writes a firmware's user settings (two 256-byte copies)
 * at header[0x20]*8, its Wi-Fi access points 0x400 below them and, on a DSi
 * firmware, the extended ones 0xA00 below: it trusts that offset. An image
 * whose offset puts any of them outside the image would have melonDS write
 * past it; every real dump keeps them inside (DS 0x3FE00, DSi 0x1FE00,
 * iQue 0x7FE00), so only such an image is refused. */
bool firmware_layout_ok(const uint8_t* fw, uint32_t len)
{
    uint32_t user = (uint32_t)rd16(fw + 0x20) << 3;
    return user >= 0xA00 && user + 0x200 <= len;
}

/* melonDS's own test (NDSCartSlot::SetCart): a secure area that is
 * decrypted gets re-encrypted as the cart goes in. */
bool secure_area_decrypted(const uint8_t* rom, uint32_t len)
{
    uint32_t off = rd32(rom + 0x20);
    if (off < 0x4000 || off >= 0x8000 || off + 0x14 > len) return false;
    return rd32(rom + off) == 0xE7FFDEFFu && rd32(rom + off + 0x10) != 0xE7FFDEFFu;
}

/* Puts what pa_set_bios asked for into the DS. A cart that is already in
 * carries a secure area melonDS re-encrypted, as it went in, with the Key1
 * table of the ARM7 BIOS then in (a known dump's, else zeros), and direct
 * boot decrypts it with the one in at boot: when the ARM7 BIOS changes
 * under a cart, the area is decrypted with the old one and the cart goes in
 * again under the new one, as a cart inserted after it would. */
void install_bios()
{
    if (!bios_pending || !nds) return;
    bios_pending = false;

    ARM9BIOSImage arm9 = FreeBIOSGetNtrArm9();
    if (!own_arm9.empty()) memcpy(arm9.data(), own_arm9.data(), arm9.size());
    ARM7BIOSImage arm7 = FreeBIOSGetNtrArm7();
    if (!own_arm7.empty()) memcpy(arm7.data(), own_arm7.data(), arm7.size());

    std::unique_ptr<NDSCart::CartCommon> cart;
    if (nds->CartInserted() && arm7 != nds->GetARM7BIOS()) {
        if (cart_area_rekeyed) {
            NDSCart::CartCommon* c = nds->NDSCartSlot.GetCart();
            u8 area[0x800];
            nds->NDSCartSlot.DecryptSecureArea(area); /* the first 8 bytes come back E7FFDEFF, as in the dump */
            memcpy(const_cast<u8*>(c->GetROM()) + c->GetHeader().ARM9ROMOffset, area, sizeof(area));
        }
        cart = nds->EjectCart();
    }
    nds->SetARM9BIOS(arm9);
    nds->SetARM7BIOS(arm7);
    if (cart) nds->SetNDSCart(std::move(cart));
    nds->SetFirmware(own_fw.empty() ? Firmware(0) : Firmware(own_fw.data(), (u32)own_fw.size()));
    own_in_ds[0] = !own_arm9.empty();
    own_in_ds[1] = !own_arm7.empty();
    own_in_ds[2] = !own_fw.empty();
    cached_state_size = 0;
}

} // namespace

/* ======================= Platform, for Emscripten ======================= */
namespace melonDS::Platform {

void SignalStop(StopReason reason, void* userdata) { (void)userdata; stop_reason = (int)reason; }

/* No file system (-sFILESYSTEM=0): nothing the core wants from disk exists.
 * It copes — BIOS and firmware come from memory, the cart from pa_load_rom. */
std::string GetLocalFilePath(const std::string& filename) { return filename; }
FileHandle* OpenFile(const std::string& path, FileMode mode) { (void)path; (void)mode; return nullptr; }
FileHandle* OpenLocalFile(const std::string& path, FileMode mode) { (void)path; (void)mode; return nullptr; }
bool FileExists(const std::string& name) { (void)name; return false; }
bool LocalFileExists(const std::string& name) { (void)name; return false; }
bool CheckFileWritable(const std::string& filepath) { (void)filepath; return false; }
bool CheckLocalFileWritable(const std::string& filepath) { (void)filepath; return false; }
bool CloseFile(FileHandle* file) { (void)file; return false; }
bool IsEndOfFile(FileHandle* file) { (void)file; return true; }
bool FileReadLine(char* str, int count, FileHandle* file) { (void)str; (void)count; (void)file; return false; }
u64 FilePosition(FileHandle* file) { (void)file; return 0; }
bool FileSeek(FileHandle* file, s64 offset, FileSeekOrigin origin) { (void)file; (void)offset; (void)origin; return false; }
void FileRewind(FileHandle* file) { (void)file; }
u64 FileRead(void* data, u64 size, u64 count, FileHandle* file) { (void)data; (void)size; (void)count; (void)file; return 0; }
bool FileFlush(FileHandle* file) { (void)file; return false; }
u64 FileWrite(const void* data, u64 size, u64 count, FileHandle* file) { (void)data; (void)size; (void)count; (void)file; return 0; }
u64 FileWriteFormatted(FileHandle* file, const char* fmt, ...) { (void)file; (void)fmt; return 0; }
u64 FileLength(FileHandle* file) { (void)file; return 0; }

/* Warnings and errors reach the page's console (Module.printErr); the rest is dropped. */
void Log(LogLevel level, const char* fmt, ...)
{
    if (level < LogLevel::Warn) return;
    va_list args;
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);
}

/* Single-threaded: the only thread melonDS would start is the threaded 3D
 * renderer's, and it is never asked for. Semaphores count without blocking
 * (nothing could ever post from elsewhere); mutexes are free. */
Thread* Thread_Create(std::function<void()> func) { (void)func; Log(LogLevel::Error, "pa: Thread_Create refused\n"); return nullptr; }
void Thread_Free(Thread* thread) { (void)thread; }
void Thread_Wait(Thread* thread) { (void)thread; }

Semaphore* Semaphore_Create() { return (Semaphore*)new Sema{0}; }
void Semaphore_Free(Semaphore* sema) { delete (Sema*)sema; }
void Semaphore_Reset(Semaphore* sema) { ((Sema*)sema)->count = 0; }
void Semaphore_Wait(Semaphore* sema) { Sema* s = (Sema*)sema; if (s->count > 0) s->count--; }
bool Semaphore_TryWait(Semaphore* sema, int timeout_ms)
{
    (void)timeout_ms;
    Sema* s = (Sema*)sema;
    if (s->count <= 0) return false;
    s->count--;
    return true;
}
void Semaphore_Post(Semaphore* sema, int count) { ((Sema*)sema)->count += count; }

Mutex* Mutex_Create() { return (Mutex*)new Mtx{0}; }
void Mutex_Free(Mutex* mutex) { delete (Mtx*)mutex; }
void Mutex_Lock(Mutex* mutex) { (void)mutex; }
void Mutex_Unlock(Mutex* mutex) { (void)mutex; }
bool Mutex_TryLock(Mutex* mutex) { (void)mutex; return true; }

void Sleep(u64 usecs) { (void)usecs; }

/* Emulated time, never the wall clock: the same on every home. */
u64 GetMSCount() { return emu_ms(); }
u64 GetUSCount() { return emu_cycles * 1000000 / CYCLES_PER_SECOND; }

/* The cartridge save changed: the adapter reads pa_sram_dirty and exports pa_sram_ptr. */
void WriteNDSSave(const u8* savedata, u32 savelen, u32 writeoffset, u32 writelen, void* userdata)
{
    (void)savedata; (void)savelen; (void)writeoffset; (void)writelen; (void)userdata;
    sram_dirty = true;
}
void WriteGBASave(const u8* savedata, u32 savelen, u32 writeoffset, u32 writelen, void* userdata)
{
    (void)savedata; (void)savelen; (void)writeoffset; (void)writelen; (void)userdata;
}
void WriteFirmware(const Firmware& firmware, u32 writeoffset, u32 writelen, void* userdata)
{
    (void)firmware; (void)writeoffset; (void)writelen; (void)userdata;
}
/* A game set the clock: the emulated RTC already holds it; nothing to persist. */
void WriteDateTime(int year, int month, int day, int hour, int minute, int second, void* userdata)
{
    (void)year; (void)month; (void)day; (void)hour; (void)minute; (void)second; (void)userdata;
}

void MP_Begin(void* userdata) { (void)userdata; mp_active = true; }
void MP_End(void* userdata) { (void)userdata; mp_active = false; }
int MP_SendPacket(u8* data, int len, u64 timestamp, void* userdata) { (void)userdata; return mp_send(0, 0, data, len, timestamp); }
int MP_RecvPacket(u8* data, u64* timestamp, void* userdata) { (void)userdata; return mp_recv(data, timestamp); }
int MP_SendCmd(u8* data, int len, u64 timestamp, void* userdata) { (void)userdata; return mp_send(1, 0, data, len, timestamp); }
int MP_SendReply(u8* data, int len, u64 timestamp, u16 aid, void* userdata) { (void)userdata; return mp_send(2, aid, data, len, timestamp); }
int MP_SendAck(u8* data, int len, u64 timestamp, void* userdata) { (void)userdata; return mp_send(3, 0, data, len, timestamp); }
int MP_RecvHostPacket(u8* data, u64* timestamp, void* userdata) { (void)userdata; return mp_recv(data, timestamp); }
/* Replies land where melonDS's LocalMP puts them: 1 KB per AID, from AID 1. */
u16 MP_RecvReplies(u8* data, u64 timestamp, u16 aidmask, void* userdata)
{
    (void)timestamp; (void)userdata;
    u16 ret = 0;
    while (!mp_rx_replies.empty()) {
        std::vector<uint8_t> f = std::move(mp_rx_replies.front());
        mp_rx_replies.pop_front();
        int len = rd16(&f[10]);
        u16 aid = rd16(&f[8]);
        if (len && aid >= 1 && aid <= 15 && len <= 1024) {
            memcpy(&data[(aid - 1) * 1024], &f[MP_HEADER], (size_t)len);
            ret |= (u16)(1 << aid);
        }
        if ((ret & aidmask) == aidmask) break;
    }
    return ret;
}

/* No internet: the DS sees no access point. */
int Net_SendPacket(u8* data, int len, void* userdata) { (void)data; (void)len; (void)userdata; return 0; }
int Net_RecvPacket(u8* data, void* userdata) { (void)data; (void)userdata; return 0; }

/* DSi cameras: never asked for on a DS; black if they were. */
void Camera_Start(int num, void* userdata) { (void)num; (void)userdata; }
void Camera_Stop(int num, void* userdata) { (void)num; (void)userdata; }
void Camera_CaptureFrame(int num, u32* frame, int width, int height, bool yuv, void* userdata)
{
    (void)num; (void)yuv; (void)userdata;
    if (frame && width > 0 && height > 0) memset(frame, 0, (size_t)width * (size_t)height * 4);
}

/* Microphone: samples the page pushed (pa_push_mic), else a synthesised
 * blow while pa_set_mic_blow(1), else nothing (the DS hears silence). */
void Mic_Start(void* userdata) { (void)userdata; }
void Mic_Stop(void* userdata) { (void)userdata; }
int Mic_ReadInput(s16* data, int maxlength, void* userdata)
{
    (void)userdata;
    if (maxlength <= 0) return 0;
    int n = 0;
    while (n < maxlength && mic_r != mic_w) {
        data[n++] = mic_ring[mic_r];
        mic_r = (mic_r + 1) % MIC_RING;
    }
    if (n) return n;
    if (!mic_blow_on) return 0;
    const unsigned blow_len = sizeof(mic_blow) / sizeof(mic_blow[0]);
    for (; n < maxlength; n++) {
        data[n] = mic_blow[blow_pos];
        blow_pos = (blow_pos + 1) % blow_len;
    }
    return n;
}

/* DSi AAC decoding (DSP HLE): not provided. */
AACDecoder* AAC_Init() { return nullptr; }
void AAC_DeInit(AACDecoder* dec) { (void)dec; }
bool AAC_Configure(AACDecoder* dec, int frequency, int channels) { (void)dec; (void)frequency; (void)channels; return false; }
bool AAC_DecodeFrame(AACDecoder* dec, const void* input, int inputlen, void* output, int outputlen)
{
    (void)dec; (void)input; (void)inputlen; (void)output; (void)outputlen;
    return false;
}

/* Add-ons: no guitar grip; the Rumble Pak is latched for pa_rumble; the
 * Motion Pak reads a console at rest (what melonDS's frontend reports
 * without a sensor). */
bool Addon_KeyDown(KeyType type, void* userdata) { (void)type; (void)userdata; return false; }
void Addon_RumbleStart(u32 len, void* userdata)
{
    (void)userdata;
    rumbling = true;
    rumble_until_ms = emu_ms() + len;
}
void Addon_RumbleStop(void* userdata) { (void)userdata; rumbling = false; }
float Addon_MotionQuery(MotionQueryType type, void* userdata) { (void)type; (void)userdata; return 0.0f; }

DynamicLibrary* DynamicLibrary_Load(const char* lib) { (void)lib; return nullptr; }
void DynamicLibrary_Unload(DynamicLibrary* lib) { (void)lib; }
void* DynamicLibrary_LoadFunction(DynamicLibrary* lib, const char* name) { (void)lib; (void)name; return nullptr; }

} // namespace melonDS::Platform

/* ============================= the C ABI ================================ */

/* A DS with FreeBIOS and generated firmware, sound resampled to `rate` Hz
 * (48000 unless the page says otherwise). Loses any loaded cart, and any
 * BIOS or firmware pa_set_bios gave. */
EXPORT int pa_init(int rate)
{
    nds.reset();
    sample_rate = rate > 0 ? rate : 48000;
    NDSArgs args;
    args.JIT = std::nullopt;
    args.GDB = std::nullopt;
    args.BitDepth = AudioBitDepth::Auto;
    args.Interpolation = AudioInterpolation::None;
    args.OutputSampleRate = (double)sample_rate;
    args.Renderer = nullptr; /* melonDS falls back to its software renderer */
    nds = std::make_unique<NDS>(std::move(args), nullptr);
    RendererSettings settings {};
    settings.ScaleFactor = 1;
    settings.Threaded = false;
    settings.HiresCoordinates = false;
    settings.BetterPolygons = false;
    nds->GetRenderer().SetRenderSettings(settings);
    memset(fb, 0, sizeof(fb));
    emu_cycles = 0;
    keys = 0xFFF;
    touch_down = false;
    lid_closed = false;
    sram_dirty = false;
    mic_r = mic_w = 0;
    blow_pos = 0;
    rumbling = false;
    stop_reason = -1;
    cached_state_size = 0;
    mp_tx.clear();
    mp_rx_packets.clear();
    mp_rx_replies.clear();
    own_arm9.clear();
    own_arm7.clear();
    own_fw.clear();
    bios_pending = false;
    own_in_ds[0] = own_in_ds[1] = own_in_ds[2] = false;
    cart_area_rekeyed = false;
    return 0;
}

/* Inserts a cart. Retail carts get the save type melonDS's ROM list knows
 * (EEPROM 64 K when unknown); homebrew gets none. The ROM is copied. A
 * BIOS pa_set_bios gave goes into the DS first, as melonDS's own frontend
 * installs the BIOS before it inserts the cart. */
EXPORT int pa_load_rom(const uint8_t* rom, uint32_t len)
{
    if (!nds || !rom || len < 0x1000) return -1;
    std::unique_ptr<NDSCart::CartCommon> cart = NDSCart::ParseROM(rom, len, nullptr, std::nullopt);
    if (!cart) return -2;
    if (bios_pending) {
        nds->EjectCart(); /* the old cart is going anyway: no need to carry it across */
        install_bios();
    }
    cart_area_rekeyed = secure_area_decrypted(rom, len);
    nds->SetNDSCart(std::move(cart));
    sram_dirty = false;
    cached_state_size = 0;
    return 0;
}

/* The player's own DS BIOS and firmware, read from their own files. Each
 * part given as 0/0 stays melonDS's: FreeBIOS for a BIOS, the generated
 * firmware for the firmware. The sizes are the ones melonDS's frontend
 * accepts: ARM9 BIOS 4 KiB, ARM7 BIOS 16 KiB, firmware 128, 256 or 512 KiB.
 * Taken by the DS when the next cart goes in or at the next power-on, which
 * stays a direct boot. Returns 0; or, with nothing changed, -1 the ARM9
 * BIOS's size, -2 the ARM7 BIOS's, -3 the firmware's, -4 a firmware whose
 * user settings lie outside it (melonDS would write past the image). */
EXPORT int pa_set_bios(const uint8_t* arm9, uint32_t arm9_len, const uint8_t* arm7, uint32_t arm7_len,
                       const uint8_t* fw, uint32_t fw_len)
{
    if (arm9_len && (!arm9 || arm9_len != ARM9BIOSSize)) return -1;
    if (arm7_len && (!arm7 || arm7_len != ARM7BIOSSize)) return -2;
    if (fw_len) {
        bool sized = false;
        for (u32 size : FIRMWARE_SIZES) sized = sized || fw_len == size;
        if (!fw || !sized) return -3;
        if (!firmware_layout_ok(fw, fw_len)) return -4;
    }
    if (arm9_len) own_arm9.assign(arm9, arm9 + arm9_len); else own_arm9.clear();
    if (arm7_len) own_arm7.assign(arm7, arm7 + arm7_len); else own_arm7.clear();
    if (fw_len) own_fw.assign(fw, fw + fw_len); else own_fw.clear();
    /* Back to melonDS's own on a DS that already runs them: nothing to do. */
    bool none = own_arm9.empty() && own_arm7.empty() && own_fw.empty();
    bios_pending = !(none && !own_in_ds[0] && !own_in_ds[1] && !own_in_ds[2]);
    return 0;
}

/* What the DS runs now, as bits: 1 the ARM9 BIOS is the player's, 2 the ARM7
 * BIOS is, 4 the firmware is; 8 the ARM9 BIOS is the dump melonDS knows by
 * its CRC32, 16 the ARM7 BIOS is; 32 the firmware is one melonDS could boot
 * (a whole DS firmware: not generated, not 128 KiB); 64 a pa_set_bios is
 * waiting for the next cart or power-on. 0 before pa_init. */
EXPORT uint32_t pa_bios_info()
{
    if (!nds) return 0;
    uint32_t bits = 0;
    if (own_in_ds[0]) bits |= 1;
    if (own_in_ds[1]) bits |= 2;
    if (own_in_ds[2]) bits |= 4;
    if (nds->IsLoadedARM9BIOSKnownNative()) bits |= 8;
    if (nds->IsLoadedARM7BIOSKnownNative()) bits |= 16;
    if (nds->GetFirmware().IsBootable()) bits |= 32;
    if (bios_pending) bits |= 64;
    return bits;
}

/* The firmware's user: `name` is UTF-8, up to 10 characters; `language` is
 * melonDS's Firmware::Language (0 Japanese, 1 English, 2 French, 3 German,
 * 4 Italian, 5 Spanish, 6 Chinese). Applied at the next power-on. */
EXPORT void pa_set_user(const char* name, int language)
{
    user_name_len = 0;
    const unsigned char* p = (const unsigned char*)(name ? name : "");
    while (*p && user_name_len < 10) {
        uint32_t cp;
        int extra;
        if (*p < 0x80) { cp = *p; extra = 0; }
        else if ((*p & 0xE0) == 0xC0) { cp = *p & 0x1F; extra = 1; }
        else if ((*p & 0xF0) == 0xE0) { cp = *p & 0x0F; extra = 2; }
        else { cp = '?'; extra = 0; p++; while ((*p & 0xC0) == 0x80) p++; user_name[user_name_len++] = (char16_t)cp; continue; }
        p++;
        for (int i = 0; i < extra; i++) {
            if ((*p & 0xC0) != 0x80) { cp = '?'; break; }
            cp = (cp << 6) | (*p++ & 0x3F);
        }
        user_name[user_name_len++] = (char16_t)cp;
    }
    user_language = (language >= 0 && language <= 6) ? language : Firmware::Language::English;
    user_set = true;
}

/* The session clock: the RTC reads this at power-on, then keeps emulated time. */
EXPORT void pa_set_clock(double unix_seconds)
{
    clock_set = true;
    clock_seconds = (int64_t)unix_seconds;
    if (nds && nds->IsRunning()) apply_clock();
}

/* Power on with the inserted cart: a direct boot (FreeBIOS cannot boot the
 * firmware, and a player's own BIOS boots the same way), the game running
 * at once. The cartridge save is kept. A BIOS pa_set_bios gave since the
 * cart went in is taken now. */
EXPORT int pa_power_on()
{
    if (!nds || !nds->CartInserted()) return -1;
    install_bios();
    nds->Reset();
    nds->SPI.GetPowerMan()->SetBatteryLevelOkay(true);
    apply_user();
    apply_clock();
    nds->SetupDirectBoot("game.nds");
    nds->Start();
    apply_inputs();
    nds->SPU.DrainOutput();
    memset(fb, 0, sizeof(fb));
    stop_reason = -1;
    rumbling = false;
    mp_tx.clear();
    mp_rx_packets.clear();
    mp_rx_replies.clear();
    return 0;
}

EXPORT int pa_reset() { return pa_power_on(); }

EXPORT void pa_set_keys(uint32_t mask12)
{
    keys = mask12 & 0xFFF;
    if (nds) nds->SetKeyMask(keys);
}

/* Pen on the bottom screen, in its pixels (0..255, 0..191). */
EXPORT void pa_set_touch(int x, int y, int down)
{
    touch_down = down != 0;
    touch_x = x < 0 ? 0 : x > 255 ? 255 : x;
    touch_y = y < 0 ? 0 : y > 191 ? 191 : y;
    if (!nds) return;
    if (touch_down) nds->TouchScreen((u16)touch_x, (u16)touch_y);
    else nds->ReleaseScreen();
}

EXPORT void pa_set_lid(int closed)
{
    lid_closed = closed != 0;
    if (nds) nds->SetLidClosed(lid_closed);
}

EXPORT void pa_set_mic_blow(int on) { mic_blow_on = on != 0; if (!on) blow_pos = 0; }

/* Mono s16 at 47.6 kHz into the mic ring; returns how many were taken. */
EXPORT int pa_push_mic(const int16_t* samples, int n)
{
    int taken = 0;
    while (taken < n) {
        unsigned next = (mic_w + 1) % MIC_RING;
        if (next == mic_r) break; /* full */
        mic_ring[mic_w] = samples[taken++];
        mic_w = next;
    }
    return taken;
}

/* One frame: 560190 system cycles. Returns the scanlines drawn (263 is a
 * full frame), or -1 with nothing powered on. */
EXPORT int pa_run_frame()
{
    if (!nds || !nds->IsRunning()) return -1;
    u32 lines = nds->RunFrame();
    emu_cycles += CYCLES_PER_FRAME;
    if (rumbling && emu_ms() >= rumble_until_ms) rumbling = false;
    copy_screens();
    return (int)lines;
}

EXPORT const uint32_t* pa_fb_top() { return fb[0]; }
EXPORT const uint32_t* pa_fb_bottom() { return fb[1]; }

/* Stereo s16 frames at pa_audio_rate(); returns the frames written. */
EXPORT int pa_read_audio(int16_t* dst, int max_frames)
{
    if (!nds || max_frames <= 0) return 0;
    return nds->SPU.ReadOutput(dst, max_frames);
}

EXPORT int pa_audio_rate() { return sample_rate; }
EXPORT uint32_t pa_frame_rate() { return FRAME_RATE_UHZ; }

/* melonDS's own save states (they carry the cartridge save). A state's size
 * is fixed for a given cart, so it is measured once, by taking one. */
EXPORT uint32_t pa_state_size()
{
    if (!nds || !nds->IsRunning()) return 0;
    if (!cached_state_size) cached_state_size = snapshot_size();
    return cached_state_size;
}

/* Writes the state into dst (at most `max` bytes); returns its length, or
 * -1 when dst is too small or nothing is running. */
EXPORT int pa_save_state(uint8_t* dst, uint32_t max)
{
    if (!nds || !nds->IsRunning() || !dst) return -1;
    Savestate s(dst, max, true);
    if (s.Error) return -1;
    if (!nds->DoSavestate(&s) || s.Error) return -1;
    return (int)s.Length();
}

/* `len` must be the state's own length (melonDS checks it). The inputs the
 * page last set are re-applied: KeyInput is not part of a state. */
EXPORT int pa_load_state(const uint8_t* src, uint32_t len)
{
    if (!nds || !nds->IsRunning() || !src) return -1;
    Savestate s((void*)src, len, false);
    if (s.Error) return -2;
    if (!nds->DoSavestate(&s) || s.Error) return -3;
    apply_inputs();
    nds->SPU.DrainOutput();
    copy_screens();
    return 0;
}

/* What two homes compare, XXH3 folded to 32 bits: main RAM and both CPUs'
 * registers; the ARM7's own WRAM and the shared WRAM, where the ARM7's
 * program and the sound and wireless drivers live; and the Wi-Fi chip — its
 * RAM, registers and timers, as melonDS saves them — where local wireless
 * lives. A desync in any of them shows here before it reaches main RAM. */
static uint8_t wifi_digest_scratch[64 * 1024]; /* Wifi::DoSavestate writes about 38 KB */

EXPORT uint32_t pa_digest()
{
    if (!nds) return 0;
    XXH3_state_t* st = XXH3_createState();
    XXH3_64bits_reset(st);
    XXH3_64bits_update(st, nds->MainRAM, nds->MainRAMMask + 1);
    XXH3_64bits_update(st, nds->ARM9.R, sizeof(nds->ARM9.R));
    XXH3_64bits_update(st, &nds->ARM9.CPSR, sizeof(nds->ARM9.CPSR));
    XXH3_64bits_update(st, nds->ARM7.R, sizeof(nds->ARM7.R));
    XXH3_64bits_update(st, &nds->ARM7.CPSR, sizeof(nds->ARM7.CPSR));
    XXH3_64bits_update(st, nds->ARM7WRAM, nds->ARM7WRAMSize);
    XXH3_64bits_update(st, nds->SharedWRAM, nds->SharedWRAMSize);
    {
        /* The chip's RAM and registers are its own; saving them is the one
         * public way to read them without a read's side effects. */
        Savestate wifi(wifi_digest_scratch, sizeof(wifi_digest_scratch), true);
        if (!wifi.Error) nds->Wifi.DoSavestate(&wifi);
        if (!wifi.Error) XXH3_64bits_update(st, wifi_digest_scratch, wifi.Length());
    }
    uint64_t h = XXH3_64bits_digest(st);
    XXH3_freeState(st);
    return (uint32_t)(h ^ (h >> 32));
}

/* The cartridge save (EEPROM/flash/NAND image), the raw .sav the DS writes.
 * The pointer is valid until the next pa_load_rom or pa_init. */
EXPORT uint8_t* pa_sram_ptr() { return nds ? nds->GetNDSSave() : nullptr; }
EXPORT uint32_t pa_sram_size() { return nds ? nds->GetNDSSaveLength() : 0; }
/* 1 if the game wrote its save since the last call; clears the flag. */
EXPORT int pa_sram_dirty()
{
    int d = sram_dirty ? 1 : 0;
    sram_dirty = false;
    return d;
}
/* Loads a .sav into the cart (after pa_load_rom, before or after power-on). */
EXPORT int pa_load_sram(const uint8_t* src, uint32_t len)
{
    if (!nds || !nds->CartInserted() || !src) return -1;
    nds->SetNDSSave(src, len);
    sram_dirty = false;
    return 0;
}

/* 1 while the Rumble Pak would be rumbling. */
EXPORT int pa_rumble() { return rumbling ? 1 : 0; }

/* -1 while running; else why the console stopped (Platform::StopReason:
 * 1 external, 2 GBA mode, 3 bad exception region, 4 the DS powered off). */
EXPORT int pa_stop_reason() { return stop_reason; }

/* ---- local multiplayer (see "in-process queues" above) ---------------- */
EXPORT void pa_mp_set_instance(int instance) { mp_instance = instance & 0xF; }

/* A frame for this DS, in the queue format; returns 0, or -1 if malformed. */
EXPORT int pa_mp_push_rx(const uint8_t* frame, int len)
{
    if (!frame || len < MP_HEADER) return -1;
    uint32_t magic = frame[0] | (frame[1] << 8) | (frame[2] << 16) | ((uint32_t)frame[3] << 24);
    int payload = rd16(&frame[10]);
    if (magic != MP_MAGIC || payload > MP_PAYLOAD_MAX || MP_HEADER + payload != len) return -1;
    std::vector<uint8_t> f(frame, frame + len);
    if (rd16(&frame[6]) == 2) mp_rx_replies.push_back(std::move(f));
    else mp_rx_packets.push_back(std::move(f));
    return 0;
}

/* The next frame this DS sent, or 0 when there is none (-1: dst too small,
 * the frame is dropped). */
EXPORT int pa_mp_pop_tx(uint8_t* dst, int max)
{
    if (mp_tx.empty()) return 0;
    std::vector<uint8_t> f = std::move(mp_tx.front());
    mp_tx.pop_front();
    if (!dst || (int)f.size() > max) return -1;
    memcpy(dst, f.data(), f.size());
    return (int)f.size();
}
