-- API 地址 / API Endpoint
local API_URL = "http://newgmapi.liulikeji.cn/api/sanjuuni"

-- 输入图片URL / Input image URL
local INPUT_URL = "https://git.liulikeji.cn/xingluo/CCTweaked-Demo/raw/branch/main/Demo/SanjuuniApi-Demo/demo.jpg"


local function Get_image_url(INPUT_URL,API_URL,args,output_format)
    -- ===== 1. 发送HTTP请求 / Send HTTP request =====
    local requestData = {
        input_url = INPUT_URL,
        args = args,
        output_format = output_format
    }

    local response, err = http.post(
        API_URL,
        textutils.serializeJSON(requestData),
        { ["Content-Type"] = "application/json" }
    )

    -- ===== 2. 读取数据 / Send HTTP request =====
    if not response then error("HTTP Request Failure: "..(err or "Unknown error")) 
    else
        -- 读取响应 / Read response
        local responseData = textutils.unserializeJSON(response.readAll())
        response.close()

        --返回下载链接 / Return download URL
        if responseData.status ~= "success" then error("Conversion failed:"..(responseData.error or "Unknown error")) 
        else
            return responseData.download_url
        end
    end
end


-- 图片宽度 / Image width
local width, height = term.getSize()  -- 获取终端尺寸（width=宽度，height=高度）
local width = width * 2            -- 宽度×2
local height = height * 3          -- 高度×3

-- 转换参数 / Conversion parameters
args = { "-8","--width="..width,"--height="..height }
output_format = "lua"

-- 调用API / Call API
local download_url = Get_image_url(INPUT_URL,API_URL,args,output_format)


-- 下载图像文件 / Download image file
print("\nConversion successful! Download URL:")
print(download_url)

luafile = http.get(download_url)
if luafile then
    print("\nLua file downloaded successfully.")

    -- 保存Lua文件 / Save Lua file
    f = fs.open("demo.lua", "w")
    f.write(luafile.readAll())
    f.close()
    print("\nLua file saved as demo.lua.")

    -- 直接运行Lua文件 / Run Lua file
    -- load(luafile.readAll())()

else
    print("\nFailed to download Lua file.")
end
