import AppKit
import QuartzCore
import AlignerCore

@MainActor
final class QuickSwitchSessionController {
    static let overlayTitle = "Aligner Quick Switch"

    private let view = QuickSwitchRootView()
    private let snapshotLoader: any QuickSwitchSnapshotLoading
    private let screenshotProvider: any ScreenshotProviderProtocol
    private let windowActivationService: any WindowActivationServiceProtocol
    private let systemCriticalWindowDetector: any SystemCriticalWindowDetecting
    private let disableScreenshotRefresh: Bool
    private let debugOverlayWidth: CGFloat?
    private let debugKeySequence: [String]
    private let debugMouseSequence: [String]
    private let debugSystemCriticalAfter: TimeInterval?
    private lazy var coordinator = WindowCoordinator(
        contentView: view,
        title: Self.overlayTitle,
        debugOverlayWidth: debugOverlayWidth
    )
    private var currentSnapshot: QuickSwitchSnapshot?
    private var currentViewModel: QuickSwitchViewModel?
    private var lastSnapshotError: String?
    private var snapshotTask: Task<Void, Never>?
    private var screenshotTask: Task<Void, Never>?
    private var systemCriticalMonitorTimer: Timer?
    private var debugSystemCriticalTimer: Timer?
    private var screenshotSession = ScreenshotCaptureSession()
    private var sessionGeneration = 0
    private var showStartTime: CFTimeInterval?
    private var overlayOpenElapsedMilliseconds: Double?
    private var snapshotStartElapsedMilliseconds: Double?
    private var snapshotDurationMilliseconds: Double?
    private var snapshotRanOnMainThread: Bool?
    private var lastCommittedSelection: QuickSwitchSelection?
    private var lastCommitSource: QuickSwitchCommitSource?
    private var lastActivationWindowID: UInt32?
    private var lastActivationResult: WindowActivationResult?
    private var lastActivationError: String?
    private var lastDismissReason: DismissReason?
    private var lastSystemCriticalAction: String?
    private var lastSystemCriticalMonitorSource: String?
    private var lastSystemCriticalWindowCount = 0
    private var lastSystemCriticalWindowTitleHashes: [String] = []
    private var lastSystemCriticalWindowTitleLengths: [Int] = []
    private var lastSystemCriticalWindowTitleIsEmpty: [Bool] = []
    private var lastSystemCriticalWindowOwners: [String] = []
    private var lastSystemCriticalOverlayLevel: CGWindowLevel?
    private var systemCriticalDetectionCount = 0
    private var lifecycleTargetCycles = 0
    private var lifecycleCompletedCycles = 0
    private var lifecycleMaximumOverlayWindows = 0
    private var lifecycleMaximumVisibleOverlayWindows = 0
    private var lifecycleResidualOverlayWindows = 0
    private var lifecycleResidualVisibleOverlayWindows = 0
    var onSnapshotUpdated: (() -> Void)?

    init(
        snapshotLoader: any QuickSwitchSnapshotLoading = LiveQuickSwitchSnapshotLoader(),
        screenshotProvider: any ScreenshotProviderProtocol = ScreenCaptureKitScreenshotProvider(
            debugLogger: StderrScreenshotDebugLogger()
        ),
        windowActivationService: any WindowActivationServiceProtocol = CGWindowAXWindowService(
            spaceIDsByWindowIDProvider: { _ in [:] }
        ),
        systemCriticalWindowDetector: any SystemCriticalWindowDetecting = CGWindowSystemCriticalWindowDetector(),
        disableScreenshotRefresh: Bool = false,
        debugHoveredAppGroupIndex: Int? = nil,
        debugOverlayWidth: CGFloat? = nil,
        debugKeySequence: [String] = [],
        debugMouseSequence: [String] = [],
        debugSystemCriticalAfter: TimeInterval? = nil
    ) {
        self.snapshotLoader = snapshotLoader
        self.screenshotProvider = screenshotProvider
        self.windowActivationService = windowActivationService
        self.systemCriticalWindowDetector = systemCriticalWindowDetector
        self.disableScreenshotRefresh = disableScreenshotRefresh
        self.debugOverlayWidth = debugOverlayWidth
        self.debugKeySequence = debugKeySequence
        self.debugMouseSequence = debugMouseSequence
        self.debugSystemCriticalAfter = debugSystemCriticalAfter
        view.setDebugHoveredAppGroupIndex(debugHoveredAppGroupIndex)
    }

