using PhpefRuntimeCore;

private static int fail(string message) {
    stderr.printf("%s\n", message);
    return 1;
}

int main(string[] args) {
    PhpefRuntimeCore.init(args);

    uint8[] hello = { 0x48, 0x65, 0x6c, 0x6c, 0x6f };
    uint8[] binary = { 0x61, 0x00, 0x62 };

    try {
        PhpefRuntimeCore.register_embedded_resource("/assets/hello.txt", hello);
        PhpefRuntimeCore.register_embedded_resource("/assets/binary.dat", binary);
    } catch (Error e) {
        return fail("register_embedded_resource failed: " + e.message);
    }

    var hello_meta = PhpefRuntimeCore.lookup_embedded_resource("/assets/hello.txt");
    if (hello_meta == null) {
        return fail("lookup for hello asset failed");
    }
    if (hello_meta.path != "/assets/hello.txt") {
        return fail("hello asset path mismatch");
    }
    if (hello_meta.length != 5 || hello_meta.data.length != 5) {
        return fail("hello asset length mismatch");
    }
    if (hello_meta.data[0] != 0x48 || hello_meta.data[4] != 0x6f) {
        return fail("hello asset bytes mismatch");
    }

    var binary_meta = PhpefRuntimeCore.lookup_embedded_resource("/assets/binary.dat");
    if (binary_meta == null) {
        return fail("lookup for binary asset failed");
    }
    if (binary_meta.length != 3 || binary_meta.data[1] != 0x00) {
        return fail("binary asset bytes mismatch");
    }

    if (!PhpefRuntimeCore.has_registered_embedded_resource("/assets/binary.dat")) {
        return fail("has_registered_embedded_resource returned false");
    }
    if (PhpefRuntimeCore.lookup_embedded_resource("assets/binary.dat") != null) {
        return fail("path without leading slash should not resolve");
    }

    bool duplicate_blocked = false;
    try {
        PhpefRuntimeCore.register_embedded_resource("/assets/hello.txt", hello);
    } catch (Error e) {
        duplicate_blocked = true;
    }
    if (!duplicate_blocked) {
        return fail("duplicate embedded resource was accepted");
    }

    stdout.printf("resource_registry_smoke=ok\n");
    return 0;
}
