--- Build strict file-reference rules for CSS documents
-- @module formats.css.references

local css_references = {}

-- Pattern breakdown: case-insensitive standalone CSS names followed by their normal separators
local url_prefix = "%f[%w_%-]url%f[^%w_%-]%s*%(%s*"
local import_prefix = "@import%f[^%w_%-]%s*"

--- Return whether one CSS target can name a local file
-- @param reference table parsed file reference
-- @return boolean accepted
local function is_local_target(reference)
	local path = reference.path
	if path:sub(1, 1) == "#" or path:sub(1, 2) == "//" then
		return false
	end

	return path:match("^%a:[/\\]") ~= nil or path:match("^%a[%w+%.%-]*:") == nil
end

--- Remove browser-only query and fragment text when looking for the CSS target
-- @param reference table parsed file reference
-- @return table candidates
local function file_candidates(reference)
	local filename = reference.path:match("^[^%?#]+")

	return filename and { filename } or {}
end

--- Return local URL and import references
-- @return table rules
function css_references.new()
	return {
		{ prefix = url_prefix, open = "\"", close = "\"", validate = is_local_target, candidates = file_candidates, caseless = true },
		{ prefix = url_prefix, open = "'", close = "'", validate = is_local_target, candidates = file_candidates, caseless = true },
		{ prefix = import_prefix, open = "\"", close = "\"", validate = is_local_target, candidates = file_candidates, caseless = true },
		{ prefix = import_prefix, open = "'", close = "'", validate = is_local_target, candidates = file_candidates, caseless = true },
		{ prefix = url_prefix, validate = is_local_target, caseless = true },
	}
end

return css_references
