CCCPaste
local gridSize = 7
local potatoSlot = 1

function isMaturePotato()
    local success, data = turtle.inspectDown()
    return success and data.name == "minecraft.potatoes" and data.stage.name == 7
end

function harvestAndReplant()
    if isMaturePotato() then
        turtle.digDown()
        turtle.select(potatoSlot)
        turtle.placeDown()
    end
end

function scanFarm()
  for row = 1, gridSize do
    for col = 1, gridSize do
      harvestAndReplant()
      if col < gridSize then turtle.forward() end
    end
    -- Move to next row
    if row < gridSize then
      if row % 2 == 1 then turtle.turnRight() else turtle.turnLeft() end
      turtle.forward()
      if row % 2 == 1 then turtle.turnRight() else turtle.turnLeft() end
    end
  end
end

function returnToStart()
  -- Reverse the scan pattern to return to top-left
  turtle.turnLeft()
  turtle.turnLeft()
  for i = 1, gridSize - 1 do turtle.forward() end
  turtle.turnRight()
  for i = 1, gridSize - 1 do turtle.forward() end
  turtle.turnRight()
end

function dumpPotatoes()
  turtle.back()
  for slot = 1, 16 do
    turtle.select(slot)
    turtle.drop()
  end
  turtle.forward()
end

-- Main loop
while True do
    scanFarm()
    returnToStart()
    dumpPotatoes()
    sleep(60)
end