using System.Net.Http;
using System.Diagnostics;
using System.Windows;
using Microsoft.Extensions.Configuration;
using NexusShell.Agent;
using NexusShell.Models;
using NexusShell.Services;
using NexusShell.Services.ControlCenter;
using NexusShell.Services.Deployment;
using NexusShell.Services.Diagnostics;
using NexusShell.Services.Identity;
using NexusShell.Services.Policy;
using NexusShell.Services.Workspace;
using NexusShell.ViewModels;

namespace NexusShell;

public partial class App : Application
{
    public static AppServices Services { get; private set; } = null!;

    private void App_OnStartup(object sender, StartupEventArgs e)
    {
        var startupSw = Stopwatch.StartNew();

        if (e.Args.Any(static arg => string.Equals(arg, "--restore-taskbar", StringComparison.OrdinalIgnoreCase)))
        {
            new ShellEnvironmentService().Restore();
            Shutdown();
            return;
        }

        SafePocRuntime.Initialize(e.Args);

        if (!SafePocRuntime.AllowsLockdown)
        {
            MessageBox.Show(
                SafePocRuntime.SafeModeMessage,
                "Ninja Nexus — Safe POC",
                MessageBoxButton.OK,
                MessageBoxImage.Information);
        }

        var configuration = new ConfigurationBuilder()
            .SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: false)
            .Build();

        var authority = configuration["Identity:Authority"] ?? "http://localhost:5000";
        var clientId = configuration["Identity:ClientId"] ?? "nexus-shell";
        var controlCenterBaseUrl = configuration["ControlCenter:BaseUrl"];
        var manifestUrl = configuration["Update:ManifestUrl"]
            ?? "https://nexus.ninjakernen.info/downloads/latest.json";
        var autoInstall = !string.Equals(configuration["Update:AutoInstall"], "false", StringComparison.OrdinalIgnoreCase);
        var checkOnStartup = !string.Equals(configuration["Update:CheckOnStartup"], "false", StringComparison.OrdinalIgnoreCase);

        var clientVersion = ClientVersionInfo.LoadDefault();

        var eventLog = new WorkspaceEventLog();
        var sessionManager = new DiagnosticSessionManager(eventLog);
        var diagnosticsService = new DiagnosticsService(eventLog, sessionManager);
        var windowEventTracker = new WindowEventTracker(diagnosticsService);
        var appLaunchTracker = new AppLaunchTracker(diagnosticsService);
        var workspaceWindowManager = new WorkspaceWindowManager(diagnosticsService, windowEventTracker, appLaunchTracker);

        var profileService = new ProfileService();
        diagnosticsService.TrackOperation("profile_load", () => profileService.LoadProfile());
        var policyStore = new NexusPolicyStore();
        var policyEvaluator = new NexusPolicyEvaluator();
        var catalogService = new AppCatalogService();
        diagnosticsService.TrackOperation("app_catalog_load", catalogService.Load);

