-- lx format
local format = require("core.format")

format.register({
	name = "Comments File",
	shortname = "Comm",
	author = "liqube",
	extensions = "comm",
	disable_tab_autocomplete = true,
	headers = "@comm\t",

	defaults = {
		word_wrap = false, -- Keep long metadata records on one line
	},

	file_references = {
		-- Source filename follows the record name directly
		{ prefix = "^@source\t" },

		-- Version 2 early layout has ID before the source range
		{ prefix = "^@comment\t%d+\t%d+\t%d+\t[^\t\r\n]+\t[^\t\r\n]*\t[^\t\r\n]*\t", locations = true },

		-- Version 1 and canonical version 2 share the locator position
		{ prefix = "^@comment\t%d+\t%d+\t[^\t\r\n]+\t[^\t\r\n]*\t[^\t\r\n]*\t", locations = true },
	},

	patterns = {
		-- Pattern breakdown: record name, tab separator, version
		{
			pattern = "(@comm)(\t)(%d+)",
			type = { "keyword", "operator", "number" },
			line_start = true,
		},

		-- Pattern breakdown: source record with path, encoding, format, size, fingerprint
		{
			pattern = "(@source)(\t)([^\t\r\n]+)(\t)([^\t\r\n]+)(\t)([^\t\r\n]+)(\t)(%d+)(\t)([%da-fA-F]+)",
			type = {
				"keyword", "operator", "string", "operator", "literal", "operator",
				"literal", "operator", "number", "operator", "hex",
			},
			line_start = true,
		},

		-- Pattern breakdown: canonical v2 comment fields followed by payload ID
		{
			pattern = "(@comment)(\t)(%d+)(\t)(%d+)(\t)([^\t\r\n]+)(\t)([^\t\r\n]*)(\t)([^\t\r\n]*)(\t)([^\t\r\n]+)(\t)(%d+)",
			type = {
				"keyword", "operator", "number", "operator", "number", "operator",
				"literal", "operator", "string", "operator", "string", "operator",
				"string", "operator", "label",
			},
			line_start = true,
		},

		-- Pattern breakdown: accepted early v2 layout with payload ID first
		{
			pattern = "(@comment)(\t)(%d+)(\t)(%d+)(\t)(%d+)(\t)([^\t\r\n]+)(\t)([^\t\r\n]*)(\t)([^\t\r\n]*)(\t)([^\t\r\n]+)",
			type = {
				"keyword", "operator", "label", "operator", "number", "operator",
				"number", "operator", "literal", "operator", "string", "operator",
				"string", "operator", "string",
			},
			line_start = true,
		},

		-- Pattern breakdown: v1 comment range, style, delimiters, locator
		{
			pattern = "(@comment)(\t)(%d+)(\t)(%d+)(\t)([^\t\r\n]+)(\t)([^\t\r\n]*)(\t)([^\t\r\n]*)(\t)([^\t\r\n]+)",
			type = {
				"keyword", "operator", "number", "operator", "number", "operator",
				"literal", "operator", "string", "operator", "string", "operator", "string",
			},
			line_start = true,
		},

		-- Version 2 payload ID
		{
			pattern = "(@%d+)",
			type = { "label" },
			line_start = true,
		},

		-- Payload framing and editable comment text
		{
			pattern = "(|)([^\r\n]*)",
			type = { "operator", "comment" },
			line_start = true,
		},
	},

	-- Numbered payloads are the only Comm outline entries
	outline_patterns = {
		{ pattern = "(@%d+)%s*$", line_start = true },
	},
})
