// The MIT License (MIT)
//
// Copyright (C) 2026 Scott Duensing
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

// 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) {
    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 > BAS_VM_MAX_LOCALS ? BAS_VM_MAX_LOCALS : 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;
}
