#include <maelys/datalog.h>
#include <maelys/datalog_builders.h>
#include <maelys/datalog_module.h>
#include <maelys/datalog_program.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static maelys_datalog_policy_t *policy = NULL;
static maelys_datalog_session_t *session = NULL;
static maelys_datalog_result_t *result = NULL;
static int cleanup_failed = 0;
static void check_status(maelys_datalog_status_t status) {
    if (status != MAELYS_DATALOG_STATUS_OK) {
        fprintf(stderr, "API call failed: %s\n", maelys_datalog_status_name(status));
        exit(EXIT_FAILURE);
    }
}
static void cleanup_context(void) {
    if (result) { if (maelys_datalog_result_free(result)) cleanup_failed = 1; result = NULL; }
    if (session) { if (maelys_datalog_session_free(session)) cleanup_failed = 1; session = NULL; }
    if (policy) { if (maelys_datalog_policy_free(policy)) cleanup_failed = 1; policy = NULL; }
}

/* The filter is pure and bounded. No callback keeps pointers or calls the engine. */
static maelys_datalog_status_t validate_suffix(const unsigned char *pattern, size_t length) {
    if (!pattern || !length || length > 63) return MAELYS_DATALOG_STATUS_INVALID_FIELD;
    return MAELYS_DATALOG_STATUS_OK;
}
static maelys_datalog_status_t suffix_cost(size_t value_length, size_t pattern_length, size_t *out_cost) {
    (void)value_length;
    if (!out_cost) return MAELYS_DATALOG_STATUS_INVALID_ARGUMENT;
    if (pattern_length == SIZE_MAX) return MAELYS_DATALOG_STATUS_PAYLOAD_TOO_LARGE;
    *out_cost = pattern_length + 1;
    return MAELYS_DATALOG_STATUS_OK;
}
static maelys_datalog_status_t evaluate_suffix(const unsigned char *value, size_t value_length,
    const unsigned char *pattern, size_t pattern_length, int *out_matched) {
    if (!value || !pattern || !out_matched) return MAELYS_DATALOG_STATUS_INVALID_ARGUMENT;
    *out_matched = value_length >= pattern_length &&
        memcmp(value + value_length - pattern_length, pattern, pattern_length) == 0;
    return MAELYS_DATALOG_STATUS_OK;
}
static const maelys_datalog_filter_module_t suffix_module = {
    MAELYS_DATALOG_MODULE_ABI_VERSION, sizeof(maelys_datalog_filter_module_t),
    "document_suffix", "example.document-suffix.bytes-v1.cost-pattern-plus-one",
    validate_suffix, suffix_cost, evaluate_suffix
};

/* The core supplies only safe choices; this callback never reorders the array. */
static maelys_datalog_status_t choose_join(const maelys_datalog_join_candidate_t *candidates,
    size_t candidate_count, size_t *out_candidate_index) {
    if (!candidates || !candidate_count || !out_candidate_index)
        return MAELYS_DATALOG_STATUS_INVALID_ARGUMENT;
    size_t best = 0;
    for (size_t i = 1; i < candidate_count; ++i)
        if (candidates[i].default_score > candidates[best].default_score ||
            (candidates[i].default_score == candidates[best].default_score &&
             candidates[i].body_index < candidates[best].body_index)) best = i;
    *out_candidate_index = best;
    return MAELYS_DATALOG_STATUS_OK;
}
static const maelys_datalog_planner_module_t planner_module = {
    MAELYS_DATALOG_MODULE_ABI_VERSION, sizeof(maelys_datalog_planner_module_t),
    "document_join", "example.document-join.score-then-body-v1", choose_join
};
static 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)
};
static maelys_datalog_status_t install_document_predicates(maelys_datalog_domain_builder_t *builder) {
    for (size_t i = 0; i < sizeof(predicates) / sizeof(predicates[0]); ++i) {
        maelys_datalog_status_t status = maelys_datalog_domain_builder_add(builder, &predicates[i]);
        if (status != MAELYS_DATALOG_STATUS_OK) return status;
    }
    return MAELYS_DATALOG_STATUS_OK;
}
static const char *const atoms[] = { ".pdf" };
static const maelys_datalog_domain_t domain = {
    "document_modules", NULL, 0, atoms, sizeof(atoms) / sizeof(atoms[0])
};
static const char source[] =
    "allow(User, Doc) :- user(User), owns(User, Doc), not(blocked(User)), "
    "document_suffix(Doc, \".pdf\").\n";
static const maelys_datalog_fact_t facts[] = {
    { "user", 1, { MAELYS_DATALOG_SYMBOL("alice") } },
    { "user", 1, { MAELYS_DATALOG_SYMBOL("mallory") } },
    { "owns", 2, { MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("roadmap.pdf") } },
    { "owns", 2, { MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("draft.txt") } },
    { "owns", 2, { MAELYS_DATALOG_SYMBOL("mallory"), MAELYS_DATALOG_SYMBOL("roadmap.pdf") } },
    { "blocked", 1, { MAELYS_DATALOG_SYMBOL("mallory") } }
};
static void load_document_policy(void) {
    check_status(maelys_datalog_policy_load_inline(domain.name, "document-access", source,
        strlen(source), &policy, NULL));
    check_status(maelys_datalog_session_create(policy, 0, &session));
}
static void prepare_context(unsigned step) {
    (void)facts;
    if (step > 1) check_status(maelys_datalog_register_filter_module(&suffix_module));
    if (step > 2) check_status(maelys_datalog_register_planner_module(&planner_module));
    if (step > 3) check_status(maelys_datalog_domain_register_advanced(&domain,
        "Document access with a native file-suffix filter", install_document_predicates));
    if (step > 4) load_document_policy();
}

int main(void) {
    if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
    prepare_context(1);
/* API_REFERENCE_EXAMPLE */
    cleanup_context();
    return cleanup_failed ? EXIT_FAILURE : EXIT_SUCCESS;
}
