#include <stdint.h>

#define REG_DISPCNT   (*(volatile uint16_t*)0x04000000)
#define REG_DISPSTAT  (*(volatile uint16_t*)0x04000004)
#define REG_VCOUNT    (*(volatile uint16_t*)0x04000006)
#define REG_KEYINPUT  (*(volatile uint16_t*)0x04000130)
#define REG_WAITCNT   (*(volatile uint16_t*)0x04000204)

#define REG_SOUNDCNT_L (*(volatile uint16_t*)0x04000080)
#define REG_SOUNDCNT_H (*(volatile uint16_t*)0x04000082)
#define REG_SOUNDCNT_X (*(volatile uint16_t*)0x04000084)
#define REG_FIFO_A     (*(volatile uint32_t*)0x040000A0)

#define REG_DMA1SAD   (*(volatile uint32_t*)0x040000BC)
#define REG_DMA1DAD   (*(volatile uint32_t*)0x040000C0)
#define REG_DMA1CNT   (*(volatile uint32_t*)0x040000C4)

#define REG_TM0CNT_L  (*(volatile uint16_t*)0x04000100)
#define REG_TM0CNT_H  (*(volatile uint16_t*)0x04000102)
#define REG_TM1CNT_L  (*(volatile uint16_t*)0x04000104)
#define REG_TM1CNT_H  (*(volatile uint16_t*)0x04000106)

#define VRAM_FB       ((uint16_t*)0x06000000)
#define SRAM_BASE     ((volatile uint8_t*)0x0E000000)

#define KEY_A      (1 << 0)
#define KEY_B      (1 << 1)
#define KEY_START  (1 << 3)
#define KEY_RIGHT  (1 << 4)
#define KEY_LEFT   (1 << 5)
#define KEY_R      (1 << 8)
#define KEY_L      (1 << 9)

typedef struct {
    uint32_t magic;               // "AGV1" = 0x31564741
    uint32_t total_frames;
    uint32_t vblanks_per_frame;   // e.g. 2 for 30fps, 3 for 20fps, 4 for 15fps
    uint32_t audio_rate;          // e.g. 10512
    uint32_t audio_per_vblank;    // e.g. 176 bytes
    uint32_t audio_offset;        // byte offset from 0x08000000
    uint32_t keyframe_interval;   // e.g. 20, 24, 30
    uint32_t seek_15s_frames;     // 15 * fps
    uint32_t seek_30s_frames;     // 30 * fps
    uint32_t timer0_reload;       // 0xF9C4 (65536 - 1596)
    uint32_t frame_offsets[1];    // bit 31 = keyframe flag, bits 0..30 = byte offset from 0x08000000
} AgvHeader;

// Embedded SRAM ID string so flashcarts & emulators allocate 32KB SRAM
__attribute__((used, aligned(4)))
const char sram_id_tag[] = "SRAM_V113\0\0\0";

static __attribute__((section(".iwram"), noinline))
void sram_write_u32(uint32_t offset, uint32_t val) {
    volatile uint8_t *p = SRAM_BASE + offset;
    p[0] = (uint8_t)(val & 0xFF);
    p[1] = (uint8_t)((val >> 8) & 0xFF);
    p[2] = (uint8_t)((val >> 16) & 0xFF);
    p[3] = (uint8_t)((val >> 24) & 0xFF);
}

static __attribute__((section(".iwram"), noinline))
uint32_t sram_read_u32(uint32_t offset) {
    volatile uint8_t *p = SRAM_BASE + offset;
    return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}

static __attribute__((section(".iwram"), noinline))
void save_bookmark(uint32_t frame) {
    sram_write_u32(0, 0x5449544E); // "TITN"
    sram_write_u32(4, frame);
    sram_write_u32(8, frame ^ 0xA5A5A5A5);
}