    var isVisible: Bool {
        coordinator.isQuickSwitchVisible
    }

    func show() {
        sessionGeneration += 1
        let generation = sessionGeneration
        DevelopmentDiagnostics.log("quickSwitch.session.show.start", [
            "generation": generation,
            "wasVisible": isVisible
        ])
        showStartTime = CACurrentMediaTime()
        overlayOpenElapsedMilliseconds = nil
        snapshotStartElapsedMilliseconds = nil
        snapshotDurationMilliseconds = nil
        snapshotRanOnMainThread = nil
        lastCommittedSelection = nil
        lastCommitSource = nil
        lastActivationWindowID = nil
        lastActivationResult = nil
        lastActivationError = nil
        lastDismissReason = nil
        lastSystemCriticalAction = nil
        lastSystemCriticalMonitorSource = nil
        lastSystemCriticalWindowCount = 0
        lastSystemCriticalWindowTitleHashes = []
        lastSystemCriticalWindowTitleLengths = []
        lastSystemCriticalWindowTitleIsEmpty = []
        lastSystemCriticalWindowOwners = []
        lastSystemCriticalOverlayLevel = nil
        systemCriticalDetectionCount = 0
        invalidateSystemCriticalMonitoring()
        screenshotTask?.cancel()
        screenshotTask = nil
        screenshotSession = ScreenshotCaptureSession()
        clearSnapshotState()
        view.onEscape = { [weak self] in
            self?.hide(reason: .escape)
        }
        view.onCommitSelection = { [weak self] selection, source in
            self?.commitSelection(selection, source: source)
        }
        view.apply(viewModel: nil)
        view.beginPerformanceFirstFrameMeasurement()
        coordinator.openQuickSwitch()
        coordinator.promoteForTextInput()
        view.window?.makeFirstResponder(view)
        overlayOpenElapsedMilliseconds = elapsedSinceShowStart()
        updateLifecycleWindowHighWaterMark()
        startSystemCriticalMonitoring()
        scheduleSnapshotRefresh(for: generation)
        DevelopmentDiagnostics.log("quickSwitch.session.show.end", [
            "generation": generation,
            "overlayOpenElapsedMilliseconds": overlayOpenElapsedMilliseconds,
            "overlayLevel": coordinator.currentLevel,
            "windowVisible": view.window?.isVisible ?? false
        ])
    }

    func hide(reason: DismissReason = .userClosed) {
        DevelopmentDiagnostics.log("quickSwitch.session.hide.start", [
            "reason": Self.dismissReasonString(reason),
            "wasVisible": isVisible,
            "generation": sessionGeneration
        ])
        sessionGeneration += 1
        lastDismissReason = reason
        snapshotTask?.cancel()
        snapshotTask = nil
        screenshotTask?.cancel()
        screenshotTask = nil
        invalidateSystemCriticalMonitoring()
        coordinator.closeQuickSwitch(reason: reason)
        lifecycleResidualOverlayWindows = overlayWindowCount()
        lifecycleResidualVisibleOverlayWindows = visibleOverlayWindowCount()
        updateLifecycleWindowHighWaterMark()
        DevelopmentDiagnostics.log("quickSwitch.session.hide.end", [
            "reason": Self.dismissReasonString(reason),
            "generation": sessionGeneration,
            "residualOverlayWindows": lifecycleResidualOverlayWindows,
            "residualVisibleOverlayWindows": lifecycleResidualVisibleOverlayWindows
        ])
    }

    func refocus() {
        DevelopmentDiagnostics.log("quickSwitch.session.refocus")
        coordinator.promoteForTextInput()
        view.window?.makeFirstResponder(view)
    }

    func retriggerFromShortcut() {
        DevelopmentDiagnostics.log("quickSwitch.session.retriggerFromShortcut")
        show()
    }

