local ie = minetest.request_insecure_environment()
local ai_model = minetest.settings:get("model_name")
if not ai_model or ai_model:match("^%s*$") then
    ai_model = "gemma3:270m"
end

if not ie then
    error("\n[shamegpt] CRITICAL ERROR!\n" ..
          "Add 'secure.trusted_mods = shamegpt' to your minetest.conf")
end

local active_requests = {}

local function clean_ai_text(text)
    if not text then return "" end
    local clean = text:gsub("\27%[[%d;]*%a", "")
    clean = clean:gsub("\r", "")
    clean = clean:gsub("\t", "    ")
    return clean:match("^%s*(.-)%s*$")
end


local function is_safe_prompt(text)

    return text:match("^[%w%s%?%.%,%!%-%_%(%)]*$") ~= nil
end

minetest.register_globalstep(function(dtime)

    if next(active_requests) == nil then return end

    for name, request in pairs(active_requests) do
        request.timer = (request.timer or 0) + dtime
        
        if request.timer > 0.5 then 
            request.timer = 0

            local done_check = ie.io.open(request.file .. ".done", "r")
            if done_check then
                done_check:close()
                
                local f = ie.io.open(request.file, "r")
                if f then
                    local content = f:read("*a")
                    f:close()

                    local final_text = clean_ai_text(content)
                    
                    if final_text ~= "" then
                        minetest.chat_send_all("[ShameGPT]: " .. final_text)
                    else
                        minetest.chat_send_all("[ShameGPT]: (Error: The AI returned an empty response)")
                    end

                    ie.os.remove(request.file)
                    ie.os.remove(request.file .. ".done")
                end
                active_requests[name] = nil
            end
        end
    end
end)

local function command_exists(cmd)
    local check_cmd = "which " .. cmd .. " > /dev/null 2>&1"
    local exit_code = ie.os.execute(check_cmd)
    return exit_code == 0 or exit_code == true
end

minetest.register_chatcommand("shamegpt", {
    params = "<text/prompt>",
    description = "Run a local query to ShameGPT via Ollama (Safe & Async)",
    privs = {interact = true},
    func = function(name, param)
        
        if not command_exists("ollama") then
            return false, "Error: The command 'ollama' is not found on the system. Is it installed?"
        end
        
        if param == "" then 
            return false, "Usage: /shamegpt [message]" 
        end
        
        if active_requests[name] then 
            return false, "Please wait, ShameGPT is still processing your previous request." 
        end

        if not is_safe_prompt(param) then
            return false, "Error: Your message contains forbidden characters (symbols like ; & | $ are not allowed)."
        end

        minetest.chat_send_all("... " .. name .. " is asking ShameGPT (" .. ai_model .. ") ...")

        local temp_file = ie.os.tmpname() .. "_" .. name:gsub("%W", "")
        
        local cmd = string.format("ollama run %s '%s' > %s 2>/dev/null && touch %s.done &",
                                  ai_model, param, temp_file, temp_file)
        
        local success = ie.os.execute(cmd)
        
        if success then
            active_requests[name] = {file = temp_file, timer = 0}
            return true, "Request sent! Waiting for response..."
        else
            return false, "Error: Failed to execute Ollama. Is the service running?"
        end
    end,
})







--[[


-- We try to obtain the insecure environment
local ie = minetest.request_insecure_environment()

-- Security validation
if not ie then
    error("\n[shamegpt] CRITICAL ERROR!\n" ..
          "The mod does not have trusted permissions.\n" ..
          "Add ‘secure.trusted_mods = shamegpt’ to your minetest.conf")
end

-- Command log
minetest.register_chatcommand("shamegpt", {
    params = "<text>",
    description = "Run a local query to Gemma 3 via Ollama",
    privs = {interact = true},
    func = function(name, param)
        if param == "" then
            return false, "Use: /shamegpt [your message]"
        end

        -- Notify that the AI is thinking (useful in case of lag)
        minetest.chat_send_all("..." .. name .. " is consulting Gemma 3...")

        -- Basic parameter cleaning to avoid problems with quotation marks
        local safe_param = param:gsub("'", "")
        
        -- Command: We use the full path if necessary, but ‘ollama’ is usually sufficient.
        local cmd = "ollama run gemma3:270m '" .. safe_param .. "' 2>/dev/null"
        
        -- Execution using the unsafe environment (ie)
        local handle = ie.io.popen(cmd)
        
        if not handle then
            return false, "Error: Couldn't start the Ollama process."
        end
        
        -- We read the complete output.
        local result = handle:read("*a")
        handle:close()

        -- Validate if there was a response
        if not result or result == "" then
            return false, "The AI did not return any response (Is Ollama turned on?)."
        end

        -- Return the result to the chat (cleaning up extra spaces)
        local clean_result = result:gsub("^%s*(.-)%s*$", "%1")
        return true, "[Gemma3]: " .. clean_result
    end,
})




local ie = minetest.request_insecure_environment()
local ai_model = minetest.settings:get("model_name")


if not ie then
    error("\n[shamegpt] CRITICAL ERROR!\n" ..
          "Add 'secure.trusted_mods = shamegpt' to your minetest.conf")
end

local active_requests = {}

minetest.register_globalstep(function(dtime)
    for name, request in pairs(active_requests) do
        
        request.timer = (request.timer or 0) + dtime
        if request.timer > 0.5 then 
            request.timer = 0
            
            
            local f = ie.io.open(request.file, "r")
            if f then
                local content = f:read("*a")
                f:close()

                local done_check = ie.io.open(request.file .. ".done", "r")
                if done_check then
                    done_check:close()
                    local clean_result = content:gsub("^%s*(.-)%s*$", "%1")
                    
                    if clean_result ~= "" then
                        minetest.chat_send_all("[ShameGPT]: " .. clean_result)
                    else
                        minetest.chat_send_all("[ShameGPT]: (Error: Empty response)")
                    end
                    
                    -- Limpieza total
                    ie.os.remove(request.file)
                    ie.os.remove(request.file .. ".done")
                    active_requests[name] = nil
                end
            end
        end
    end
end)

minetest.register_chatcommand("shamegpt", {
    params = "<text/prompt>",
    description = "Run a local query to ShameGPT via Ollama (Async Fixed)",
    privs = {interact = true},
    func = function(name, param)
        if param == "" then return false, "Use: /shamegpt [message]" end
        if active_requests[name] then return false, "ShameGPT is still thinking..." end

        minetest.chat_send_all("... " .. name .. " is asking ShameGPT ...")

        local temp_file = ie.os.tmpname()
        local safe_param = param:gsub("'", "")

        local cmd = "ollama run "..ai_model.." '" .. safe_param .. "' > " .. temp_file .. " 2>/dev/null && touch " .. temp_file .. ".done &"
        
        ie.os.execute(cmd)
        active_requests[name] = {file = temp_file, timer = 0}
        return true, "Thinking..."
    end,
})


]]--