local https = require("ssl.https")
local ltn12 = require("ltn12")

https.TIMEOUT = 20

local API_URL = "__API_BASE_URL__/api/analyze"

local function readBinary(path)
  local file, err = io.open(path, "rb")
  if not file then return nil, err end
  local data = file:read("*a")
  file:close()
  return data
end

function 异常图片上传()
  local path = "/mnt/sdcard/test11.png"
  local screenX = 591
  local screenY = 79

  snapShot(path, screenX, screenY, 1200, 620)
  sleep(50)

  local imageData, readError = readBinary(path)
  if not imageData then return nil, "读取图片失败: " .. tostring(readError) end

  local query = table.concat({
    "?useSpecifiedGrid=true",
    "&rows=8",
    "&cols=9",
    "&cellWidth=68",
    "&cellHeight=68",
    "&cornerSize=5",
    "&x=0",
    "&y=0"
  })

  local response = {}
  local ok, status = https.request {
    url = API_URL .. query,
    method = "POST",
    headers = {
      ["Content-Type"] = "application/octet-stream",
      ["Content-Length"] = tostring(#imageData),
      ["Accept"] = "application/json",
      ["Connection"] = "close"
    },
    source = ltn12.source.string(imageData),
    sink = ltn12.sink.table(response)
  }

  local responseText = table.concat(response)
  if not ok or tonumber(status) ~= 200 then return nil, "请求失败: " .. tostring(status) .. " " .. responseText end

  local data, decodeError = jsonLib.decode(responseText)
  if not data then return nil, "返回解析失败: " .. tostring(decodeError) end
  if not data.ok then return nil, data.error or "接口处理失败" end

  local output = {}
  local groups = { ["红"] = {}, ["黄"] = {}, ["紫"] = {}, ["蓝"] = {}, ["绿"] = {}, ["白"] = {} }

  for _, cell in ipairs(data.result or {}) do
    local item = {
      row = cell.row + 1,
      col = cell.col + 1,
      x = cell.x + screenX,
      y = cell.y + screenY,
      color = cell.color
    }
    output[#output + 1] = item
    groups[cell.color][#groups[cell.color] + 1] = item
  end

  local resultJson, encodeError = jsonLib.encode({
    ok = true,
    count = #output,
    groups = groups
  })
  if not resultJson then return nil, "结果编码失败: " .. tostring(encodeError) end

  print("图片字节数", #imageData)
  print("六色分类JSON", resultJson)
  print("红色数量", #groups["红"], "黄色数量", #groups["黄"], "紫色数量", #groups["紫"])
  print("蓝色数量", #groups["蓝"], "绿色数量", #groups["绿"], "白色数量", #groups["白"])
  return resultJson, nil, groups
end

function API测试()
  local resultJson, err = 异常图片上传()
  if not resultJson then
    print("API测试失败", err)
    return false
  end
  print("API测试成功")
  return true
end

-- API测试()
