
-- Dedicated syntax for DOS-era text files so a load-time hook can pick a codepage

-- lx syntax
local syntax = require("core.syntax")
local patterns = require("core.syntax.patterns")
local dosdetect = require("syntax.dos.dosdetect")

--- Detect whether DOS syntax applies and which metadata to carry forward
-- @param ctx table load context with filename and raw data
-- @return table|false|nil detect result
local function detect_hook(ctx)
	local filename = tostring(ctx and ctx.filename or "")
	local data = ctx and ctx.data or ""

	if data ~= "" then
		local profile = dosdetect.get_scan_profile_for_filename(filename)
		local result = dosdetect.detect(data, profile)

		-- If action is "continue" the syntax delivers metadata but allows
		-- another syntax to have a go at the file.
		-- Like this we can combine e.g. codepage with another syntax highlighter.
		if not result.binary and (result.oem or result.ansi or result.escapes) then
			local meta = {
				action = "continue",
			}

			if result.oem then
				meta.codepage = "cp437"
			end

			if result.ansi or result.escapes then
				meta.ansi_viewer = true
			end

			-- Keep ANSI-like DOS files on the text path even when the generic probe dislikes padding bytes
			meta.force_text_open = true

			return meta
		end
	end
	-- Syntax rejects this file
	return false
end

syntax.add({
	name = "DOS-era Text File",
	shortname = "DOS",

--	files = "$", -- Try files with any extension

	extensions = {
		"bbs",
		"nfo",
		"diz",
		"ans",
		"art",
		"asc",
		"txt",
		"clr",
		"vt",
		"5bs", -- Origin unclear
		"8bs", -- Origin unclear
	},
	detect_hook = detect_hook,

	patterns = {
		-- Keep lightweight plain-text rules for legacy art and info files
		patterns.number_token(),

		-- Keep quoted spans readable in embedded notes
		patterns.double_quoted_string(),
		patterns.single_quoted_string(),
	},

	symbols = {},
	post_symbols = {},
})