    func reportDictionary() -> [String: Any] {
        let spaceCount = currentViewModel?.spaceCount ?? 0
        let appCount = currentViewModel?.appShelf.count ?? 0
        let columnCount = currentViewModel?.waterfallColumns.count ?? 0
        let windowCount = currentViewModel?.windowCount ?? 0

        return [
            "snapshotLoaded": currentSnapshot != nil,
            "snapshotError": lastSnapshotError ?? NSNull(),
            "quickSwitchVisible": isVisible,
            "diagnosticLogLocationKind": DevelopmentDiagnostics.pathSummary(DevelopmentDiagnostics.logPath)["locationKind"] ?? "unknown",
            "diagnosticLogBasename": DevelopmentDiagnostics.pathSummary(DevelopmentDiagnostics.logPath)["basename"] ?? "aligner-dev.log",
            "displayCount": currentViewModel?.displays.count ?? 0,
            "spaceCount": spaceCount,
            "appCount": appCount,
            "columnCount": columnCount,
            "windowCount": windowCount,
            "initialSelectionWindowID": currentViewModel?.initialSelection?.windowID ?? NSNull(),
            "appShelfNames": currentViewModel?.appShelf.map(\.app.name) ?? [],
            "spaceLabels": currentViewModel?.displays.flatMap { $0.spaces.map(\.label) } ?? [],
            "overlayOpenElapsedMilliseconds": overlayOpenElapsedMilliseconds ?? NSNull(),
            "snapshotStartElapsedMilliseconds": snapshotStartElapsedMilliseconds ?? NSNull(),
            "snapshotDurationMilliseconds": snapshotDurationMilliseconds ?? NSNull(),
            "snapshotRanOnMainThread": snapshotRanOnMainThread ?? NSNull(),
            "lastCommittedAppGroupIndex": lastCommittedSelection?.appGroupIndex ?? NSNull(),
            "lastCommittedWindowIndex": lastCommittedSelection?.windowIndex ?? NSNull(),
            "lastCommittedWindowID": lastCommittedSelection?.windowID ?? NSNull(),
            "lastCommitSource": lastCommitSource?.rawValue ?? NSNull(),
            "lastActivationWindowID": lastActivationWindowID ?? NSNull(),
            "lastActivationResult": lastActivationResult.map(Self.activationResultString) ?? NSNull(),
            "lastActivationError": lastActivationError ?? NSNull(),
            "lastDismissReason": lastDismissReason.map(Self.dismissReasonString) ?? NSNull(),
            "overlayLevel": Int(coordinator.currentLevel),
            "overlayMainMenuLevel": Int(CGWindowLevelForKey(.mainMenuWindow)),
            "overlayBelowRescueSystemWindows": coordinator.currentLevel < CGWindowLevelForKey(.mainMenuWindow),
            "lastSystemCriticalAction": lastSystemCriticalAction ?? NSNull(),
            "lastSystemCriticalMonitorSource": lastSystemCriticalMonitorSource ?? NSNull(),
            "lastSystemCriticalWindowCount": lastSystemCriticalWindowCount,
            "lastSystemCriticalWindowTitleHashes": lastSystemCriticalWindowTitleHashes,
            "lastSystemCriticalWindowTitleLengths": lastSystemCriticalWindowTitleLengths,
            "lastSystemCriticalWindowTitleIsEmpty": lastSystemCriticalWindowTitleIsEmpty,
            "lastSystemCriticalWindowOwners": lastSystemCriticalWindowOwners,
            "lastSystemCriticalOverlayLevel": lastSystemCriticalOverlayLevel.map { Int($0) } ?? NSNull(),
            "systemCriticalDetectionCount": systemCriticalDetectionCount,
            "lifecycleTargetCycles": lifecycleTargetCycles,
            "lifecycleCompletedCycles": lifecycleCompletedCycles,
            "lifecycleMaximumOverlayWindows": lifecycleMaximumOverlayWindows,
            "lifecycleMaximumVisibleOverlayWindows": lifecycleMaximumVisibleOverlayWindows,
            "lifecycleResidualOverlayWindows": lifecycleResidualOverlayWindows,
            "lifecycleResidualVisibleOverlayWindows": lifecycleResidualVisibleOverlayWindows,
            "lifecycleGatePassed": lifecycleTargetCycles == 0
                || (
                    lifecycleCompletedCycles == lifecycleTargetCycles
                        && lifecycleMaximumOverlayWindows <= 1
                        && lifecycleMaximumVisibleOverlayWindows <= 1
                        && lifecycleResidualOverlayWindows <= 1
                        && lifecycleResidualVisibleOverlayWindows == 0
                ),
            "rootView": view.reportDictionary()
        ]
    }

    func prepareLifecycleRun(targetCycles: Int) {
        lifecycleTargetCycles = max(0, targetCycles)
        lifecycleCompletedCycles = 0
        lifecycleMaximumOverlayWindows = 0
        lifecycleMaximumVisibleOverlayWindows = 0
        lifecycleResidualOverlayWindows = 0
        lifecycleResidualVisibleOverlayWindows = 0
        view.resetPerformanceMeasurements()
    }

