#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mem.h"
#include "xtensa.h"
uint32_t image_load(const char *path);
uint32_t flash_boot_load(const char *path);
uint32_t flash_image_load(const char *path);
void elf_load(const char *path);
extern uint32_t g_last_read, g_last_write;
extern uint64_t g_ticks;   // monotonic system time driving SYSTIMER (advanced below)
int g_mspi_dbg = 0;   // set to 1 to trace MSPI flash/PSRAM transactions on stderr

// --- PC-sampling profiler (env PROF=1): histogram every executed app PC, dump the
// hottest at exit so we can see where the emulated interpreter burns Xtensa cycles.
#define PROF_N (1u<<21)
static struct prof_e { uint32_t pc, cnt; } *g_prof[2];
static int g_prof_on;
static inline void prof_hit(int core, uint32_t pc){
    struct prof_e *t = g_prof[core];
    uint32_t h = (pc * 2654435761u) & (PROF_N - 1);
    for (int i = 0; i < 128; i++) { uint32_t j = (h + i) & (PROF_N - 1);
        if (t[j].cnt == 0) { t[j].pc = pc; t[j].cnt = 1; return; }
        if (t[j].pc == pc) { t[j].cnt++; return; } }
}
static int prof_cmp(const void *a, const void *b){
    uint32_t ca=((const struct prof_e*)a)->cnt, cb=((const struct prof_e*)b)->cnt;
    return ca<cb?1:ca>cb?-1:0;
}
static void prof_dump(void){
    if (!g_prof_on) return;
    for (int core=0; core<2; core++) {
        qsort(g_prof[core], PROF_N, sizeof(struct prof_e), prof_cmp);
        uint64_t tot=0; for (uint32_t i=0;i<PROF_N;i++) tot += g_prof[core][i].cnt;
        fprintf(stderr, "=== PROF core%d ALL PCs (samples %llu) ===\n", core, (unsigned long long)tot);
        for (uint32_t i=0; i<PROF_N && g_prof[core][i].cnt; i++)
            fprintf(stderr, "PROF%d %08x %u\n", core, g_prof[core][i].pc, g_prof[core][i].cnt);
    }
}

// Give a core a valid startup frame like the 2nd-stage bootloader would: a high
// DRAM stack (grows down) with headroom, and a root window marked as a call8 frame
// (a0[31:30]=CALLINC) so it spills correctly when the deep ROM call chain wraps
// all 16 register windows. The two cores use separate stacks.
static void seed_core(xtensa_t *c, uint32_t entry, int core_id, uint32_t sp) {
    xt_reset(c, entry);
    c->core_id = core_id;
    xt_set_a(c, 1, sp);
    xt_set_a(c, 0, 0x80000000);
}

