/* Retained inputs use the same document-access vocabulary as the Solving guide. */
#include <maelys/datalog_inputs.h>

static maelys_datalog_policy_t *policy = NULL;
static maelys_datalog_session_t *session = NULL;
static maelys_datalog_session_inputs_t *inputs = NULL;
static maelys_datalog_result_t *result = NULL;
static void *storage = NULL;
static maelys_datalog_input_options_t options = MAELYS_DATALOG_INPUT_OPTIONS_INIT;

static void cleanup_context(void) {
    if (result != NULL) { cleanup_status(maelys_datalog_result_free(result)); result = NULL; }
    if (inputs != NULL) { cleanup_status(maelys_datalog_session_inputs_free(inputs)); inputs = NULL; }
    if (session != NULL) { cleanup_status(maelys_datalog_session_free(session)); session = NULL; }
    if (policy != NULL) { cleanup_status(maelys_datalog_policy_free(policy)); policy = NULL; }
    free(storage);
    storage = NULL;
}

static void *allocate_storage(size_t bytes, size_t alignment) {
    void *memory = malloc(bytes);
    if (memory == NULL || alignment == 0 || (uintptr_t)memory % alignment != 0) {
        free(memory);
        fputs("Storage allocation failed\n", stderr);
        exit(EXIT_FAILURE);
    }
    return memory;
}

static void create_inputs(void) {
    size_t bytes = 0, alignment = 0;
    check_status(maelys_datalog_session_inputs_storage_requirements(session, &options, &bytes, &alignment));
    storage = allocate_storage(bytes, alignment);
    check_status(maelys_datalog_session_inputs_init(session, &options, storage, bytes, &inputs));
}

int main(void) {
    if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
    const maelys_datalog_predicate_t predicates[] = {
        MAELYS_DATALOG_EDB("user", 1), MAELYS_DATALOG_EDB("owns", 2),
        MAELYS_DATALOG_EDB("blocked", 1), MAELYS_DATALOG_IDB_QUERY("allow", 2),
    };
    const maelys_datalog_domain_t domain = MAELYS_DATALOG_DOMAIN_NO_ATOMS("documents", predicates);
    check_status(maelys_datalog_domain_register(&domain));
    const char *source = "allow(User, Doc) :- owns(User, Doc), not(blocked(User)).";
    maelys_datalog_diagnostic_t diagnostic = MAELYS_DATALOG_DIAGNOSTIC_INIT;
    check_status(maelys_datalog_policy_load_inline("documents", "reference-context", source,
        strlen(source), &policy, &diagnostic));
    check_status(maelys_datalog_session_create(policy, 0u, &session));
    const char *symbols[] = {"alice", "roadmap.pdf"};
    options.fact_capacity = 2;
    options.addition_capacity = 2;
    options.removal_capacity = 2;
    options.symbols = symbols;
    options.symbol_count = sizeof(symbols) / sizeof(symbols[0]);
    const maelys_datalog_fact_t facts[] = {
        { .predicate = "owns", .arity = 2u, .terms = {
            MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("roadmap.pdf"),
        } },
    };
    {
        /* API_REFERENCE_EXAMPLE */
    }
    cleanup_context();
    if (cleanup_failed) return EXIT_FAILURE;
    return EXIT_SUCCESS;
}
