#include <cli.h>
#include <game.h>
#include <graphics.h>
#include <SDL2/SDL.h>
#include "shrooms-vb-core/core/vb.h"
#include <stdio.h>

uint8_t *readROM(char *filename, uint32_t *size) {
    FILE *file = fopen(filename, "rb");
    uint8_t *rom;
    long filesize;

    if (!file) {
        perror("could not open file");
        return NULL;
    }

    if (fseek(file, 0, SEEK_END)) {
        perror("could not seek file end");
        return NULL;
    }
    filesize = ftell(file);
    if (filesize == -1) {
        perror("could not read file size");
        return NULL;
    }
    if (fseek(file, 0, SEEK_SET)) {
        perror("could not seek file start");
        return NULL;
    }

    *size = (uint32_t) filesize;
    rom = malloc(*size);
    if (!rom) {
        perror("could not allocate ROM");
        return NULL;
    }
    fread(rom, 1, *size, file);
    if (ferror(file)) {
        perror("could not read file");
        return NULL;
    }
    if (fclose(file)) {
        perror("could not close file");
        return NULL;
    }

    return rom;
}

int main(int argc, char **argv) {
    VB *sim;
    uint8_t *rom;
    uint32_t romSize;
    GraphicsContext gfx;
    CLIArgs args;
    int status;

    if (parseCLIArgs(argc, argv, &args)) {
        return 1;
    }
    
    rom = readROM(args.filename, &romSize);
    if (!rom) {
        return 1;
    }

    sim = malloc(vbSizeOf());
    vbInit(sim);
    vbSetCartROM(sim, rom, romSize);

    SDL_SetHint(SDL_HINT_VIDEO_HIGHDPI_DISABLED, "0");
    if (SDL_Init(SDL_INIT_EVERYTHING)) {
        fprintf(stderr, "Error initializing SDL: %s\n", SDL_GetError());
        return 1;
    }

    if (gfxInit(&gfx)) {
        SDL_Quit();
        return 1;
    }

    status = runGame(sim, &gfx);
    SDL_Quit();
    return status;
}