-- Troubleshooting.lua — secondary-action window.
--
-- The main Dashboard used to host five buttons under a
-- "Troubleshooting" header (Rescan / Restart background
-- service / View log / View helper log / Clear thumbnail
-- cache).  Cluttered the primary surface and made the
-- Windows-row-spacing issue worse because the inline
-- push_buttons tower over the text-only status rows.
--
-- This module owns its own floating dialog and hosts the
-- four secondary actions.  The fifth one, Rescan, was
-- renamed "Recheck status" and stays on the main dashboard
-- because it's the most-used button (post-prerequisite-
-- install refresh) — and the main dashboard hides it
-- automatically when all status rows are green.
--
-- Button actions that need the main dashboard's LrView
-- context (Restart, Clear thumbnail cache) set flags on
-- the shared `active` table — the main dashboard's poll
-- loop drains them.  Actions that don't need the
-- dashboard context (log openers) shell out directly.

local LrDialogs = import 'LrDialogs'
local LrFunctionContext = import 'LrFunctionContext'
local LrPathUtils = import 'LrPathUtils'
local LrFileUtils = import 'LrFileUtils'
local LrTasks = import 'LrTasks'
local LrView = import 'LrView'

local Log = require 'Log'
local Platform = require 'Platform'
local Version = require 'Version'

local Troubleshooting = {}

local function openLogFile(label, filename)
    local path = LrPathUtils.child(Platform.scratchRoot, filename)
    if not LrFileUtils.exists(path) then
        LrDialogs.message(
            label .. ' not available yet',
            'Expected file:\n' .. path,
            'info')
        return
    end
    LrTasks.startAsyncTask(function()
        Log.line('troubleshooting', 'opening ' .. filename)
        LrTasks.execute(Platform.openTextFileCmd(path))
    end)
end

-- Guard so repeat clicks from the main dashboard don't
-- stack multiple floating dialogs.  Flipped back to false
-- on dismiss.  Module-local (not per-show) so it survives
-- across multiple show() calls.
local windowOpen = false

-- deps: {
--     active = <main dashboard's active flag table>,
-- }
function Troubleshooting.show(deps)
    if windowOpen then return end
    windowOpen = true

    LrTasks.startAsyncTask(function()
        LrFunctionContext.callWithContext(
            'pairs-troubleshooting',
            function(context)
                context:addCleanupHandler(function()
                    -- Best-effort: also flip if we crash
                    -- out of the dialog so a retry works.
                    windowOpen = false
                end)

                local f = LrView.osFactory()

                local contents = f:column {
                    spacing = f:control_spacing(),
                    margin_horizontal = 14,
                    margin_vertical = 12,

                    f:static_text {
                        title = 'Troubleshooting',
                        font = '<system/bold>',
                    },
                    -- Version stamp at the top of the
                    -- Troubleshooting window so a tester
                    -- copy-pasting logs into a bug report
                    -- can also grab the build number from
                    -- this same screen — saves the trip
                    -- back to the Dashboard for the build
                    -- number.
                    f:static_text {
                        title = 'Version ' .. Version.string(),
                        text_color = LrView.kColorGrey,
                    },
                    f:static_text {
                        title = 'These actions can help if the '
                            .. 'plugin is misbehaving.  View log '
                            .. 'opens the plugin\'s activity log; '
                            .. 'View helper log opens the Go '
                            .. 'helper\'s output.',
                        text_color = LrView.kColorGrey,
                        width_in_chars = 60,
                        height_in_lines = 2,
                    },

                    f:separator { fill_horizontal = 1 },

                    f:row {
                        spacing = f:control_spacing(),
                        f:push_button {
                            title = 'Restart background service',
                            action = function()
                                Log.line('troubleshooting',
                                    'restart background service requested')
                                -- Same flag the main dashboard's
                                -- restart control sets; the poll
                                -- loop drains restartAllRequested
                                -- and runs Launcher.restart.  An
                                -- earlier rename on the dashboard
                                -- side left this button setting
                                -- restartHelperRequested, which
                                -- nothing read — the click logged
                                -- a line and did nothing.  See
                                -- dev/code-review-2026-07-03.md
                                -- §2.3.
                                if deps.active then
                                    deps.active.restartAllRequested = true
                                end
                            end,
                        },
                        f:push_button {
                            title = 'Clear thumbnail cache',
                            action = function()
                                Log.line('troubleshooting',
                                    'clear thumbs requested')
                                if deps.active then
                                    deps.active.clearThumbsRequested = true
                                end
                            end,
                        },
                    },

                    f:row {
                        spacing = f:control_spacing(),
                        f:push_button {
                            title = 'View log',
                            action = function()
                                openLogFile('Plugin log', 'plugin.log')
                            end,
                        },
                        f:push_button {
                            title = 'View helper log',
                            action = function()
                                openLogFile('Helper log', 'helper.log')
                            end,
                        },
                        f:push_button {
                            title = 'Open temp folder',
                            -- Reveals the plugin's temp folder in
                            -- Finder / Explorer.  Without this
                            -- button there's no obvious way for a
                            -- tester to find the log files when
                            -- attaching them to a bug report —
                            -- the path is buried in /tmp on
                            -- macOS or %LOCALAPPDATA%\Temp on
                            -- Windows.
                            action = function()
                                Log.line('troubleshooting',
                                    'open temp folder requested')
                                LrFileUtils.createAllDirectories(
                                    Platform.scratchRoot)
                                LrTasks.startAsyncTask(function()
                                    LrTasks.execute(
                                        Platform.openFolderCmd(
                                            Platform.scratchRoot))
                                end)
                            end,
                        },
                    },
                }

                LrDialogs.presentFloatingDialog(_PLUGIN, {
                    title = 'Troubleshooting — Random Pair Generator',
                    contents = contents,
                    resizable = false,
                    -- Distinct save_frame so the window remembers
                    -- its own position independently of the main
                    -- dashboard.
                    save_frame = 'PairsTroubleshootingWindow1',
                })
                -- IMPORTANT: do NOT clear windowOpen here.
                -- presentFloatingDialog returns immediately on
                -- macOS (non-blocking despite the name) — if we
                -- cleared the guard here the dialog would be
                -- considered closed before the user dismissed
                -- it and a second Troubleshooting click would
                -- stack a new window on top.  The cleanup
                -- handler above handles the genuine close /
                -- crash paths.  See CLAUDE.md entry on
                -- presentFloatingDialog non-blocking behavior.
            end)
    end)
end

return Troubleshooting
