#ifndef SERIAL_UPLOADER_H
#define SERIAL_UPLOADER_H

#include <cstdint>
#include "ff.h"

class GameLauncher;

class SerialUploader {
public:
    SerialUploader(GameLauncher* launcher);

    // Process incoming serial data (call this frequently in main loop)
    // Returns true if a game was launched
    // spi_busy: set to true if SPI bus is currently in use by another core (e.g. display refresh)
    bool process(bool spi_busy = false);

    // Check if uploader wants to launch a game (after upload complete)
    bool wants_to_launch_game() const { return state == LAUNCHING_GAME; }

    // Complete the game launch (call only when safe - no display refresh in progress)
    // Returns true if launch succeeded
    bool complete_launch();

    // Get the filename of the last uploaded game (without .lua extension)
    const char* get_last_uploaded_filename() const { return last_uploaded_name; }

private:
    enum State {
        IDLE,
        RECEIVING_FILENAME,
        RECEIVING_SIZE,
        RECEIVING_DATA,
        WRITING_FILE,
        LAUNCHING_GAME
    };

    State state;
    GameLauncher* game_launcher;

    // Upload state
    char filename[64];
    char last_uploaded_name[64];  // Game name without .lua extension
    uint32_t file_size;
    uint32_t bytes_received;
    uint8_t* file_buffer;

    // Base64 decoding buffer
    char base64_buffer[4];
    int base64_index;

    // Helper methods
    void reset();
    bool write_file_to_sd();
    void launch_game();
    uint8_t decode_base64_char(char c);
    void decode_base64_block(const char* input, uint8_t* output);
};

#endif // SERIAL_UPLOADER_H
