#include <Python.h>
#include <stdlib.h>
#include <string.h>

static PyObject* module = NULL;

int init_python() {
    if (!Py_IsInitialized()) {
        Py_Initialize();
        if (!Py_IsInitialized()) return 0;
    }
    module = PyImport_ImportModule("shamirs_secret_sharing");
    if (!module) return 0;
    return 1;
}

char* py_string_to_c(PyObject* py_str) {
    const char* temp = PyUnicode_AsUTF8(py_str);
    if (!temp) return NULL;
    char* out = (char*)malloc(strlen(temp) + 1);
    strcpy(out, temp);
    return out;
}

char* combine_wrapper(char** shares, int length) {
    if (!module) if (!init_python()) return NULL;

    PyObject* list = PyList_New(length);
    for (int i = 0; i < length; i++) {
        PyList_SetItem(list, i, PyUnicode_FromString(shares[i]));
    }

    PyObject* func = PyObject_GetAttrString(module, "combine_wrapper");
    if (!func) return NULL;

    PyObject* args = PyTuple_Pack(2, list, PyLong_FromLong(length));
    PyObject* result = PyObject_CallObject(func, args);

    Py_XDECREF(func);
    Py_XDECREF(args);
    Py_XDECREF(list);

    if (!result) return NULL;

    char* out = py_string_to_c(result);
    Py_XDECREF(result);
    return out;
}

char* split_wrapper(char** secret, int length, int shares_num, int threshold) {
    if (!module) if (!init_python()) return NULL;

    PyObject* list = PyList_New(length);
    for (int i = 0; i < length; i++) {
        PyList_SetItem(list, i, PyUnicode_FromString(secret[i]));
    }

    PyObject* func = PyObject_GetAttrString(module, "split_wrapper");
    if (!func) return NULL;

    PyObject* args = PyTuple_Pack(4, list, PyLong_FromLong(length),
                                     PyLong_FromLong(shares_num), PyLong_FromLong(threshold));
    PyObject* result = PyObject_CallObject(func, args);

    Py_XDECREF(func);
    Py_XDECREF(args);
    Py_XDECREF(list);

    if (!result) return NULL;

    char* out = py_string_to_c(result);
    Py_XDECREF(result);
    return out;
}