using System;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Windows;
using XplorePlane.Views;
using XplorePlane.ViewModels;
using XplorePlane.Services;
using Prism.Ioc;
using Prism.DryIoc;
using Prism.Modularity;
using Serilog;
using XP.Common.Module;
using XP.Hardware.RaySource.Module;
using XP.Hardware.RaySource.Services;

namespace XplorePlane
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            // 强制使用中文 UI，确保 ImageProcessing 库显示中文
            var zhCN = new CultureInfo("zh-CN");
            Thread.CurrentThread.CurrentCulture   = zhCN;
            Thread.CurrentThread.CurrentUICulture = zhCN;
            CultureInfo.DefaultThreadCurrentCulture   = zhCN;
            CultureInfo.DefaultThreadCurrentUICulture = zhCN;

            // 配置 Serilog 日志系统
            ConfigureLogging();

            // 捕获未处理的异常
            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
            DispatcherUnhandledException += OnDispatcherUnhandledException;

            try
            {
                base.OnStartup(e);

                // Initialize Prism with DryIoc
                var bootstrapper = new AppBootstrapper();
                bootstrapper.Run();
            }
            catch (FileNotFoundException ex)
            {
                Log.Fatal(ex, "Required DLL not found: {FileName}", ex.FileName);
                MessageBox.Show(
                    $"Required library not found: {ex.FileName}\n\nPlease ensure all required DLLs are present in the Libs/ImageProcessing/ directory.",
                    "Missing Library",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
                Shutdown(1);
            }
            catch (TypeLoadException ex)
            {
                Log.Fatal(ex, "Failed to load type from DLL: {TypeName}", ex.TypeName);
                MessageBox.Show(
                    $"Failed to load required type: {ex.TypeName}\n\nPlease ensure the correct version of DLLs are present in the Libs/ImageProcessing/ directory.",
                    "Library Load Error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
                Shutdown(1);
            }
        }

        private void ConfigureLogging()
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.Console()
                .WriteTo.File("logs/xploreplane-.log", 
                    rollingInterval: RollingInterval.Day,
                    retainedFileCountLimit: 30)
                .CreateLogger();
                
            Log.Information("========================================");
            Log.Information("XplorePlane 应用程序启动");
            Log.Information("========================================");
        }

        protected override void OnExit(ExitEventArgs e)
        {
            Log.Information("========================================");
            Log.Information("XplorePlane 应用程序退出");
            Log.Information("========================================");

            // 释放射线源资源
            try
            {
                var bootstrapper = AppBootstrapper.Instance;
                if (bootstrapper != null)
                {
                    var raySourceService = bootstrapper.Container.Resolve<IRaySourceService>();
                    raySourceService?.Dispose();
                    Log.Information("射线源资源已释放");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "射线源资源释放失败");
            }

            Log.CloseAndFlush();
            base.OnExit(e);
        }

        /// <summary>
        /// 处理未捕获的异常
        /// </summary>
        private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var exception = e.ExceptionObject as Exception;
            Log.Fatal(exception, "应用程序发生未处理的异常");

            MessageBox.Show(
                $"应用程序发生严重错误：\n\n{exception?.Message}\n\n请查看日志文件获取详细信息。",
                "严重错误",
                MessageBoxButton.OK,
                MessageBoxImage.Error);
        }

        /// <summary>
        /// 处理 UI 线程未捕获的异常
        /// </summary>
        private void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            Log.Error(e.Exception, "UI 线程发生未处理的异常");

            MessageBox.Show(
                $"应用程序发生错误：\n\n{e.Exception.Message}\n\n请查看日志文件获取详细信息。",
                "错误",
                MessageBoxButton.OK,
                MessageBoxImage.Error);

            // 标记为已处理，防止应用程序崩溃
            e.Handled = true;
        }
    }

    public class AppBootstrapper : PrismBootstrapper
    {
        public static AppBootstrapper Instance { get; private set; }

        public new IContainerProvider Container => base.Container;

        public AppBootstrapper()
        {
            Instance = this;
        }

        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            // 注册 Serilog 的 ILogger 实例
            containerRegistry.RegisterInstance<ILogger>(Log.Logger);

            // 注册 XP.Common.ILoggerService 适配器
            containerRegistry.RegisterSingleton<XP.Common.Logging.Interfaces.ILoggerService, Services.LoggerServiceAdapter>();

            // 注册视图和视图模型
            containerRegistry.RegisterForNavigation<MainWindow>();
            containerRegistry.RegisterForNavigation<MainWindowB>();
            containerRegistry.Register<MainViewModel>();

            // 注册图像处理服务与视图
            containerRegistry.RegisterSingleton<IImageProcessingService, ImageProcessingService>();
            containerRegistry.Register<ImageProcessingViewModel>();
            containerRegistry.RegisterForNavigation<ImageProcessingPanelView>();

            // 注册流水线服务（单例，共享 IImageProcessingService）
            containerRegistry.RegisterSingleton<IPipelineExecutionService, PipelineExecutionService>();
            containerRegistry.RegisterSingleton<IPipelinePersistenceService, PipelinePersistenceService>();

            // 注册流水线 ViewModel（每次解析创建新实例）
            containerRegistry.Register<PipelineEditorViewModel>();
            containerRegistry.Register<OperatorToolboxViewModel>();

            Log.Information("依赖注入容器配置完成");
        }

        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        {
            // 通用模块（注册 ILocalizationService、ILocalizationConfig）— 必须在 RaySourceModule 之前
            moduleCatalog.AddModule<CommonModule>();

            // 射线源模块（自动注册 IRaySourceService、IRaySourceFactory、RaySourceConfig）
            moduleCatalog.AddModule<RaySourceModule>();

            base.ConfigureModuleCatalog(moduleCatalog);
        }
    }
}
