// test_quick.c -- Quick single-program test
//
// Build: make -C dvxbasic tests

#include "compiler/parser.h"
#include "runtime/vm.h"
#include "runtime/values.h"
#include <stdio.h>
#include <string.h>

int main(void) {
    basStringSystemInit();

    const char *source = "PRINT \"Hello, World!\"\n";
    printf("Source: [%s]\n", source);
    printf("Source len: %d\n", (int)strlen(source));

    int32_t len = (int32_t)strlen(source);
    BasParserT parser;
    basParserInit(&parser, source, len);

    if (!basParse(&parser)) {
        printf("COMPILE ERROR: %s\n", parser.error);
        basParserFree(&parser);
        return 1;
    }

    printf("Compiled OK (%d bytes of p-code)\n", parser.cg.codeLen);

    // Dump p-code
    for (int i = 0; i < parser.cg.codeLen; i++) {
        printf("%02X ", parser.cg.code[i]);
    }
    printf("\n");

    BasModuleT *mod = basParserBuildModule(&parser);
    basParserFree(&parser);

    BasVmT *vm = basVmCreate();
    basVmLoadModule(vm, mod);
    vm->callStack[0].localCount = mod->globalCount > 64 ? 64 : mod->globalCount;
    vm->callDepth = 1;

    // Step limit
    int steps = 0;
    vm->running = true;

    while (vm->running && steps < 1000) {
        BasVmResultE r = basVmStep(vm);
        steps++;

        if (r != BAS_VM_OK) {
            printf("[Result: %d after %d steps: %s]\n", r, steps, basVmGetError(vm));
            break;
        }
    }

    if (steps >= 1000) {
        printf("[TIMEOUT after %d steps, PC=%d]\n", steps, vm->pc);
    }

    basVmDestroy(vm);
    basModuleFree(mod);
    return 0;
}
