#include "defs.h"

int save_game(const char *path)
{
    FILE *f = fopen(path, "wb");
    if (!f) {
        msg("(unable to save game)");
        return 0;
    }

    /* Write header */
    unsigned int magic = 0xD00AADA0;
    fwrite(&magic, sizeof(int), 1, f);
    int version = GAME_VERSION_MAJ * 100 + GAME_VERSION_MIN;
    fwrite(&version, sizeof(int), 1, f);

    /* Write player */
    fwrite(&G->player, sizeof(player_t), 1, f);

    /* Write game state */
    fwrite(&G->cur_level, sizeof(int), 1, f);
    fwrite(&G->n_levels, sizeof(int), 1, f);
    fwrite(&G->opts, sizeof(options_t), 1, f);
    fwrite(G->pill_names_known, sizeof(G->pill_names_known), 1, f);
    fwrite(G->pill_color_map, sizeof(G->pill_color_map), 1, f);
    fwrite(&G->rng_seed, sizeof(long), 1, f);

    /* Write levels */
    for (int i = 0; i < MAX_LEVELS; i++) {
        int exists = (G->levels[i] != NULL);
        fwrite(&exists, sizeof(int), 1, f);
        if (exists) {
            fwrite(G->levels[i], sizeof(level_t), 1, f);
        }
    }

    fclose(f);
    return 1;
}

int load_game(const char *path)
{
    FILE *f = fopen(path, "rb");
    if (!f) return 0;

    unsigned int magic;
    if (fread(&magic, sizeof(magic), 1, f) != 1 || magic != 0xD00AADA0) {
        fclose(f);
        return 0;
    }

    int version;
    if (fread(&version, sizeof(int), 1, f) != 1) {
        fclose(f);
        return 0;
    }

    /* Read player */
    if (fread(&G->player, sizeof(player_t), 1, f) != 1) {
        fclose(f);
        return 0;
    }

    /* Read game state */
    fread(&G->cur_level, sizeof(int), 1, f);
    fread(&G->n_levels, sizeof(int), 1, f);
    fread(&G->opts, sizeof(options_t), 1, f);
    fread(G->pill_names_known, sizeof(G->pill_names_known), 1, f);
    fread(G->pill_color_map, sizeof(G->pill_color_map), 1, f);
    fread(&G->rng_seed, sizeof(long), 1, f);

    /* Read levels */
    for (int i = 0; i < MAX_LEVELS; i++) {
        int exists;
        if (fread(&exists, sizeof(int), 1, f) != 1) break;
        if (exists) {
            G->levels[i] = calloc(1, sizeof(level_t));
            if (fread(G->levels[i], sizeof(level_t), 1, f) != 1) {
                free(G->levels[i]);
                G->levels[i] = NULL;
            }
        }
    }

    fclose(f);
    G->player.session_start = time(NULL);
    return 1;
}

void save_scoreboard(const char *cause)
{
    player_t *p = &G->player;
    int total = p->eps + p->bonus_pts - p->penalty_pts;

    FILE *f = fopen(SCORE_FILE, "a");
    if (!f) return;

    time_t now = time(NULL);
    struct tm *tm = localtime(&now);
    char datebuf[64];
    strftime(datebuf, sizeof(datebuf), "%d-%b-%Y %H:%M", tm);

    fprintf(f, "%10d  %-12s  Lev %2d  %s  %s\n",
            total, p->name, p->level, cause, datebuf);
    fclose(f);
}
