#include <Python.h>
#include <libkydiagnostics.h>


static PyObject* buried_point(PyObject* self, PyObject* args) {
    char *appName;
    char *messageType;
    PyObject *py_data;
    int length;

   if (!PyArg_ParseTuple(args, "ssOi", &appName, &messageType, &py_data, &length)) {
        return NULL;
    }

    if (!PyDict_Check(py_data)) {
        PyErr_SetString(PyExc_TypeError, "Third argument must be a dict of KBuriedPoint");
        return NULL;
    }

    KBuriedPoint *data = (KBuriedPoint *)malloc(length * sizeof(KBuriedPoint));
    if (data == NULL) {
        PyErr_SetString(PyExc_MemoryError, "Failed to allocate memory");
        return NULL;
    }
    
    PyObject *py_key, *py_value;
    Py_ssize_t pos = 0;
    while (PyDict_Next(py_data, &pos, &py_key, &py_value)) {
        if (!PyUnicode_Check(py_key) || !PyUnicode_Check(py_value)) {
            PyErr_SetString(PyExc_TypeError, "Dictionary items must be strings");
            free(data);
            Py_BuildValue("i", -1);
        }

        data[(int)pos-1].key = PyUnicode_AsUTF8(py_key);
        data[(int)pos-1].value = PyUnicode_AsUTF8(py_value);
    }

    int result = kdk_buried_point(appName, messageType, data, length);
    
    free(data);

    return Py_BuildValue("i", result);
}

static PyMethodDef myMethods[] = {
    {"buried_point", buried_point, METH_VARARGS, "kdk_buried_point in python"},
    {NULL, NULL, 0, NULL} // Sentinel
};

static struct PyModuleDef myModule = {
    PyModuleDef_HEAD_INIT,
    "buried_point",   // 模块名称
    NULL,          // 模块文档，如果为NULL，模块将没有__doc__属性
    -1,            // 模块状态，-1表示不使用子解释器
    myMethods      // 包含模块中的方法的方法表
};

PyMODINIT_FUNC PyInit_buried_point(void) {
    return PyModule_Create(&myModule);
}