#define _POSIX_C_SOURCE 200809L

#include "tools_internal.h"

#include <stdlib.h>

#include "cjson/cJSON.h"
#include "../nostr_handler.h"

static char* json_error_local(const char* msg) {
    cJSON* root = cJSON_CreateObject();
    if (!root) return NULL;
    cJSON_AddBoolToObject(root, "success", 0);
    cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
    char* out = cJSON_PrintUnformatted(root);
    cJSON_Delete(root);
    return out;
}

char* execute_nostr_query(const char* args_json) {
    cJSON* args = cJSON_Parse(args_json ? args_json : "{}");
    if (!args) return json_error_local("invalid arguments JSON");

    cJSON* filter = cJSON_GetObjectItemCaseSensitive(args, "filter");
    cJSON* timeout = cJSON_GetObjectItemCaseSensitive(args, "timeout_ms");
    if (!filter || !cJSON_IsObject(filter)) {
        cJSON_Delete(args);
        return json_error_local("nostr_query requires object filter");
    }

    cJSON* filter_dup = cJSON_Duplicate(filter, 1);
    if (!filter_dup) {
        cJSON_Delete(args);
        return json_error_local("failed to duplicate filter");
    }

    int timeout_ms = (timeout && cJSON_IsNumber(timeout)) ? (int)timeout->valuedouble : 8000;
    char* events_json = nostr_handler_query_json(filter_dup, timeout_ms);
    cJSON_Delete(filter_dup);
    cJSON_Delete(args);

    if (!events_json) return json_error_local("nostr_query failed");

    cJSON* out = cJSON_CreateObject();
    if (!out) {
        free(events_json);
        return NULL;
    }

    cJSON* events = cJSON_Parse(events_json);
    free(events_json);
    if (!events) {
        cJSON_Delete(out);
        return json_error_local("nostr_query returned invalid JSON");
    }

    cJSON_AddBoolToObject(out, "success", 1);
    cJSON_AddItemToObject(out, "events", events);
    char* json = cJSON_PrintUnformatted(out);
    cJSON_Delete(out);
    return json;
}
