#include "engine/assets.h"
#include "config.h"
#include <SDL2/SDL_image.h>
#include <stdio.h>
#include <string.h>

typedef struct AssetEntry {
    char         path[ASSET_PATH_MAX];
    SDL_Texture *texture;
    Sound        sound;
    Music        music;
} AssetEntry;

static AssetEntry s_assets[MAX_ASSETS];
static int        s_asset_count = 0;
static SDL_Renderer *s_renderer = NULL;

void assets_init(SDL_Renderer *renderer) {
    s_renderer = renderer;
    s_asset_count = 0;
    memset(s_assets, 0, sizeof(s_assets));

    /* Initialize SDL_image */
    int img_flags = IMG_INIT_PNG;
    if (!(IMG_Init(img_flags) & img_flags)) {
        fprintf(stderr, "IMG_Init failed: %s\n", IMG_GetError());
    }
}

static int find_asset(const char *path) {
    for (int i = 0; i < s_asset_count; i++) {
        if (strcmp(s_assets[i].path, path) == 0) {
            return i;
        }
    }
    return -1;
}

SDL_Texture *assets_get_texture(const char *path) {
    int idx = find_asset(path);
    if (idx >= 0) return s_assets[idx].texture;

    if (s_asset_count >= MAX_ASSETS) {
        fprintf(stderr, "Asset limit reached!\n");
        return NULL;
    }

    SDL_Texture *tex = IMG_LoadTexture(s_renderer, path);
    if (!tex) {
        fprintf(stderr, "Failed to load texture: %s (%s)\n", path, IMG_GetError());
        return NULL;
    }

    idx = s_asset_count++;
    strncpy(s_assets[idx].path, path, ASSET_PATH_MAX - 1);
    s_assets[idx].texture = tex;

    printf("Loaded texture: %s\n", path);
    return tex;
}

Sound assets_get_sound(const char *path) {
    int idx = find_asset(path);
    if (idx >= 0) return s_assets[idx].sound;

    if (s_asset_count >= MAX_ASSETS) {
        fprintf(stderr, "Asset limit reached!\n");
        return (Sound){0};
    }

    Sound s = audio_load_sound(path);
    idx = s_asset_count++;
    strncpy(s_assets[idx].path, path, ASSET_PATH_MAX - 1);
    s_assets[idx].sound = s;

    return s;
}

Music assets_get_music(const char *path) {
    int idx = find_asset(path);
    if (idx >= 0) return s_assets[idx].music;

    if (s_asset_count >= MAX_ASSETS) {
        fprintf(stderr, "Asset limit reached!\n");
        return (Music){0};
    }

    Music m = audio_load_music(path);
    idx = s_asset_count++;
    strncpy(s_assets[idx].path, path, ASSET_PATH_MAX - 1);
    s_assets[idx].music = m;

    return m;
}

void assets_free_all(void) {
    for (int i = 0; i < s_asset_count; i++) {
        if (s_assets[i].texture) {
            SDL_DestroyTexture(s_assets[i].texture);
        }
        /* Sound/Music chunks are freed by SDL_mixer on close */
    }
    s_asset_count = 0;
    memset(s_assets, 0, sizeof(s_assets));
    IMG_Quit();
}