        var userSettingsService = new UserSettingsService();
        var themeService = new ThemeService();
        var displaySettingsService = new DisplaySettingsService();
        var deviceInfoService = new NexusDeviceInfoService();
        var networkInfoService = new NexusNetworkInfoService();
        var audioService = new NexusAudioService();
        var bluetoothInfoService = new NexusBluetoothInfoService();
        var printerInfoService = new NexusPrinterInfoService();
        var cpuService = new NexusCpuService();
        var memoryService = new NexusMemoryService();
        var diskService = new NexusDiskService();
        var gpuService = new NexusGpuService();
        var networkService = new NexusNetworkService(networkInfoService);
        var displayService = new NexusDisplayService(displaySettingsService);
        var printerService = new NexusPrinterService(printerInfoService);
        var usbService = new NexusUsbService();
        var bluetoothService = new NexusBluetoothService(bluetoothInfoService);
        var processService = new NexusProcessService();
        var hardwareService = new NexusHardwareService(
            deviceInfoService,
            cpuService,
            memoryService,
            diskService,
            gpuService,
            networkService,
            displayService,
            printerService,
            usbService,
            bluetoothService,
            processService);
        var shellEnvironmentService = new ShellEnvironmentService();
        var fileSystemService = new NexusFileSystemService();
        var navigationService = new NexusNavigationService(fileSystemService);
        var searchService = new NexusSearchService();
        var favoritesService = new NexusFavoritesService(fileSystemService);
        var previewService = new NexusPreviewService();
        var defaultAppsService = new NexusDefaultAppsService();
        var fileOpenService = new NexusFileOpenService(defaultAppsService);
        var nexusTabService = new NexusTabService();
        var browserNavigationService = new NexusBrowserNavigationService();
        var nexusBrowserService = new NexusBrowserService(nexusTabService, browserNavigationService);
        var nexusCalculatorService = new NexusCalculatorService();
        var nexusMediaMetadataService = new NexusMediaMetadataService();
        var nexusMediaLibraryService = new NexusMediaLibraryService(nexusMediaMetadataService);
        var nexusMediaPlayerService = new NexusMediaPlayerService(nexusMediaLibraryService);
        var nexusMediaQueueService = new NexusQueueService();
        var nexusPlaylistService = new NexusPlaylistService();
        var nexusMediaFavoritesService = new NexusMediaFavoritesService();
        var nexusMediaRecentService = new NexusMediaRecentService();
        var photosLibraryService = new NexusPhotosLibraryService();
        var photosThumbnailService = new NexusThumbnailService();
        var photosViewerService = new NexusImageViewerService();
        var photosSlideshowService = new NexusSlideshowService();
        var photosMetadataService = new NexusMetadataService();
        var photosFavoritesService = new NexusPhotosFavoritesService();
        var nexusPackageReader = new NexusPackageReader();
        var nexusPackageValidator = new NexusPackageValidator();
        var nexusPackageRepository = new NexusPackageRepository(nexusPackageReader, nexusPackageValidator);
        var nexusPackageRegistry = new NexusPackageRegistry(nexusPackageRepository);
        var nexusRollbackService = new NexusRollbackService(nexusPackageRepository);
        var nexusPackageInstaller = new NexusPackageInstaller(
            nexusPackageRepository, nexusPackageReader, nexusPackageValidator);
        var nexusPackageUpdater = new NexusPackageUpdater(
            nexusPackageRepository, nexusPackageInstaller, nexusRollbackService);
        var nexusInstallQueue = new NexusInstallQueue();
        var nexusInstalledAppsService = new NexusInstalledAppsService();
        var nexusDeploymentService = new NexusDeploymentService(
            nexusInstallQueue,
            nexusPackageRegistry,
            nexusPackageInstaller,
            nexusPackageUpdater,
            nexusRollbackService,
            nexusPackageRepository,
            nexusInstalledAppsService);
        var nexusPackageService = new NexusPackageService(
            nexusPackageRepository, nexusPackageValidator, registry: nexusPackageRegistry);
        diagnosticsService.TrackOperation("package_catalog_reload", nexusPackageService.Reload);

        var lockdownService = new LockdownService(SafePocRuntime.AllowsLockdown);
        var platformLockService = new NexusPlatformLockService(lockdownService);
        var httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
        var agentHttpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
        var platformHttpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
        var platformApiBaseUrl = string.IsNullOrWhiteSpace(controlCenterBaseUrl) ? null : controlCenterBaseUrl.Trim();
        var controlCenterApiClient = new NexusControlCenterApiClient(platformHttpClient, platformApiBaseUrl);
        var remoteEnrollmentClient = new NexusRemoteEnrollmentClient(platformHttpClient, platformApiBaseUrl);

        var organizationService = new NexusOrganizationService();
        var identityUserService = new NexusUserProfileService();
        var deviceTrustService = new NexusDeviceTrustService();
        var enrollmentService = new NexusEnrollmentService(
            organizationService, identityUserService, deviceTrustService, remoteEnrollmentClient);
        var identityService = new NexusIdentityService(
            organizationService, identityUserService, enrollmentService, deviceTrustService);
        diagnosticsService.TrackOperation("identity_state_load", identityService.LoadAll);
        enrollmentService.RefreshVersions(clientVersion.Version, NexusAgentConfig.AgentVersion);

        var policyService = new NexusPolicyService(policyStore, policyEvaluator, profileService, identityService);