    func markLifecycleCycleCompleted() {
        lifecycleCompletedCycles += 1
        updateLifecycleWindowHighWaterMark()
    }

    func finalizeLifecycleRun() {
        lifecycleResidualOverlayWindows = overlayWindowCount()
        lifecycleResidualVisibleOverlayWindows = visibleOverlayWindowCount()
        updateLifecycleWindowHighWaterMark()
    }

    private func scheduleSnapshotRefresh(for generation: Int) {
        DevelopmentDiagnostics.log("quickSwitch.snapshot.schedule", [
            "generation": generation,
            "visible": isVisible
        ])
        snapshotTask?.cancel()
        let loader = snapshotLoader
        let showStartTime = showStartTime
        snapshotTask = Task { [weak self] in
            guard let self, !Task.isCancelled else { return }

            let loadTask = Task.detached(priority: .userInitiated) {
                SnapshotLoadResult.load(using: loader, showStartTime: showStartTime)
            }
            let result = await withTaskCancellationHandler {
                await loadTask.value
            } onCancel: {
                loadTask.cancel()
            }

            guard !Task.isCancelled else { return }
            self.applySnapshotResult(result, generation: generation)
        }
    }

    private func clearSnapshotState() {
        currentSnapshot = nil
        currentViewModel = nil
        lastSnapshotError = nil
    }

    private func startSystemCriticalMonitoring() {
        invalidateSystemCriticalMonitoring()
        checkForSystemCriticalWindows(source: "initial")
        guard isVisible else { return }

        let monitorTimer = Timer(timeInterval: 0.20, repeats: true) { [weak self] _ in
            Task { @MainActor [weak self] in
                self?.checkForSystemCriticalWindows(source: "poll")
            }
        }
        RunLoop.main.add(monitorTimer, forMode: .common)
        systemCriticalMonitorTimer = monitorTimer

        if let debugSystemCriticalAfter {
            let debugTimer = Timer(timeInterval: debugSystemCriticalAfter, repeats: false) { [weak self] _ in
                Task { @MainActor [weak self] in
                    self?.handleSystemCriticalWindows(
                        [
                            SystemCriticalWindowRecord(
                                ownerName: "SecurityAgent",
                                title: "Debug Security Confirmation",
                                processIdentifier: 0,
                                layer: Int(CGWindowLevelForKey(.mainMenuWindow)),
                                bounds: .zero
                            )
                        ],
                        source: "debug"
                    )
                }
            }
            RunLoop.main.add(debugTimer, forMode: .common)
            debugSystemCriticalTimer = debugTimer
        }
    }

    private func invalidateSystemCriticalMonitoring() {
        systemCriticalMonitorTimer?.invalidate()
        systemCriticalMonitorTimer = nil
        debugSystemCriticalTimer?.invalidate()
        debugSystemCriticalTimer = nil
    }

    private func checkForSystemCriticalWindows(source: String) {
        guard isVisible else { return }

        let criticalWindows = systemCriticalWindowDetector.visibleSystemCriticalWindows()
        guard !criticalWindows.isEmpty else { return }

        handleSystemCriticalWindows(criticalWindows, source: source)
    }

    private func handleSystemCriticalWindows(_ windows: [SystemCriticalWindowRecord], source: String) {
        guard isVisible, !windows.isEmpty else { return }

        systemCriticalDetectionCount += 1
        lastSystemCriticalAction = "closeOverlay"
        lastSystemCriticalMonitorSource = source
        lastSystemCriticalWindowCount = windows.count
        lastSystemCriticalWindowTitleHashes = windows.map { DevelopmentDiagnostics.stableFingerprint($0.title) }
        lastSystemCriticalWindowTitleLengths = windows.map { $0.title.count }
        lastSystemCriticalWindowTitleIsEmpty = windows.map { $0.title.isEmpty }
        lastSystemCriticalWindowOwners = windows.map(\.ownerName)
        lastSystemCriticalOverlayLevel = coordinator.currentLevel
        hide(reason: .systemCriticalWindow)
        onSnapshotUpdated?()
    }