int emu_run(int argc, char **argv) {
    if (argc < 2) { fprintf(stderr, "usage: %s <app.bin> [maxsteps] [trace] [tracestart]\n", argv[0]); return 1; }
    long maxsteps = argc > 2 ? atol(argv[2]) : 200;
    int trace = argc > 3;
    long tracestart = argc > 4 ? atol(argv[4]) : 0;
    mem_init();
    elf_load("/Users/l/Developer/Lewpen/Hardware/Waveshare/33691 - ESP32-S3 1.75inch AMOLED Round Touch Display Development Board/.tooling/espressif/tools/esp-rom-elfs/20241011/esp32s3_rev0_rom.elf");
    // FAITHFUL boot: raw flash image + start at the mask-ROM reset vector, so the
    // real 1st-stage ROM loader, 2nd-stage bootloader and app all run — the ROM
    // fills in its own globals, the bootloader sets clocks/MMU and loads the app.
    void rom_data_reconstruct(void); rom_data_reconstruct();  // fill in the .data blob the ROM ELF omits
    // A 32 MB argument is a full flash dump (boot it wholesale); anything smaller
    // is an app .bin with sibling bootloader/partition-table (the 3-file path).
    uint32_t entry = flash_image_load(argv[1]);

    static xtensa_t cpu0, cpu1;
    seed_core(&cpu0, entry, 0, 0x3fceb700);   // PRO CPU (ROM resets its own stack)
    int cpu1_up = 0;
    g_prof_on = getenv("PROF") != 0;
    if (g_prof_on) { g_prof[0]=calloc(PROF_N,sizeof(struct prof_e)); g_prof[1]=calloc(PROF_N,sizeof(struct prof_e)); }

    // Display: the CO5300 frame memory is filled from the SPI2 QSPI transactions
    // (mmio.c -> co5300_spi2_xfer); we snapshot it here. A face-advance request
    // (env or signal) pokes the AXP2101 PWR-key status so the app cycles faces.
    void co5300_dump_ppm(const char *);
    const char *dumppath = getenv("WC_DUMP") ? getenv("WC_DUMP") : "/tmp/woodclock.ppm";

    uint32_t lo = 0xffffffff, hi = 0; long win = 0;
    long n = 0;
    for (; n < maxsteps && !cpu0.halted; n++) {
        // Soft reset (esp_restart -> RTC_CNTL SW_SYS_RST): re-run the boot from the ROM
        // reset vector. Flash + the RTC boot-hint persist, so the custom bootloader boots
        // the app the menu just cached into `storage`. This closes the menu->launch loop.
        { extern int g_reboot_req; void mmio_reboot(void);
          if (g_reboot_req) { g_reboot_req = 0; printf("=== soft reset: re-running boot ===\n");
            mmio_reboot(); g_core1_start_req = 0; cpu1_up = 0;
            seed_core(&cpu0, entry, 0, 0x3fceb700); continue; } }
        if (trace && n >= tracestart)
            printf("%6ld [0] pc=%08x a0=%08x a1=%08x wb=%u ws=%04x vb=%08x ps=%05x\n",
                   n, cpu0.pc, xt_a(&cpu0,0), xt_a(&cpu0,1), cpu0.windowbase,
                   cpu0.windowstart, cpu0.vecbase, cpu0.ps);
        // Bring the APP CPU online once core 0 has released it.
        if (!cpu1_up && g_core1_start_req) {
            seed_core(&cpu1, g_core1_entry, 1, 0x3fce4000);   // APP CPU, separate stack
            cpu1_up = 1;
        }
        uint32_t p = cpu0.pc;
        if (p < lo) lo = p; if (p > hi) hi = p;
        if (++win >= 40000000) {
            if (hi - lo < 64) {
                printf("STUCK loop pc~%08x (range %u) last MMIO r=%08x w=%08x after %ld steps%s\n",
                       cpu0.pc, hi - lo, g_last_read, g_last_write, n, cpu1_up ? " [smp]" : "");
                return 0;
            }
            lo = 0xffffffff; hi = 0; win = 0;
        }
        if (trace && n >= tracestart && cpu1_up)
            printf("       [1] pc=%08x a2=%08x a6=%08x wb=%u ps=%05x\n",
                   cpu1.pc, xt_a(&cpu1,2), xt_a(&cpu1,6), cpu1.windowbase, cpu1.ps);        if ((n & 0x3fffff) == 0) co5300_dump_ppm(dumppath);
        g_ticks++;                                     // advance system time (SYSTIMER source)
        // Test touch injection (TOUCHTEST=1): press a fixed point after boot to verify GT911.
        { extern int g_touch_down, g_touch_x, g_touch_y;
          static int tt = -1; if (tt < 0) tt = getenv("TOUCHTEST") ? 1 : 0;
          if (tt && n > 40000000) { g_touch_down = 1; g_touch_x = 270; g_touch_y = 480; } }
        systimer_step();                               // fire tick-timer alarms -> interrupts
        // ring buffer of core0's last control-flow, dumped when it halts (abort forensics; RB=1)
        static int rb_on = -1; if (rb_on < 0) rb_on = getenv("RB") ? 1 : 0;
        static uint32_t rb_pc[128], rb_a0[128], rb_a1[128], rb_ps[128]; static int rb_i;
        if (rb_on) { rb_pc[rb_i&127]=cpu0.pc; rb_a0[rb_i&127]=xt_a(&cpu0,0); rb_a1[rb_i&127]=xt_a(&cpu0,1); rb_ps[rb_i&127]=cpu0.ps; rb_i++; }
        static int bw = -1; if (bw < 0) bw = getenv("BPW") ? 1 : 0;
        uint32_t bwpc = cpu0.pc, bwp0 = bw ? mem_r32(0x3fccc8d4) : 0, bwp1 = bw ? mem_r32(0x3fccc8d8) : 0;
        if (bw && cpu0.pc == 0x42009784u)   // esp_vfs_register_fs entry (does strlen(base_path))
            fprintf(stderr, "BPW register_fs @cyc=%llu base[0..7]=%08x %08x\n",
                    (unsigned long long)cpu0.cycles, mem_r32(0x3fccc8d4), mem_r32(0x3fccc8d8));
        xt_step(&cpu0);
        if (bw && (mem_r32(0x3fccc8d4) != bwp0 || mem_r32(0x3fccc8d8) != bwp1))
            fprintf(stderr, "BPW write pc=%08x cyc=%llu -> %08x %08x\n", bwpc,
                    (unsigned long long)cpu0.cycles, mem_r32(0x3fccc8d4), mem_r32(0x3fccc8d8));
        if (cpu0.halted && rb_on) {
            fprintf(stderr,"=== core0 last 128 steps before halt ===\n");
            for (int k=0;k<128;k++){ int j=(rb_i+k)&127;
                fprintf(stderr,"  pc=%08x a0=%08x a1=%08x ps=%05x\n", rb_pc[j], rb_a0[j], rb_a1[j], rb_ps[j]); }
        }
        if (cpu1_up && !cpu1.halted) xt_step(&cpu1);   // interleave the APP CPU
        if (g_prof_on) { prof_hit(0,cpu0.pc); if (cpu1_up) prof_hit(1,cpu1.pc); }
    }
    co5300_dump_ppm(dumppath);                         // final screen snapshot
    printf("final [0] pc=%08x cycles=%llu %s\n", cpu0.pc, (unsigned long long)cpu0.cycles,
           cpu0.halted ? cpu0.stopmsg : "(limit)");
    prof_dump();
    if (cpu1_up)
        printf("final [1] pc=%08x cycles=%llu %s\n", cpu1.pc, (unsigned long long)cpu1.cycles,
               cpu1.halted ? cpu1.stopmsg : "(running)");
    return 0;
}

#ifndef EMU_GUI     // CLI entry; the Cocoa GUI (gui.m) provides its own main() + calls emu_run.
int main(int argc, char **argv) { return emu_run(argc, argv); }
#endif