        var agentConfig = NexusAgentConfig.Load(
            authority,
            clientVersion.Version,
            identityService.Enrollment.CurrentDevice?.DeviceId);
        var agentInventoryService = new NexusInventoryService(hardwareService);
        var agentHealthService = new NexusHealthService(hardwareService);
        var agentApiClient = new NexusApiClient(agentHttpClient, agentConfig);
        var agentRegistrationService = new NexusDeviceRegistrationService(
            agentApiClient, agentConfig, agentInventoryService, clientVersion);
        var agentPresenceService = new NexusPresenceService(identityService);
        var agentDeviceStatusService = new NexusDeviceStatusService(
            agentPresenceService, agentHealthService, agentConfig, clientVersion);
        var agentHeartbeatDispatcher = new NexusHeartbeatDispatcher(
            agentApiClient, agentConfig, agentPresenceService, agentDeviceStatusService);
        var nexusAgentService = new NexusAgentService(
            agentConfig,
            agentInventoryService,
            agentHealthService,
            agentRegistrationService,
            agentHeartbeatDispatcher,
            agentPresenceService,
            agentDeviceStatusService,
            clientVersion.Version,
            identityService,
            policyService);
        var agentLocalClient = new NexusAgentLocalClient(agentConfig.LocalApiUrl);
        var controlCenterService = new NexusControlCenterService(
            identityService, agentInventoryService, agentHealthService, controlCenterApiClient);
        var authService = new AuthService(httpClient, profileService, authority, clientId);
        var launchService = new AppLaunchService(catalogService, profileService, lockdownService, policyService, appLaunchTracker, workspaceWindowManager);
        var systemStatusService = new SystemStatusService();
        var performanceMonitor = new PerformanceMonitorService(systemStatusService, diagnosticsService);
        var developerConsoleService = new DeveloperConsoleService(lockdownService);
        var updateService = new UpdateService(
            httpClient, manifestUrl, clientVersion.Version, clientVersion.Build, autoInstall);
        var nexusCommandRegistry = new NexusCommandRegistry();
        var nexusConsoleAuditService = new NexusConsoleAuditService();
        var nexusConsoleService = new NexusConsoleService(
            nexusCommandRegistry,
            nexusConsoleAuditService,
            profileService,
            lockdownService,
            platformLockService,
            updateService,
            catalogService,
            systemStatusService,
            policyService);

        var desktopViewModel = new DesktopViewModel(
            profileService, catalogService, launchService, systemStatusService, updateService, userSettingsService, authority, agentLocalClient, policyService, workspaceWindowManager, performanceMonitor, diagnosticsService);
        var launcherViewModel = new LauncherViewModel(catalogService, profileService, launchService, policyService, appLaunchTracker);
        var updateInfoViewModel = new UpdateInfoViewModel(updateService);
        var settingsViewModel = new NexusSettingsViewModel(
            lockdownService,
            platformLockService,
            updateService,
            userSettingsService,
            themeService,
            displaySettingsService,
            profileService,
            deviceInfoService,
            networkInfoService,
            audioService,
            bluetoothInfoService,
            printerInfoService,
            identityService,
            controlCenterService,
            policyService,
            defaultAppsService,
            diagnosticsService,
            performanceMonitor,
            workspaceWindowManager,
            clientVersion);
        var filesViewModel = new NexusFilesViewModel(
            fileSystemService,
            navigationService,
            searchService,
            favoritesService,
            previewService,
            fileOpenService);
        var browserViewModel = new NexusBrowserViewModel(nexusBrowserService);
        var calculatorViewModel = new NexusCalculatorViewModel(nexusCalculatorService);
        var mediaViewModel = new NexusMediaViewModel(
            nexusMediaLibraryService,
            nexusMediaPlayerService,
            nexusMediaQueueService,
            nexusPlaylistService,
            nexusMediaMetadataService,
            nexusMediaFavoritesService,
            nexusMediaRecentService);
        var photosViewModel = new NexusPhotosViewModel(
            photosLibraryService,
            photosThumbnailService,
            photosViewerService,
            photosSlideshowService,
            photosMetadataService,
            photosFavoritesService);
        var nexusStoreService = new NexusStoreService(
            nexusPackageService, nexusInstalledAppsService, nexusDeploymentService, updateService, clientVersion, policyService);
        var storeViewModel = new NexusStoreViewModel(nexusStoreService);
        var deviceManagerViewModel = new NexusDeviceManagerViewModel(hardwareService, agentLocalClient, identityService);
        var setupFlowViewModel = new NexusSetupFlowViewModel(
            identityService, platformLockService, agentConfig, clientVersion.Version);