    private func commitSelection(_ selection: QuickSwitchSelection, source: QuickSwitchCommitSource) {
        DevelopmentDiagnostics.log("quickSwitch.activation.commit.start", [
            "source": source.rawValue,
            "appGroupIndex": selection.appGroupIndex,
            "windowIndex": selection.windowIndex,
            "windowID": selection.windowID
        ])
        lastCommittedSelection = selection
        lastCommitSource = source
        lastActivationWindowID = selection.windowID
        lastActivationError = nil

        guard let window = window(for: selection) else {
            lastActivationResult = .windowNotFound
            DevelopmentDiagnostics.log("quickSwitch.activation.commit.windowNotFound", [
                "source": source.rawValue,
                "appGroupIndex": selection.appGroupIndex,
                "windowIndex": selection.windowIndex,
                "windowID": selection.windowID
            ])
            onSnapshotUpdated?()
            return
        }

        DevelopmentDiagnostics.log("quickSwitch.activation.commit.hideBeforeActivation", [
            "source": source.rawValue,
            "windowID": window.id
        ])
        hide(reason: .userClosed)

        do {
            lastActivationResult = try windowActivationService.activate(window: window)
            DevelopmentDiagnostics.log("quickSwitch.activation.commit.result", [
                "source": source.rawValue,
                "windowID": window.id,
                "appName": window.app.name,
                "appPID": window.app.processIdentifier,
                "titleHash": DevelopmentDiagnostics.stableFingerprint(window.title),
                "titleLength": window.title.count,
                "titleIsEmpty": window.title.isEmpty,
                "result": lastActivationResult.map(Self.activationResultString)
            ])
        } catch {
            let errorSummary = DevelopmentDiagnostics.errorSummaryString(error)
            lastActivationResult = .failed(errorSummary)
            lastActivationError = errorSummary
            var fields: [String: CustomStringConvertible?] = [
                "source": source.rawValue,
                "windowID": window.id,
                "appName": window.app.name,
                "titleHash": DevelopmentDiagnostics.stableFingerprint(window.title),
                "titleLength": window.title.count,
                "titleIsEmpty": window.title.isEmpty
            ]
            DevelopmentDiagnostics.errorSummaryFields(error).forEach { fields[$0.key] = $0.value }
            DevelopmentDiagnostics.log("quickSwitch.activation.commit.error", fields)
        }

        if shouldCloseAfterActivation(lastActivationResult) {
            DevelopmentDiagnostics.log("quickSwitch.activation.commit.closeAfterActivation", [
                "result": lastActivationResult.map(Self.activationResultString)
            ])
        } else {
            DevelopmentDiagnostics.log("quickSwitch.activation.commit.refreshAfterActivation", [
                "result": lastActivationResult.map(Self.activationResultString)
            ])
        }
        onSnapshotUpdated?()
    }

    private func shouldCloseAfterActivation(_ result: WindowActivationResult?) -> Bool {
        switch result {
        case .activated, .restored, .appActivatedOnly:
            return true
        case .windowNotFound, .unsupported, .activationFailed, .failed, nil:
            return false
        }
    }

    private func window(for selection: QuickSwitchSelection) -> AlignerWindow? {
        currentViewModel?
            .waterfallColumns
            .flatMap(\.windows)
            .first { card in
                card.appGroupIndex == selection.appGroupIndex
                    && card.windowIndex == selection.windowIndex
                    && card.window.id == selection.windowID
            }?
            .window
    }