// Fast IWRAM decoder writing 32-bit pixel pairs directly to 0-waitstate VRAM (0x06000000)
__attribute__((section(".iwram"), noinline))
void decode_agv_frame(const uint8_t *frame_ptr, int is_keyframe) {
    const uint8_t *modes = frame_ptr;
    const uint16_t *payload = (const uint16_t *)(frame_ptr + 600);
    uint16_t last_color = 0;

    int mode_idx = 0;
    for (int cy = 0; cy < 160; cy += 4) {
        uint16_t *row_base = &VRAM_FB[cy * 240];
        for (int cx = 0; cx < 240; cx += 4, mode_idx++) {
            uint8_t m = (modes[mode_idx >> 2] >> ((mode_idx & 3) << 1)) & 3;
            uint32_t *dst32 = (uint32_t *)(row_base + cx);
            if (m == 0) {
                if (is_keyframe) {
                    uint32_t pair = (uint32_t)last_color | ((uint32_t)last_color << 16);
                    dst32[0]   = pair; dst32[1]   = pair;
                    dst32[120] = pair; dst32[121] = pair;
                    dst32[240] = pair; dst32[241] = pair;
                    dst32[360] = pair; dst32[361] = pair;
                }
                continue;
            } else if (m == 1) {
                uint16_t c = *payload++;
                last_color = c;
                uint32_t pair = (uint32_t)c | ((uint32_t)c << 16);
                dst32[0]   = pair; dst32[1]   = pair;
                dst32[120] = pair; dst32[121] = pair;
                dst32[240] = pair; dst32[241] = pair;
                dst32[360] = pair; dst32[361] = pair;
            } else if (m == 2) {
                uint32_t c0 = payload[0];
                uint32_t c1 = payload[1];
                uint32_t mask = payload[2];
                payload += 3;
                last_color = (uint16_t)c0;
                uint32_t lut[4] = {
                    c0 | (c0 << 16),
                    c1 | (c0 << 16),
                    c0 | (c1 << 16),
                    c1 | (c1 << 16)
                };
                dst32[0]   = lut[mask & 3];         dst32[1]   = lut[(mask >> 2) & 3];
                dst32[120] = lut[(mask >> 4) & 3];  dst32[121] = lut[(mask >> 6) & 3];
                dst32[240] = lut[(mask >> 8) & 3];  dst32[241] = lut[(mask >> 10) & 3];
                dst32[360] = lut[(mask >> 12) & 3]; dst32[361] = lut[(mask >> 14) & 3];
            } else {
                uint32_t c4[4];
                c4[0] = payload[0];
                c4[1] = payload[1];
                c4[2] = payload[2];
                c4[3] = payload[3];
                uint32_t m0 = payload[4];
                uint32_t m1 = payload[5];
                payload += 6;
                last_color = (uint16_t)c4[3];
                dst32[0]   = c4[m0 & 3]         | (c4[(m0 >> 2) & 3] << 16);
                dst32[1]   = c4[(m0 >> 4) & 3]  | (c4[(m0 >> 6) & 3] << 16);
                dst32[120] = c4[(m0 >> 8) & 3]  | (c4[(m0 >> 10) & 3] << 16);
                dst32[121] = c4[(m0 >> 12) & 3] | (c4[(m0 >> 14) & 3] << 16);
                dst32[240] = c4[m1 & 3]         | (c4[(m1 >> 2) & 3] << 16);
                dst32[241] = c4[(m1 >> 4) & 3]  | (c4[(m1 >> 6) & 3] << 16);
                dst32[360] = c4[(m1 >> 8) & 3] | (c4[(m1 >> 10) & 3] << 16);
                dst32[361] = c4[(m1 >> 12) & 3] | (c4[(m1 >> 14) & 3] << 16);
            }
        }
    }
}

static inline void wait_vblank(void) {
    while (REG_VCOUNT >= 160) {}
    while (REG_VCOUNT < 160) {}
}

