/* Solving extension of the common C reference declarations. */
static maelys_datalog_policy_t *policy = NULL;
static maelys_datalog_session_t *session = NULL;
static maelys_datalog_session_config_t *config = NULL;
static maelys_datalog_input_edb_t *edb = NULL;
static maelys_datalog_result_t *result = NULL;
static void *storage = NULL;

static void cleanup_context(void) {
    if (result != NULL) { cleanup_status(maelys_datalog_result_free(result)); result = NULL; }
    if (session != NULL) { cleanup_status(maelys_datalog_session_free(session)); session = NULL; }
    if (config != NULL) { cleanup_status(maelys_datalog_session_config_free(config)); config = NULL; }
    if (edb != NULL) { cleanup_status(maelys_datalog_input_edb_free(edb)); edb = NULL; }
    if (policy != NULL) { cleanup_status(maelys_datalog_policy_free(policy)); policy = NULL; }
    free(storage);
    storage = NULL;
}

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));
    check_status(maelys_datalog_session_config_create(&config));
    check_status(maelys_datalog_input_edb_create(&edb));
    check_status(MAELYS_DATALOG_ADD_FACT(edb, &diagnostic, "owns", "alice", "roadmap.pdf"));
    const maelys_datalog_fact_t facts[] = {
        { .predicate = "owns", .arity = 2u, .terms = {
            MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("roadmap.pdf"),
        } },
    };
    const size_t fact_count = sizeof(facts) / sizeof(facts[0]);
    size_t storage_bytes = 0, storage_alignment = 0;
    check_status(maelys_datalog_session_explanation_storage_bound(session,
        MAELYS_DATALOG_EXPLAIN_TRUE, &storage_bytes, &storage_alignment));
    storage = malloc(storage_bytes);
    if (storage == NULL) {
        fputs("Explanation workspace allocation failed\n", stderr);
        return EXIT_FAILURE;
    }
    {
        /* API_REFERENCE_EXAMPLE */
    }
    cleanup_context();
    if (cleanup_failed) return EXIT_FAILURE;
    return EXIT_SUCCESS;
}