    private func applySnapshotResult(_ result: SnapshotLoadResult, generation: Int) {
        guard generation == sessionGeneration, isVisible else {
            DevelopmentDiagnostics.log("quickSwitch.snapshot.drop", [
                "resultGeneration": generation,
                "currentGeneration": sessionGeneration,
                "visible": isVisible
            ])
            return
        }

        switch result {
        case .success(let success):
            currentSnapshot = success.snapshot
            currentViewModel = success.viewModel
            lastSnapshotError = nil
            snapshotStartElapsedMilliseconds = success.timing.startElapsedMilliseconds
            snapshotDurationMilliseconds = success.timing.durationMilliseconds
            snapshotRanOnMainThread = success.timing.ranOnMainThread
            view.apply(viewModel: success.viewModel)
            view.recordPerformanceFirstFrameIfNeeded()
            view.performDebugKeyboardCommands(debugKeySequence)
            view.performDebugMouseCommands(debugMouseSequence)
            DevelopmentDiagnostics.log("quickSwitch.snapshot.success", [
                "generation": generation,
                "displayCount": success.viewModel.displays.count,
                "spaceCount": success.viewModel.spaceCount,
                "appCount": success.viewModel.appShelf.count,
                "windowCount": success.viewModel.windowCount,
                "durationMilliseconds": success.timing.durationMilliseconds,
                "ranOnMainThread": success.timing.ranOnMainThread,
                "initialSelectionWindowID": success.viewModel.initialSelection?.windowID
            ])
            guard isVisible else { return }
            if disableScreenshotRefresh {
                view.markScreenshotsNotRequested(for: success.viewModel, reason: "disabledByLaunchOption")
                screenshotTask?.cancel()
                screenshotTask = nil
                DevelopmentDiagnostics.log("quickSwitch.screenshot.disabledByLaunchOption", [
                    "generation": generation
                ])
            } else {
                scheduleScreenshotRefresh(for: success.viewModel, generation: generation)
            }
        case .failure(let failure):
            currentSnapshot = nil
            currentViewModel = nil
            lastSnapshotError = failure.message
            snapshotStartElapsedMilliseconds = failure.timing.startElapsedMilliseconds
            snapshotDurationMilliseconds = failure.timing.durationMilliseconds
            snapshotRanOnMainThread = failure.timing.ranOnMainThread
            view.apply(viewModel: nil)
            screenshotTask?.cancel()
            screenshotTask = nil
            DevelopmentDiagnostics.log("quickSwitch.snapshot.failure", [
                "generation": generation,
                "message": failure.message,
                "durationMilliseconds": failure.timing.durationMilliseconds,
                "ranOnMainThread": failure.timing.ranOnMainThread
            ])
        }

        onSnapshotUpdated?()
    }

    private func scheduleScreenshotRefresh(
        for viewModel: QuickSwitchViewModel,
        generation: Int
    ) {
        screenshotTask?.cancel()
        let provider = screenshotProvider
        let session = screenshotSession
        let allWindows = viewModel.waterfallColumns.flatMap { column in
            column.windows.map(\.window)
        }
        let windows = allWindows.filter(Self.shouldRequestScreenshot)
        let skippedWindows = allWindows.filter { !Self.shouldRequestScreenshot(for: $0) }
        DevelopmentDiagnostics.log("quickSwitch.screenshot.schedule", [
            "generation": generation,
            "eligibleCount": windows.count,
            "skippedCount": skippedWindows.count
        ])

        for window in skippedWindows {
            view.markScreenshotNotRequested(for: window.id, reason: "skeletonPreferred")
        }
        if !skippedWindows.isEmpty {
            onSnapshotUpdated?()
        }
        guard !windows.isEmpty else {
            screenshotTask = nil
            return
        }

        screenshotTask = Task { [weak self] in
            guard let self else { return }

            var retryWindows: [AlignerWindow] = []
            for window in windows {
                guard !Task.isCancelled else { return }
                let resolution = await provider.resolvedScreenshot(for: window, in: session)
                guard !Task.isCancelled, generation == self.sessionGeneration, self.isVisible else { return }
                self.view.applyScreenshot(resolution, for: window.id)
                DevelopmentDiagnostics.log("quickSwitch.screenshot.resolved", [
                    "generation": generation,
                    "windowID": window.id,
                    "appName": window.app.name,
                    "source": Self.screenshotSourceString(resolution.source)
                ])
                self.onSnapshotUpdated?()

                if case .skeletonFallback(let reason) = resolution.source,
                   Self.shouldRetryScreenshot(after: reason) {
                    retryWindows.append(window)
                }
            }

            for window in retryWindows {
                guard !Task.isCancelled else { return }
                let retryResolution = await provider.resolvedScreenshot(for: window, in: session)
                guard !Task.isCancelled, generation == self.sessionGeneration, self.isVisible else { return }
                self.view.applyScreenshot(retryResolution, for: window.id)
                DevelopmentDiagnostics.log("quickSwitch.screenshot.retryResolved", [
                    "generation": generation,
                    "windowID": window.id,
                    "appName": window.app.name,
                    "source": Self.screenshotSourceString(retryResolution.source)
                ])
                self.onSnapshotUpdated?()
            }
        }
    }

    private static func shouldRequestScreenshot(for window: AlignerWindow) -> Bool {
        switch ThumbnailPolicy.preferredStrategy(for: window.app.category) {
        case .screenshotPreferred:
            return true
        case .skeletonPreferred, .fallbackSkeleton:
            return false
        }
    }

