// Host-side regression test for examples/agi/agiRes.c.
//
// The AGI resource loader is plain stdio C with no JoeyLib runtime
// dependencies, so we can compile and exercise it on the build host
// without touching any emulator. This keeps the Phase 0 iteration
// loop fast: edit agiRes.c, rerun scripts/test-agi.sh, get a pass
// or fail against KQ3 (or any AGI v2 directory) in under a second.
//
// Usage: testAgiRes <game-directory>
//
// Exit codes:
//   0  resource directories parsed and at least one resource per
//      type loaded successfully (or the type was empty)
//   1  game directory missing or malformed
//   2  invalid command line

#include "agi.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


// ----- Prototypes -----

static const char *resTypeName(AgiResTypeE type);
static int         testFirstResource(AgiGameT *game, AgiResTypeE type);


// ----- Helpers (alphabetical) -----

static const char *resTypeName(AgiResTypeE type) {
    switch (type) {
        case AGI_RES_LOGIC: return "LOGIC";
        case AGI_RES_PIC:   return "PIC  ";
        case AGI_RES_VIEW:  return "VIEW ";
        case AGI_RES_SOUND: return "SOUND";
        default:            return "?????";
    }
}


// Locate the first non-empty resource of `type`, load it, print its
// length. Returns 0 on success or empty type, 1 on load failure.
static int testFirstResource(AgiGameT *game, AgiResTypeE type) {
    uint16_t  i;
    uint16_t  length;
    uint8_t  *payload;
    uint16_t  count;

    count = game->resCount[type];
    for (i = 0; i < count; i++) {
        if (game->resDir[type][i].volume >= AGI_MAX_VOLUMES) {
            continue;
        }
        payload = agiResLoad(game, type, i, &length);
        if (payload == NULL) {
            fprintf(stderr, "FAIL: %s id %u failed to load\n", resTypeName(type), (unsigned)i);
            return 1;
        }
        printf("  %s: %u resources, first non-empty id %u is %u bytes\n",
               resTypeName(type), (unsigned)count, (unsigned)i, (unsigned)length);
        free(payload);
        return 0;
    }
    printf("  %s: %u directory slots, all empty\n", resTypeName(type), (unsigned)count);
    return 0;
}


// ----- main -----

int main(int argc, char **argv) {
    AgiGameT  game;
    uint8_t   t;
    int       rc;

    if (argc != 2) {
        fprintf(stderr, "usage: %s <game-directory>\n", argv[0]);
        return 2;
    }

    printf("Opening AGI game directory: %s\n", argv[1]);
    if (!agiResOpen(&game)) {
        fprintf(stderr, "FAIL: agiResOpen rejected '%s' (missing files? wrong format?)\n", argv[1]);
        return 1;
    }

    rc = 0;
    for (t = 0; t < AGI_RES_COUNT; t++) {
        if (testFirstResource(&game, (AgiResTypeE)t) != 0) {
            rc = 1;
        }
    }

    agiResClose(&game);
    if (rc == 0) {
        printf("OK\n");
    }
    return rc;
}
