// Written by retoor@molodetz.nl

// This source code initializes a Python interpreter within a plugin, executes a provided Python script with some basic imports, and finalizes the Python environment when done.

// This code does not use any non-standard imports or includes aside from Python.h and structmember.h which are part of Python's C API.

// MIT License


#include <python3.14/Python.h>
#include <python3.14/structmember.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

bool plugin_initialized = false;

bool plugin_construct() {
    if (plugin_initialized)
        return true;

    Py_Initialize();

    if (!Py_IsInitialized()) {
        fprintf(stderr, "Failed to initialize Python interpreter\n");
        return plugin_initialized;
    }
    plugin_initialized = true;
    return plugin_initialized;
}

void plugin_run(char *src) {
    plugin_construct();
    const char *basics = 
        "import sys\n"
        "import os\n"
        "import math\n"
        "import pathlib\n"
        "import subprocess\n"
        "import time\n"
        "from datetime import datetime\n"
        "%s";
    size_t length = strlen(basics) + strlen(src);
    char *script = (char *)malloc(length + 1);
    sprintf(script, basics, src);
    script[length] = '\0';
    PyRun_SimpleString(script);
    free(script);
}

void plugin_destruct() {
    if (plugin_initialized)
        Py_Finalize();
}