        themeService.Apply(
            userSettingsService.Current.Theme,
            profileService,
            userSettingsService.Current.AccentColor);

        Services = new AppServices(
            authService,
            profileService,
            catalogService,
            launchService,
            lockdownService,
            platformLockService,
            developerConsoleService,
            nexusConsoleService,
            systemStatusService,
            updateService,
            userSettingsService,
            themeService,
            displaySettingsService,
            shellEnvironmentService,
            policyService,
            new LoginViewModel(authService),
            desktopViewModel,
            launcherViewModel,
            new DeveloperConsoleViewModel(authService, developerConsoleService, lockdownService),
            new NexusConsoleViewModel(nexusConsoleService, profileService),
            settingsViewModel,
            filesViewModel,
            browserViewModel,
            calculatorViewModel,
            mediaViewModel,
            photosViewModel,
            storeViewModel,
            deviceManagerViewModel,
            nexusAgentService,
            agentLocalClient,
            identityService,
            setupFlowViewModel,
            controlCenterService,
            agentConfig,
            nexusBrowserService,
            nexusCalculatorService,
            nexusStoreService,
            updateInfoViewModel,
            defaultAppsService,
            fileOpenService,
            checkOnStartup,
            diagnosticsService,
            performanceMonitor,
            workspaceWindowManager,
            eventLog,
            sessionManager,
            appLaunchTracker);

        var mainWindow = new MainWindow(SafePocRuntime.IsOverlayMode);
        workspaceWindowManager.Initialize(mainWindow);
        fileOpenService.SetRouter(mainWindow);
        platformLockService.LockStateChanged += (_, _) => mainWindow.ApplyShellSettings();
        settingsViewModel.AppearanceChanged += (_, _) => desktopViewModel.RefreshAppearance();
        settingsViewModel.ShellSettingsChanged += (_, _) => mainWindow.ApplyShellSettings();
        settingsViewModel.RequestWindowsUnlock += (_, _) => mainWindow.OpenWindowsUnlockDialog();
        Exit += (_, _) =>
        {
            diagnosticsService.LogLifecycle("app_shutdown", "Ninja Nexus Shell lukker");
            diagnosticsService.StopSession();
            _ = eventLog.DisposeAsync();
            performanceMonitor.Dispose();
            _ = nexusAgentService.StopAsync();
            shellEnvironmentService.Restore();
        };
        DispatcherUnhandledException += (_, args) =>
        {
            shellEnvironmentService.Restore();
            args.Handled = false;
        };
        AppDomain.CurrentDomain.UnhandledException += (_, _) =>
        {
            shellEnvironmentService.Restore();
        };
        TaskScheduler.UnobservedTaskException += (_, args) =>
        {
            shellEnvironmentService.Restore();
            args.SetObserved();
        };

        _ = StartAgentSafelyAsync(nexusAgentService);

        diagnosticsService.EnsureSessionStarted();
        diagnosticsService.LogLifecycle("app_start", "Ninja Nexus Shell startet",
            new Dictionary<string, string>
            {
                ["version"] = clientVersion.Version,
                ["build"] = clientVersion.Build.ToString(),
            });

        var uiLatencyMonitor = new UiLatencyMonitor(performanceMonitor, Dispatcher);
        uiLatencyMonitor.Start();
        performanceMonitor.PerformanceMode = userSettingsService.Current.PerformanceMode;

        mainWindow.Show();
        diagnosticsService.LogLifecycle("shell_ready", "Shell-vindue vist");
        diagnosticsService.LogLifecycle("startup_complete", "Shell startup baseline",
            new Dictionary<string, string>
            {
                ["startupToShellWindowMs"] = startupSw.ElapsedMilliseconds.ToString(),
                ["mode"] = SafePocRuntime.IsOverlayMode ? "overlay" : "fullscreen",
            });