    private static func shouldRetryScreenshot(after reason: ScreenshotFallbackReason) -> Bool {
        switch reason {
        case .screenRecordingDenied, .syntheticWindowID, .retryLimitReached:
            return false
        case .captureFailed, .timedOut, .invalidCapture:
            return true
        }
    }

    private func elapsedSinceShowStart() -> Double? {
        guard let showStartTime else { return nil }
        return (CACurrentMediaTime() - showStartTime) * 1000
    }

    private func updateLifecycleWindowHighWaterMark() {
        lifecycleMaximumOverlayWindows = max(
            lifecycleMaximumOverlayWindows,
            overlayWindowCount()
        )
        lifecycleMaximumVisibleOverlayWindows = max(
            lifecycleMaximumVisibleOverlayWindows,
            visibleOverlayWindowCount()
        )
    }

    private func overlayWindowCount() -> Int {
        NSApp.windows.filter { window in
            window.title == Self.overlayTitle
        }.count
    }

    private func visibleOverlayWindowCount() -> Int {
        NSApp.windows.filter { window in
            window.title == Self.overlayTitle && window.isVisible
        }.count
    }

    private static func activationResultString(_ result: WindowActivationResult) -> String {
        switch result {
        case .activated:
            return "activated"
        case .restored:
            return "restored"
        case .appActivatedOnly:
            return "appActivatedOnly"
        case .windowNotFound:
            return "windowNotFound"
        case .unsupported:
            return "unsupported"
        case .activationFailed:
            return "activationFailed"
        case .failed(let message):
            return "failed(\(message))"
        }
    }

    private static func screenshotSourceString(_ source: ScreenshotResolutionSource) -> String {
        switch source {
        case .realScreenshot:
            return "realScreenshot"
        case .skeletonFallback(let reason):
            return "skeletonFallback(\(reason))"
        }
    }

    private static func dismissReasonString(_ reason: DismissReason) -> String {
        switch reason {
        case .escape:
            return "escape"
        case .focusLost:
            return "focusLost"
        case .systemCriticalWindow:
            return "systemCriticalWindow"
        case .timeout:
            return "timeout"
        case .userClosed:
            return "userClosed"
        }
    }

}

private struct SnapshotLoadTiming: Sendable {
    let startElapsedMilliseconds: Double?
    let durationMilliseconds: Double
    let ranOnMainThread: Bool
}

private struct SnapshotLoadSuccess: Sendable {
    let snapshot: QuickSwitchSnapshot
    let viewModel: QuickSwitchViewModel
    let timing: SnapshotLoadTiming
}

private struct SnapshotLoadFailure: Sendable {
    let message: String
    let timing: SnapshotLoadTiming
}

private enum SnapshotLoadResult: Sendable {
    case success(SnapshotLoadSuccess)
    case failure(SnapshotLoadFailure)

    static func load(
        using loader: any QuickSwitchSnapshotLoading,
        showStartTime: CFTimeInterval?
    ) -> SnapshotLoadResult {
        let startedAt = CACurrentMediaTime()
        let startedOnMainThread = Thread.isMainThread

        do {
            let load = try loader.snapshot()
            let viewModel = QuickSwitchViewModelBuilder.viewModel(
                from: load.snapshot,
                currentSpaceIDs: load.currentSpaceIDs
            )
            return .success(SnapshotLoadSuccess(
                snapshot: load.snapshot,
                viewModel: viewModel,
                timing: SnapshotLoadTiming(
                    startElapsedMilliseconds: showStartTime.map { (startedAt - $0) * 1000 },
                    durationMilliseconds: (CACurrentMediaTime() - startedAt) * 1000,
                    ranOnMainThread: startedOnMainThread
                )
            ))
        } catch {
            return .failure(SnapshotLoadFailure(
                message: DevelopmentDiagnostics.errorSummaryString(error),
                timing: SnapshotLoadTiming(
                    startElapsedMilliseconds: showStartTime.map { (startedAt - $0) * 1000 },
                    durationMilliseconds: (CACurrentMediaTime() - startedAt) * 1000,
                    ranOnMainThread: startedOnMainThread
                )
            ))
        }
    }
}

