
-- ANSI terminal streams are text files that need their own replay-based view

-- lx format
local format = require("core.format")
local patterns = require("core.format.patterns")
local ansi_detect = require("format.dos.detect")

--- Detect ANSI content and carry CP437 hints for older text art
-- @param ctx table load context with filename and raw data
-- @return table|false|nil detect result
local function detect_dos(ctx)
	local filename = tostring(ctx and ctx.filename or "")
	local data = ctx and ctx.data or ""

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

		if not result.binary and (result.oem or result.ansi or result.escapes) then
			local meta = {
				-- ANSI controls identify this format; CP437 alone remains ordinary text
				action = (result.ansi or result.escapes) and "accept" or "continue",
			}

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

			-- Keep ANSI-like 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

format.register({
	name = "DOS",
	shortname = "DOS",
	kind = "ansiart",
	default_mode = "preview", -- Replay accepted ANSi art unless the user chooses another mode

	extensions = {
		"bbs",
		"nfo",
		"diz",
		"ans",
		"art",
		"asc",
		"txt",
		"clr",
		"vt",
		"5bs", -- Origin unclear
		"8bs", -- Origin unclear
	},
	headers = {
		"\27%[", -- Pattern breakdown: a literal ESC byte followed by '[' starts a CSI command
	},
	detect = detect_dos,

	patterns = {
		-- Keep lightweight rules when ANSI content is shown as text
		patterns.number_token(),

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

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