        if (e.Args.Any(static arg => string.Equals(arg, "--capture-design-evidence", StringComparison.OrdinalIgnoreCase)))
        {
            _ = RunDesignEvidenceCaptureAsync(mainWindow);
        }
    }

    private static async Task RunDesignEvidenceCaptureAsync(MainWindow mainWindow)
    {
        try
        {
            await DesignEvidenceCaptureRunner.RunAsync(mainWindow);
        }
        catch (Exception ex)
        {
            MessageBox.Show(
                $"Design evidence capture failed.\n\n{ex.Message}",
                "Ninja Nexus",
                MessageBoxButton.OK,
                MessageBoxImage.Warning);
        }
        finally
        {
            Current.Shutdown();
        }
    }

    private static async Task StartAgentSafelyAsync(NexusAgentService agent)
    {
        try
        {
            await agent.StartAsync();
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"[Nexus Agent] Start failed: {ex.Message}");
        }
    }
}

public sealed class AppServices
{
    public AppServices(
        AuthService authService,
        ProfileService profileService,
        AppCatalogService catalogService,
        AppLaunchService launchService,
        LockdownService lockdownService,
        NexusPlatformLockService platformLockService,
        DeveloperConsoleService developerConsoleService,
        NexusConsoleService nexusConsoleService,
        SystemStatusService systemStatusService,
        UpdateService updateService,
        UserSettingsService userSettingsService,
        ThemeService themeService,
        DisplaySettingsService displaySettingsService,
        ShellEnvironmentService shellEnvironmentService,
        NexusPolicyService policyService,
        LoginViewModel loginViewModel,
        DesktopViewModel desktopViewModel,
        LauncherViewModel launcherViewModel,
        DeveloperConsoleViewModel developerConsoleViewModel,
        NexusConsoleViewModel nexusConsoleViewModel,
        NexusSettingsViewModel settingsViewModel,
        NexusFilesViewModel filesViewModel,
        NexusBrowserViewModel browserViewModel,
        NexusCalculatorViewModel calculatorViewModel,
        NexusMediaViewModel mediaViewModel,
        NexusPhotosViewModel photosViewModel,
        NexusStoreViewModel storeViewModel,
        NexusDeviceManagerViewModel deviceManagerViewModel,
        NexusAgentService nexusAgentService,
        NexusAgentLocalClient agentLocalClient,
        NexusIdentityService identityService,
        NexusSetupFlowViewModel setupFlowViewModel,
        NexusControlCenterService controlCenterService,
        NexusAgentConfig agentConfig,
        NexusBrowserService browserService,
        NexusCalculatorService calculatorService,
        NexusStoreService storeService,
        UpdateInfoViewModel updateInfoViewModel,
        NexusDefaultAppsService defaultAppsService,
        NexusFileOpenService fileOpenService,
        bool checkOnStartup,
        DiagnosticsService diagnosticsService,
        PerformanceMonitorService performanceMonitor,
        WorkspaceWindowManager workspaceWindowManager,
        WorkspaceEventLog eventLog,
        DiagnosticSessionManager sessionManager,
        AppLaunchTracker appLaunchTracker)
    {
        CheckOnStartup = checkOnStartup;
        AuthService = authService;
        ProfileService = profileService;
        CatalogService = catalogService;
        LaunchService = launchService;
        LockdownService = lockdownService;
        PlatformLockService = platformLockService;
        DeveloperConsoleService = developerConsoleService;
        NexusConsoleService = nexusConsoleService;
        SystemStatusService = systemStatusService;
        UpdateService = updateService;
        UserSettingsService = userSettingsService;
        ThemeService = themeService;
        DisplaySettingsService = displaySettingsService;
        ShellEnvironmentService = shellEnvironmentService;
        PolicyService = policyService;
        LoginViewModel = loginViewModel;
        DesktopViewModel = desktopViewModel;
        LauncherViewModel = launcherViewModel;
        DeveloperConsoleViewModel = developerConsoleViewModel;
        NexusConsoleViewModel = nexusConsoleViewModel;
        SettingsViewModel = settingsViewModel;
        FilesViewModel = filesViewModel;
        BrowserViewModel = browserViewModel;
        CalculatorViewModel = calculatorViewModel;
        MediaViewModel = mediaViewModel;
        PhotosViewModel = photosViewModel;
        StoreViewModel = storeViewModel;
        DeviceManagerViewModel = deviceManagerViewModel;
        NexusAgentService = nexusAgentService;
        AgentLocalClient = agentLocalClient;
        IdentityService = identityService;
        SetupFlowViewModel = setupFlowViewModel;
        ControlCenterService = controlCenterService;
        AgentConfig = agentConfig;
        BrowserService = browserService;
        CalculatorService = calculatorService;
        StoreService = storeService;
        UpdateInfoViewModel = updateInfoViewModel;
        DefaultAppsService = defaultAppsService;
        FileOpenService = fileOpenService;
        DiagnosticsService = diagnosticsService;
        PerformanceMonitor = performanceMonitor;
        WorkspaceWindowManager = workspaceWindowManager;
        EventLog = eventLog;
        SessionManager = sessionManager;
        AppLaunchTracker = appLaunchTracker;
    }

