-- lx-bundle:true

-- This file is part of Lx, created by Liqube <www.liqube.com>
-- Copyright Liqube Audio. All rights reserved.
-- Lx Interim License. See LICENSE for details.

--- Native file-byte probing helpers
-- @module core.file.type

local native_text = require("text")

local filetype = {}
local DEFAULT_SAMPLE_BYTES = 8192
local CHARACTER_LOOKAHEAD_BYTES = 3

--- Probe bytes already held by Lua
-- @param data string file bytes
-- @param maximum number|nil logical sample limit
-- @return table probe native byte findings
function filetype.probe_data(data, maximum)
	return native_text.probe_file(data, maximum or DEFAULT_SAMPLE_BYTES)
end

--- Read and probe one bounded file prefix
-- Returns the same bytes for format detection so opening does not read the prefix twice
-- @param filename string file path
-- @return table|nil probe native byte findings
-- @return string|nil data bounded file bytes
-- @return string|nil err read error
function filetype.probe_path(filename)
	local data, err = system.read_file(
		filename,
		DEFAULT_SAMPLE_BYTES + CHARACTER_LOOKAHEAD_BYTES
	)

	if not data then
		return nil, nil, err
	end

	return filetype.probe_data(data), data
end

return filetype
