-- control.lua

local OUTPUT_FILE = "map_data.bin"

-- Mapping of tile names to unique IDs
local tile_id_map = {}
local next_id = 1

-- Function to send chunk data to the file
local function send_chunk_data(chunk_pos, tiles)
    -- Pack chunk position (x, y) as two 4-byte signed integers
    local data = string.pack("<i4 i4", chunk_pos.x, chunk_pos.y)
    -- Pack each tile ID as a 1-byte unsigned integer
    for _, tile_id in ipairs(tiles) do
        data = data .. string.pack("<B", tile_id)
    end
    -- Prepend the total size of the data (4 bytes, unsigned)
    local size = #data
    local full_data = string.pack("<I4", size) .. data
    -- Append to the file
    helpers.write_file(OUTPUT_FILE, full_data, true)
end

-- Function to get or assign a tile ID for a tile name
local function get_tile_id(tile_name)
    if not tile_id_map[tile_name] then
        tile_id_map[tile_name] = next_id
        next_id = next_id + 1
        -- Note: You could extend this to send tile mappings to Rust if needed
    end
    return tile_id_map[tile_name]
end

-- Event handler for chunk generation
script.on_event(defines.events.on_chunk_generated, function(event)
    local surface = event.surface
    local chunk_pos = event.position
    local tiles = {}
    -- Collect tile data for the 32x32 chunk
    for x = 0, 31 do
        for y = 0, 31 do
            local tile = surface.get_tile(chunk_pos.x * 32 + x, chunk_pos.y * 32 + y)
            local tile_id = get_tile_id(tile.name)
            table.insert(tiles, tile_id)
        end
    end
    send_chunk_data(chunk_pos, tiles)
end)