--[[ "Run Diagnostics" for the Plug-in Manager: everything a support mail
needs in one copyable dialog — plugin version, license state, which detector
will run (bundled engine vs Python path), and the detector's own runtime
report (detect.py --diag). Must be called from an async task because it
shells out. ]]

local LrFileUtils = import 'LrFileUtils'
local LrPathUtils = import 'LrPathUtils'
local LrPrefs = import 'LrPrefs'
local LrTasks = import 'LrTasks'

local Detect = require 'Detect'
local Json = require 'Json'
local License = require 'License'

local prefs = LrPrefs.prefsForPlugin()

local Diagnostics = {}

local function quote(s)
	return '"' .. s .. '"'
end

local function pluginVersion()
	local ok, info = pcall(dofile, LrPathUtils.child(_PLUGIN.path, 'Info.lua'))
	if ok and info and info.VERSION then
		return string.format('%d.%d.%d', info.VERSION.major,
			info.VERSION.minor, info.VERSION.revision)
	end
	return 'unknown'
end

function Diagnostics.report()
	local lines = {}
	local function add(fmt, ...)
		lines[#lines + 1] = string.format(fmt, ...)
	end

	add('Cut Corners %s (%s)', pluginVersion(), WIN_ENV and 'Windows' or 'macOS')
	add('%s', License.statusText())

	local engine = Detect.enginePath()
	local runner
	if engine then
		add('Detector: bundled engine at %s', engine)
		runner = quote(engine)
	else
		local python = tostring(prefs.pythonPath or '')
		local exists = LrFileUtils.exists(python) and 'found'
			or 'NOT FOUND at that path (relies on PATH)'
		add('Detector: Python at %s (%s)', python, exists)
		runner = quote(python) .. ' ' .. quote(LrPathUtils.child(
			LrPathUtils.child(_PLUGIN.path, 'bin'), 'detect.py'))
	end

	local out = LrPathUtils.child(LrPathUtils.getStandardFilePath('temp'),
		'cut-corners-diag-' .. os.time() .. '.json')
	local cmd = runner .. ' --diag ' .. quote(out)
	if WIN_ENV then
		cmd = '"' .. cmd .. '"'
	end
	local exitCode = LrTasks.execute(cmd)
	if LrFileUtils.exists(out) then
		local info = Json.decode(LrFileUtils.readFile(out) or '')
		LrFileUtils.delete(out)
		if info then
			add('Engine check: OK - Python %s, OpenCV %s, NumPy %s%s',
				tostring(info.python), tostring(info.opencv),
				tostring(info.numpy), info.frozen and ' (frozen)' or '')
		else
			add('Engine check: ran but produced unreadable output')
		end
	else
		add('Engine check: FAILED (exit %d). The detector cannot run;', exitCode)
		add('  install Python 3 with "pip install opencv-python numpy" or')
		add('  point the Python executable setting at one that has them.')
	end

	if prefs.enableLogging then
		add('Logging: enabled - see Documents/lrClassicLogs/CutCorners.log')
	else
		add('Logging: disabled (enable it here, then reload the plugin)')
	end
	return table.concat(lines, '\n')
end

return Diagnostics