// Start continuous DirectSound A DMA1 stream from ROM at the exact sample offset for `frame`
static __attribute__((section(".iwram"), noinline))
uint32_t start_continuous_audio(const int8_t *audio_base, uint32_t frame, uint32_t audio_rate, uint32_t fps, uint16_t tm0_reload) {
    REG_DMA1CNT = 0;
    REG_TM0CNT_H = 0;
    REG_TM1CNT_H = 0;

    uint32_t sample_off = (frame * audio_rate) / fps;
    uint32_t aligned_off = sample_off & ~3u;

    REG_SOUNDCNT_H = 0x0B0E; // DirectSound A 100%, L+R, Timer 0, FIFO reset
    REG_DMA1SAD = (uint32_t)(audio_base + aligned_off);
    REG_DMA1DAD = 0x040000A0;
    REG_DMA1CNT = 0xB6400004; // Continuous FIFO DMA1 from ROM

    REG_TM1CNT_L = 0;
    REG_TM1CNT_H = 0x0084;    // Timer 1 Cascade: counts exact audio samples played!
    REG_TM0CNT_L = tm0_reload;
    REG_TM0CNT_H = 0x0080;    // Start Timer 0 sample clock
    return aligned_off;
}

__attribute__((section(".iwram"), noreturn))
void player_main(void) {
    REG_WAITCNT = 0x4317; // Enable Game Pak prefetch + fast ROM waitstates
    REG_DISPCNT = 0x0403; // Mode 3 (240x160 16-bit BGR555) + BG2 enable

    const AgvHeader *hdr = (const AgvHeader *)0x08002000;
    if (hdr->magic != 0x31564741) {
        while (1) { wait_vblank(); }
    }

    uint32_t total_frames = hdr->total_frames ? hdr->total_frames : 1;
    uint32_t vpf = hdr->vblanks_per_frame ? hdr->vblanks_per_frame : 3;
    uint32_t audio_rate = hdr->audio_rate ? hdr->audio_rate : 10512;
    const int8_t *audio_base = (const int8_t *)(0x08000000 + hdr->audio_offset);
    uint32_t kf_int = hdr->keyframe_interval ? hdr->keyframe_interval : 20;
    uint32_t seek15 = hdr->seek_15s_frames ? hdr->seek_15s_frames : 300;
    uint32_t seek30 = hdr->seek_30s_frames ? hdr->seek_30s_frames : 600;
    uint32_t fps = (seek15 >= 75) ? (seek15 / 15) : (60 / vpf);
    if (fps == 0) fps = 20;
    uint16_t tm0_reload = (uint16_t)(hdr->timer0_reload ? hdr->timer0_reload : 0xF9C4);

    // Enable master sound
    REG_SOUNDCNT_X = 0x0080;
    REG_SOUNDCNT_L = 0;

    // Check SRAM auto-resume unless B is held on boot
    uint32_t cur_frame = 0;
    uint16_t boot_keys = ~REG_KEYINPUT & 0x03FF;
    if (!(boot_keys & KEY_B)) {
        if (sram_read_u32(0) == 0x5449544E) {
            uint32_t saved = sram_read_u32(4);
            uint32_t chk   = sram_read_u32(8);
            if ((saved ^ 0xA5A5A5A5) == chk && saved < total_frames) {
                cur_frame = (saved / kf_int) * kf_int;
            }
        }
    } else {
        save_bookmark(0);
    }

    uint16_t prev_keys = boot_keys;
    uint16_t newly_pressed = 0;
    int paused = 0;

    wait_vblank();
    uint32_t samples_played = start_continuous_audio(audio_base, cur_frame, audio_rate, fps, tm0_reload);
    uint16_t prev_tm1 = REG_TM1CNT_L;

    while (1) {
        // Decode current video frame directly into 0-waitstate VRAM during VBlank
        uint32_t raw_off = hdr->frame_offsets[cur_frame];
        int is_kf = (raw_off & 0x80000000) ? 1 : 0;
        const uint8_t *fptr = (const uint8_t *)(0x08000000 + (raw_off & 0x7FFFFFFF));
        decode_agv_frame(fptr, is_kf);

        // Save bookmark once per second (on keyframes)
        if (is_kf && (cur_frame % kf_int) == 0) {
            save_bookmark(cur_frame);
        }

        // Target audio sample count when (cur_frame + 1) should be displayed
        uint32_t next_frame_sample = ((cur_frame + 1) * audio_rate) / fps;

        // Wait until hardware audio clock reaches next_frame_sample (always at least 1 VBlank)
        do {
            wait_vblank();

            uint16_t cur_tm1 = REG_TM1CNT_L;
            samples_played += (uint16_t)(cur_tm1 - prev_tm1);
            prev_tm1 = cur_tm1;

            // Poll keys (edge-triggered)
            uint16_t keys = ~REG_KEYINPUT & 0x03FF;
            newly_pressed = keys & ~prev_keys;
            prev_keys = keys;

            if (newly_pressed & (KEY_START | KEY_A)) {
                save_bookmark(cur_frame);
                goto enter_pause;
            }

            if (newly_pressed & (KEY_RIGHT | KEY_LEFT | KEY_R | KEY_L)) {
                goto handle_seek;
            }
        } while (samples_played < next_frame_sample);

        cur_frame++;
        if (cur_frame >= total_frames) {
            // Reached end of file: hold on the final frame and enter Pause instead of looping around
            cur_frame = total_frames - 1;
            save_bookmark(0);
            goto enter_pause;
        }
        goto next_frame_immediate;

enter_pause:
        paused = 1;
        REG_DMA1CNT = 0;
        REG_TM0CNT_H = 0;
        REG_TM1CNT_H = 0;
        while (paused) {
            wait_vblank();
            uint16_t pk = ~REG_KEYINPUT & 0x03FF;
            uint16_t pnew = pk & ~prev_keys;
            prev_keys = pk;
            if (pnew & (KEY_START | KEY_A)) {
                paused = 0;
                if (cur_frame >= total_frames - 1) {
                    // Paused at end of file: A or START restarts from the beginning (0:00)
                    cur_frame = 0;
                } else {
                    cur_frame++;
                }
                samples_played = start_continuous_audio(audio_base, cur_frame, audio_rate, fps, tm0_reload);
                prev_tm1 = REG_TM1CNT_L;
                goto next_frame_immediate;
            }
            if (pnew & (KEY_RIGHT | KEY_LEFT | KEY_R | KEY_L)) {
                newly_pressed = pnew;
                paused = 0;
                goto handle_seek;
            }
        }

handle_seek:
        {
            int32_t target = (int32_t)cur_frame;
            if (newly_pressed & KEY_RIGHT) target += (int32_t)seek15;
            else if (newly_pressed & KEY_LEFT) target -= (int32_t)seek15;
            else if (newly_pressed & KEY_R) target += (int32_t)seek30;
            else if (newly_pressed & KEY_L) target -= (int32_t)seek30;

            if (target < 0) target = 0;
            if ((uint32_t)target >= total_frames - 1) {
                // Seeking forward reached/passed end of file: clamp to final frame and enter Pause
                REG_DMA1CNT = 0;
                REG_TM0CNT_H = 0;
                REG_TM1CNT_H = 0;
                if (cur_frame != total_frames - 1) {
                    wait_vblank();
                    uint32_t last_kf = ((total_frames - 1) / kf_int) * kf_int;
                    for (uint32_t f = last_kf; f < total_frames; f++) {
                        uint32_t roff = hdr->frame_offsets[f];
                        decode_agv_frame((const uint8_t *)(0x08000000 + (roff & 0x7FFFFFFF)), (roff & 0x80000000) ? 1 : 0);
                    }
                    cur_frame = total_frames - 1;
                }
                save_bookmark(0);
                goto enter_pause;
            }
            cur_frame = ((uint32_t)target / kf_int) * kf_int;
            save_bookmark(cur_frame);
            wait_vblank();
            samples_played = start_continuous_audio(audio_base, cur_frame, audio_rate, fps, tm0_reload);
            prev_tm1 = REG_TM1CNT_L;
            goto next_frame_immediate;
        }

next_frame_immediate:;
    }
}
