--[[ Named settings profiles: save/recall the tunable set per scanning setup
("Epson V600 · 35mm", "DSLR · 120").

Profiles live in prefs.profiles, a table of name -> { key = value }. LrPrefs
only persists (and notifies observers) on *top-level assignment*, so every
mutation here copies the table, modifies the copy, and reassigns
prefs.profiles — never write into the nested tables in place. All writes go
through this module to keep that invariant in one file.
]]

local LrPrefs = import 'LrPrefs'

local prefs = LrPrefs.prefsForPlugin()

local Profiles = {}

-- Everything that describes a scanning setup. Machine/user-level prefs
-- (pythonPath, skipLabel, enableLogging, licensing) and per-run behavior
-- (dryRun, overwriteCropped, rollRescue) deliberately stay out.
Profiles.KEYS = {
	'filmType', 'filmFormat', 'edgeBand', 'inset', 'border',
	'aspectTarget', 'aspectTolerance', 'minArea', 'maxArea',
	'manualThreshold', 'darkEdgeMask', 'maxPixels',
}

-- Copy the profiled keys out of src (prefs, or a dialog's props table).
function Profiles.snapshot(src)
	local profile = {}
	for _, key in ipairs(Profiles.KEYS) do
		profile[key] = src[key]
	end
	return profile
end

-- Copy a profile into dst, skipping keys the profile doesn't carry: a
-- profile saved before a tunable existed leaves that setting alone.
function Profiles.applyTo(dst, profile)
	for _, key in ipairs(Profiles.KEYS) do
		if profile[key] ~= nil then
			dst[key] = profile[key]
		end
	end
end

-- Sorted profile names (table key order is undefined; the popups rebuild
-- their items from this every time).
function Profiles.list()
	local names = {}
	for name in pairs(prefs.profiles or {}) do
		names[#names + 1] = name
	end
	table.sort(names)
	return names
end

function Profiles.get(name)
	return (prefs.profiles or {})[name]
end

-- Saves src's profiled keys under name, overwriting an existing profile of
-- that name (which is also the update flow — there is no separate rename).
-- Returns the trimmed name, or nil for a blank one.
function Profiles.save(name, src)
	name = tostring(name or ''):gsub('^%s+', ''):gsub('%s+$', '')
	if name == '' then
		return nil
	end
	local copy = {}
	for k, v in pairs(prefs.profiles or {}) do
		copy[k] = v
	end
	copy[name] = Profiles.snapshot(src)
	prefs.profiles = copy
	return name
end

function Profiles.delete(name)
	local copy = {}
	for k, v in pairs(prefs.profiles or {}) do
		if k ~= name then
			copy[k] = v
		end
	end
	prefs.profiles = copy
end

return Profiles