struct Round1QuickSwitchLaunchOptions {
    let openQuickSwitch: Bool
    let simulateAccessibilityDenied: Bool
    let simulateScreenRecordingDenied: Bool
    let autoHideAfter: TimeInterval?
    let quitAfter: TimeInterval?
    let reportPath: String?
    let snapshotLoadDelay: TimeInterval?
    let fixtureAppCount: Int?
    let fixtureWindowsPerApp: Int?
    let fixtureCandidateFiltering: Bool
    let fixtureActivation: Bool
    let debugHoveredAppGroupIndex: Int?
    let debugOverlayWidth: CGFloat?
    let debugKeySequence: [String]
    let debugMouseSequence: [String]
    let debugSystemCriticalAfter: TimeInterval?
    let debugWindowActivation: Bool
    let disableScreenshotRefresh: Bool
    let lifecycleCycles: Int?
    let lifecycleInterval: TimeInterval
    let lifecycleVisibleDuration: TimeInterval

    static func parse(arguments: [String]) -> Round1QuickSwitchLaunchOptions {
        Round1QuickSwitchLaunchOptions(
            openQuickSwitch: arguments.contains("--round01-open-quick-switch"),
            simulateAccessibilityDenied: arguments.contains("--round01-simulate-accessibility-denied"),
            simulateScreenRecordingDenied: arguments.contains("--round01-simulate-screen-recording-denied"),
            autoHideAfter: timeInterval(for: "--round01-quick-switch-auto-hide-after", in: arguments),
            quitAfter: timeInterval(for: "--round01-quick-switch-quit-after", in: arguments),
            reportPath: stringValue(for: "--round01-quick-switch-report", in: arguments),
            snapshotLoadDelay: timeInterval(for: "--round01-snapshot-load-delay", in: arguments),
            fixtureAppCount: intValue(for: "--round01-fixture-app-count", in: arguments),
            fixtureWindowsPerApp: intValue(for: "--round01-fixture-windows-per-app", in: arguments),
            fixtureCandidateFiltering: arguments.contains("--round01-fixture-candidate-filtering"),
            fixtureActivation: arguments.contains("--round01-fixture-window-activation"),
            debugHoveredAppGroupIndex: intValue(for: "--round01-debug-hover-app-index", in: arguments),
            debugOverlayWidth: cgFloatValue(for: "--round01-debug-overlay-width", in: arguments),
            debugKeySequence: stringListValue(for: "--round01-debug-key-sequence", in: arguments),
            debugMouseSequence: stringListValue(for: "--round01-debug-mouse-sequence", in: arguments),
            debugSystemCriticalAfter: timeInterval(for: "--round01-debug-system-critical-after", in: arguments),
            debugWindowActivation: arguments.contains("--round01-debug-window-activation"),
            disableScreenshotRefresh: arguments.contains("--round01-disable-screenshot-refresh"),
            lifecycleCycles: intValue(for: "--round01-quick-switch-lifecycle-cycles", in: arguments),
            lifecycleInterval: timeInterval(for: "--round01-quick-switch-lifecycle-interval", in: arguments) ?? 0.02,
            lifecycleVisibleDuration: timeInterval(for: "--round01-quick-switch-lifecycle-visible-duration", in: arguments) ?? 0.16
        )
    }

    private static func timeInterval(for key: String, in arguments: [String]) -> TimeInterval? {
        let prefix = "\(key)="
        guard let argument = arguments.first(where: { $0.hasPrefix(prefix) }) else {
            return nil
        }

        return TimeInterval(argument.dropFirst(prefix.count))
    }

    private static func stringValue(for key: String, in arguments: [String]) -> String? {
        let prefix = "\(key)="
        guard let argument = arguments.first(where: { $0.hasPrefix(prefix) }) else {
            return nil
        }

        return String(argument.dropFirst(prefix.count))
    }

    private static func intValue(for key: String, in arguments: [String]) -> Int? {
        stringValue(for: key, in: arguments).flatMap(Int.init)
    }

    private static func cgFloatValue(for key: String, in arguments: [String]) -> CGFloat? {
        stringValue(for: key, in: arguments)
            .flatMap(Double.init)
            .map { CGFloat($0) }
    }

    private static func stringListValue(for key: String, in arguments: [String]) -> [String] {
        guard let value = stringValue(for: key, in: arguments) else { return [] }

        return value
            .split(separator: ",")
            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
            .filter { !$0.isEmpty }
    }
}

@MainActor
private final class StderrScreenshotDebugLogger: ScreenshotDebugLogging {
    func record(_ event: ScreenshotDebugEvent) {
        DevelopmentDiagnostics.log("quickSwitch.screenshot.debug", [
            "event": event.diagnosticDescription
        ])
        fputs("Round01 screenshot debug: \(event.diagnosticDescription)\n", stderr)
    }
}
