using PhpefRuntimeCore;

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

int main(string[] args) {
    PhpefRuntimeEmbed.engine_start(args);

    var value = Zval.from_string("123");
    var ok = PhpefRuntimeEmbed.phpfunc_settype(value, Zval.from_string("integer"));
    if (!ok.to_bool()) {
        return fail("settype returned false");
    }
    if (value.kind != ValueKind.INT || value.as_int() != 123) {
        return fail("settype did not propagate by-reference int conversion; got " + value.to_php_string());
    }

    var output = Zval.from_null();
    var result_code = Zval.from_null();
    var last_line = PhpefRuntimeEmbed.phpfunc_exec(Zval.from_string("printf 'alpha\nbeta\n'"), output, result_code);
    if (last_line.to_php_string() != "beta") {
        return fail("exec returned wrong last line: " + last_line.to_php_string());
    }
    if (result_code.kind != ValueKind.INT || result_code.as_int() != 0) {
        return fail("exec did not propagate result code 0; got " + result_code.to_php_string());
    }
    if (output.kind != ValueKind.ARRAY) {
        return fail("exec did not propagate output array; got kind " + output.kind.to_string());
    }
    var entries = output.as_array_entries();
    if (entries.length != 2
        || entries[0].value.to_php_string() != "alpha"
        || entries[1].value.to_php_string() != "beta") {
        return fail("exec output array mismatch: " + output.to_php_string());
    }

    PhpefRuntimeEmbed.engine_stop();
    stdout.printf("byref_smoke=ok\n");
    return 0;
}