    public AuthService AuthService { get; }
    public ProfileService ProfileService { get; }
    public AppCatalogService CatalogService { get; }
    public AppLaunchService LaunchService { get; }
    public LockdownService LockdownService { get; }
    public NexusPlatformLockService PlatformLockService { get; }
    public DeveloperConsoleService DeveloperConsoleService { get; }
    public NexusConsoleService NexusConsoleService { get; }
    public SystemStatusService SystemStatusService { get; }
    public UpdateService UpdateService { get; }
    public UserSettingsService UserSettingsService { get; }
    public ThemeService ThemeService { get; }
    public DisplaySettingsService DisplaySettingsService { get; }
    public ShellEnvironmentService ShellEnvironmentService { get; }
    public NexusPolicyService PolicyService { get; }
    public LoginViewModel LoginViewModel { get; }
    public DesktopViewModel DesktopViewModel { get; }
    public LauncherViewModel LauncherViewModel { get; }
    public DeveloperConsoleViewModel DeveloperConsoleViewModel { get; }
    public NexusConsoleViewModel NexusConsoleViewModel { get; }
    public NexusSettingsViewModel SettingsViewModel { get; }
    public NexusFilesViewModel FilesViewModel { get; }
    public NexusBrowserViewModel BrowserViewModel { get; }
    public NexusCalculatorViewModel CalculatorViewModel { get; }
    public NexusMediaViewModel MediaViewModel { get; }
    public NexusPhotosViewModel PhotosViewModel { get; }
    public NexusStoreViewModel StoreViewModel { get; }
    public NexusDeviceManagerViewModel DeviceManagerViewModel { get; }
    public NexusAgentService NexusAgentService { get; }
    public NexusAgentLocalClient AgentLocalClient { get; }
    public NexusIdentityService IdentityService { get; }
    public NexusSetupFlowViewModel SetupFlowViewModel { get; }
    public NexusControlCenterService ControlCenterService { get; }
    public NexusAgentConfig AgentConfig { get; }
    public NexusBrowserService BrowserService { get; }
    public NexusCalculatorService CalculatorService { get; }
    public NexusStoreService StoreService { get; }
    public UpdateInfoViewModel UpdateInfoViewModel { get; }
    public NexusDefaultAppsService DefaultAppsService { get; }
    public NexusFileOpenService FileOpenService { get; }
    public bool CheckOnStartup { get; }
    public DiagnosticsService DiagnosticsService { get; }
    public PerformanceMonitorService PerformanceMonitor { get; }
    public WorkspaceWindowManager WorkspaceWindowManager { get; }
    public WorkspaceEventLog EventLog { get; }
    public DiagnosticSessionManager SessionManager { get; }
    public AppLaunchTracker AppLaunchTracker { get; }

    public async Task RefreshUpdateStatusAsync()
    {
        await UpdateService.CheckForUpdatesAsync();
        DesktopViewModel.NotifyUpdateStatus();
        SettingsViewModel.NotifyUpdateStatusChanged();
    }

    public async Task<UpdateApplyResult> TryAutoUpdateAsync(IProgress<string>? progress = null)
    {
        if (!UpdateService.AutoInstallEnabled)
        {
            return new UpdateApplyResult { Status = UpdateApplyStatus.Skipped };
        }

        var result = await UpdateService.TryAutoApplyUpdateAsync(progress);
        if (result.RestartScheduled)
        {
            if (Application.Current is Application app)
            {
                app.Shutdown();
            }
        }

        return result;
    }
}
