using System.Collections.Concurrent;
using System.Timers;
using Timer = System.Timers.Timer;

namespace NavisworksTransport.Core.UIUpdate
{
    /// <summary>
    /// UI状态同步器
    /// 提供UI状态验证、同步和一致性检查功能
    /// </summary>
    public class UIStateSynchronizer : IDisposable
    {
        #region 嵌套类型定义

        /// <summary>
        /// UI状态快照
        /// </summary>
        public class UIStateSnapshot
        {
            /// <summary>
            /// 快照ID
            /// </summary>
            public string Id { get; set; } = Guid.NewGuid().ToString();

            /// <summary>
            /// 快照名称
            /// </summary>
            public string Name { get; set; }

            /// <summary>
            /// 创建时间
            /// </summary>
            public DateTime CreatedTime { get; set; } = DateTime.UtcNow;

            /// <summary>
            /// 状态数据
            /// </summary>
            public Dictionary<string, object> StateData { get; set; } = new Dictionary<string, object>();

            /// <summary>
            /// 快照元数据
            /// </summary>
            public Dictionary<string, object> Metadata { get; set; } = new Dictionary<string, object>();
        }

        /// <summary>
        /// UI状态验证结果
        /// </summary>
        public class UIStateValidationResult
        {
            /// <summary>
            /// 验证是否通过
            /// </summary>
            public bool IsValid { get; set; }

            /// <summary>
            /// 验证消息
            /// </summary>
            public string Message { get; set; }

            /// <summary>
            /// 验证错误详情
            /// </summary>
            public List<string> ValidationErrors { get; set; } = new List<string>();

            /// <summary>
            /// 不一致的状态项
            /// </summary>
            public Dictionary<string, object> InconsistentStates { get; set; } = new Dictionary<string, object>();

            /// <summary>
            /// 建议的修复操作
            /// </summary>
            public List<IUIUpdate> SuggestedFixes { get; set; } = new List<IUIUpdate>();
        }

        /// <summary>
        /// UI同步策略
        /// </summary>
        public enum UISyncStrategy
        {
            /// <summary>
            /// 立即同步
            /// </summary>
            Immediate,

            /// <summary>
            /// 延迟同步
            /// </summary>
            Delayed,

            /// <summary>
            /// 批量同步
            /// </summary>
            Batch,

            /// <summary>
            /// 手动同步
            /// </summary>
            Manual
        }

        /// <summary>
        /// UI状态同步配置
        /// </summary>
        public class UISyncConfiguration
        {
            /// <summary>
            /// 同步策略
            /// </summary>
            public UISyncStrategy Strategy { get; set; } = UISyncStrategy.Delayed;

            /// <summary>
            /// 同步间隔（毫秒）
            /// </summary>
            public int SyncIntervalMilliseconds { get; set; } = 1000;

            /// <summary>
            /// 是否启用自动验证
            /// </summary>
            public bool EnableAutoValidation { get; set; } = true;

            /// <summary>
            /// 验证间隔（毫秒）
            /// </summary>
            public int ValidationIntervalMilliseconds { get; set; } = 5000;

            /// <summary>
            /// 最大快照数量
            /// </summary>
            public int MaxSnapshotCount { get; set; } = 10;

            /// <summary>
            /// 是否启用状态恢复
            /// </summary>
            public bool EnableStateRecovery { get; set; } = true;

            /// <summary>
            /// 超时时间（毫秒）
            /// </summary>
            public int TimeoutMilliseconds { get; set; } = 10000;
        }

        #endregion

        #region 字段和属性

        private readonly IUIUpdateService _uiUpdateService;
        private readonly UISyncConfiguration _configuration;
        private readonly ConcurrentDictionary<string, object> _expectedStates;
        private readonly ConcurrentDictionary<string, object> _actualStates;
        private readonly ConcurrentQueue<UIStateSnapshot> _stateSnapshots;
        private readonly ConcurrentDictionary<string, Func<object, object, bool>> _stateValidators;
        private readonly ConcurrentDictionary<string, Func<object>> _stateReaders;
        private readonly Timer _syncTimer;
        private readonly Timer _validationTimer;
        private readonly object _syncLock = new object();
        private volatile bool _isDisposed = false;

        /// <summary>
        /// 同步配置
        /// </summary>
        public UISyncConfiguration Configuration => _configuration;

        /// <summary>
        /// 当前期望状态数量
        /// </summary>
        public int ExpectedStateCount => _expectedStates.Count;

        /// <summary>
        /// 当前实际状态数量
        /// </summary>
        public int ActualStateCount => _actualStates.Count;

        /// <summary>
        /// 状态快照数量
        /// </summary>
        public int SnapshotCount => _stateSnapshots.Count;

        /// <summary>
        /// 是否正在同步
        /// </summary>
        public bool IsSyncing { get; private set; }

        #endregion

        #region 事件

        /// <summary>
        /// 状态不一致事件
        /// </summary>
        public event EventHandler<UIStateInconsistencyEventArgs> StateInconsistencyDetected;

        /// <summary>
        /// 状态同步完成事件
        /// </summary>
        public event EventHandler<UIStateSyncCompletedEventArgs> StateSyncCompleted;

        /// <summary>
        /// 快照创建事件
        /// </summary>
        public event EventHandler<UIStateSnapshotCreatedEventArgs> SnapshotCreated;

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化UI状态同步器
        /// </summary>
        /// <param name="uiUpdateService">UI更新服务</param>
        /// <param name="configuration">同步配置</param>
        public UIStateSynchronizer(IUIUpdateService uiUpdateService, UISyncConfiguration configuration = null)
        {
            _uiUpdateService = uiUpdateService ?? throw new ArgumentNullException(nameof(uiUpdateService));
            _configuration = configuration ?? new UISyncConfiguration();

            _expectedStates = new ConcurrentDictionary<string, object>();
            _actualStates = new ConcurrentDictionary<string, object>();
            _stateSnapshots = new ConcurrentQueue<UIStateSnapshot>();
            _stateValidators = new ConcurrentDictionary<string, Func<object, object, bool>>();
            _stateReaders = new ConcurrentDictionary<string, Func<object>>();

            // 初始化定时器
            _syncTimer = new Timer(_configuration.SyncIntervalMilliseconds);
            _syncTimer.Elapsed += OnSyncTimerElapsed;
            _syncTimer.AutoReset = true;

            _validationTimer = new Timer(_configuration.ValidationIntervalMilliseconds);
            _validationTimer.Elapsed += OnValidationTimerElapsed;
            _validationTimer.AutoReset = true;

            LogManager.Info("[UIStateSynchronizer] UI状态同步器已创建");
        }

        #endregion

        #region 公共方法

        /// <summary>
        /// 启动状态同步器
        /// </summary>
        public void Start()
        {
            if (_isDisposed)
            {
                throw new ObjectDisposedException(nameof(UIStateSynchronizer));
            }

            lock (_syncLock)
            {
                if (_configuration.Strategy != UISyncStrategy.Manual)
                {
                    _syncTimer.Start();
                }

                if (_configuration.EnableAutoValidation)
                {
                    _validationTimer.Start();
                }
            }

            LogManager.Info("[UIStateSynchronizer] 状态同步器已启动");
        }

        /// <summary>
        /// 停止状态同步器
        /// </summary>
        public void Stop()
        {
            lock (_syncLock)
            {
                _syncTimer.Stop();
                _validationTimer.Stop();
                IsSyncing = false;
            }

            LogManager.Info("[UIStateSynchronizer] 状态同步器已停止");
        }

        /// <summary>
        /// 注册状态项
        /// </summary>
        /// <param name="key">状态键</param>
        /// <param name="expectedValue">期望值</param>
        /// <param name="stateReader">状态读取器</param>
        /// <param name="validator">状态验证器</param>
        public void RegisterState(string key, object expectedValue, Func<object> stateReader, Func<object, object, bool> validator = null)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (stateReader == null)
            {
                throw new ArgumentNullException(nameof(stateReader));
            }

            _expectedStates[key] = expectedValue;
            _stateReaders[key] = stateReader;

            if (validator != null)
            {
                _stateValidators[key] = validator;
            }
            else
            {
                // 默认验证器 - 简单相等比较
                _stateValidators[key] = (expected, actual) => Equals(expected, actual);
            }

            LogManager.Debug($"[UIStateSynchronizer] 注册状态项: {key}");
        }

        /// <summary>
        /// 取消注册状态项
        /// </summary>
        /// <param name="key">状态键</param>
        public void UnregisterState(string key)
        {
            _expectedStates.TryRemove(key, out _);
            _actualStates.TryRemove(key, out _);
            _stateValidators.TryRemove(key, out _);
            _stateReaders.TryRemove(key, out _);

            LogManager.Debug($"[UIStateSynchronizer] 取消注册状态项: {key}");
        }

        /// <summary>
        /// 更新期望状态
        /// </summary>
        /// <param name="key">状态键</param>
        /// <param name="expectedValue">新的期望值</param>
        public void UpdateExpectedState(string key, object expectedValue)
        {
            if (_expectedStates.ContainsKey(key))
            {
                _expectedStates[key] = expectedValue;
                LogManager.Debug($"[UIStateSynchronizer] 更新期望状态: {key} = {expectedValue}");

                // 根据策略决定是否立即同步
                if (_configuration.Strategy == UISyncStrategy.Immediate)
                {
                    _ = Task.Run(() => SyncStateAsync(key));
                }
            }
            else
            {
                LogManager.Warning($"[UIStateSynchronizer] 尝试更新未注册的状态项: {key}");
            }
        }

        /// <summary>
        /// 手动执行状态同步
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>同步结果</returns>
        public async Task<UIBatchUpdateResult> SyncAllStatesAsync(CancellationToken cancellationToken = default)
        {
            if (_isDisposed)
            {
                return new UIBatchUpdateResult
                {
                    IsSuccess = false,
                    Message = "同步器已被释放"
                };
            }

            try
            {
                IsSyncing = true;
                LogManager.Info("[UIStateSynchronizer] 开始手动同步所有状态");

                var updateOperations = new List<IUIUpdate>();
                var inconsistentStates = new List<string>();

                // 读取当前实际状态
                await ReadAllActualStatesAsync();

                // 比较期望状态和实际状态
                foreach (var expectedState in _expectedStates)
                {
                    var key = expectedState.Key;
                    var expectedValue = expectedState.Value;

                    if (_actualStates.TryGetValue(key, out var actualValue))
                    {
                        if (_stateValidators.TryGetValue(key, out var validator))
                        {
                            if (!validator(expectedValue, actualValue))
                            {
                                inconsistentStates.Add(key);
                                
                                // 创建同步操作
                                var syncOperation = CreateSyncOperation(key, expectedValue);
                                if (syncOperation != null)
                                {
                                    updateOperations.Add(syncOperation);
                                }
                            }
                        }
                    }
                }

                // 执行同步操作
                UIBatchUpdateResult result;
                if (updateOperations.Count > 0)
                {
                    result = await _uiUpdateService.ExecuteBatchUpdateAsync(updateOperations, null, cancellationToken);
                    
                    LogManager.Info($"[UIStateSynchronizer] 同步完成，处理了{inconsistentStates.Count}个不一致状态");
                }
                else
                {
                    result = new UIBatchUpdateResult
                    {
                        IsSuccess = true,
                        TotalCount = 0,
                        SuccessCount = 0,
                        FailureCount = 0,
                        Message = "所有状态都已同步"
                    };
                    
                    LogManager.Info("[UIStateSynchronizer] 所有状态都已同步，无需更新");
                }

                // 触发同步完成事件
                OnStateSyncCompleted(new UIStateSyncCompletedEventArgs(result, inconsistentStates));

                return result;
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIStateSynchronizer] 状态同步过程中发生异常", ex);
                return new UIBatchUpdateResult
                {
                    IsSuccess = false,
                    Message = $"同步失败: {ex.Message}",
                    AggregateException = new AggregateException(ex)
                };
            }
            finally
            {
                IsSyncing = false;
            }
        }

        /// <summary>
        /// 同步单个状态
        /// </summary>
        /// <param name="key">状态键</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>同步结果</returns>
        public async Task<UIUpdateResult> SyncStateAsync(string key, CancellationToken cancellationToken = default)
        {
            if (!_expectedStates.TryGetValue(key, out var expectedValue))
            {
                return UIUpdateResult.Failure($"未找到状态项: {key}");
            }

            try
            {
                // 读取实际状态
                if (_stateReaders.TryGetValue(key, out var stateReader))
                {
                    var actualValue = stateReader();
                    _actualStates[key] = actualValue;

                    // 验证状态
                    if (_stateValidators.TryGetValue(key, out var validator))
                    {
                        if (!validator(expectedValue, actualValue))
                        {
                            // 创建并执行同步操作
                            var syncOperation = CreateSyncOperation(key, expectedValue);
                            if (syncOperation != null)
                            {
                                var result = await _uiUpdateService.ExecuteUpdateAsync(syncOperation, null, cancellationToken);
                                
                                if (result.IsSuccess)
                                {
                                    LogManager.Debug($"[UIStateSynchronizer] 成功同步状态: {key}");
                                }
                                
                                return result;
                            }
                        }
                        else
                        {
                            return UIUpdateResult.Success($"状态{key}已同步");
                        }
                    }
                }

                return UIUpdateResult.Failure($"无法同步状态{key}：缺少读取器或验证器");
            }
            catch (Exception ex)
            {
                LogManager.Error($"[UIStateSynchronizer] 同步状态{key}时发生异常", ex);
                return UIUpdateResult.Failure($"同步状态{key}失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 验证所有状态
        /// </summary>
        /// <returns>验证结果</returns>
        public async Task<UIStateValidationResult> ValidateAllStatesAsync()
        {
            var result = new UIStateValidationResult();

            try
            {
                LogManager.Debug("[UIStateSynchronizer] 开始验证所有状态");

                // 读取当前实际状态
                await ReadAllActualStatesAsync();

                var inconsistentCount = 0;
                
                foreach (var expectedState in _expectedStates)
                {
                    var key = expectedState.Key;
                    var expectedValue = expectedState.Value;

                    if (_actualStates.TryGetValue(key, out var actualValue))
                    {
                        if (_stateValidators.TryGetValue(key, out var validator))
                        {
                            if (!validator(expectedValue, actualValue))
                            {
                                inconsistentCount++;
                                result.ValidationErrors.Add($"状态不一致: {key}, 期望: {expectedValue}, 实际: {actualValue}");
                                result.InconsistentStates[key] = actualValue;

                                // 创建建议的修复操作
                                var fixOperation = CreateSyncOperation(key, expectedValue);
                                if (fixOperation != null)
                                {
                                    result.SuggestedFixes.Add(fixOperation);
                                }
                            }
                        }
                        else
                        {
                            result.ValidationErrors.Add($"状态验证器缺失: {key}");
                        }
                    }
                    else
                    {
                        result.ValidationErrors.Add($"无法读取实际状态: {key}");
                    }
                }

                result.IsValid = inconsistentCount == 0;
                result.Message = result.IsValid 
                    ? "所有状态都是一致的" 
                    : $"发现{inconsistentCount}个不一致的状态";

                if (!result.IsValid)
                {
                    LogManager.Warning($"[UIStateSynchronizer] 状态验证失败: {result.Message}");
                    
                    // 触发状态不一致事件
                    OnStateInconsistencyDetected(new UIStateInconsistencyEventArgs(result.InconsistentStates, result.SuggestedFixes));
                }
                else
                {
                    LogManager.Debug("[UIStateSynchronizer] 所有状态验证通过");
                }

                return result;
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIStateSynchronizer] 状态验证过程中发生异常", ex);
                result.IsValid = false;
                result.Message = $"验证失败: {ex.Message}";
                result.ValidationErrors.Add($"验证异常: {ex.Message}");
                return result;
            }
        }

        /// <summary>
        /// 创建状态快照
        /// </summary>
        /// <param name="name">快照名称</param>
        /// <param name="metadata">快照元数据</param>
        /// <returns>状态快照</returns>
        public async Task<UIStateSnapshot> CreateSnapshotAsync(string name, Dictionary<string, object> metadata = null)
        {
            try
            {
                LogManager.Info($"[UIStateSynchronizer] 创建状态快照: {name}");

                // 读取当前实际状态
                await ReadAllActualStatesAsync();

                var snapshot = new UIStateSnapshot
                {
                    Name = name,
                    StateData = new Dictionary<string, object>(_actualStates),
                    Metadata = metadata ?? new Dictionary<string, object>()
                };

                // 添加到快照队列
                _stateSnapshots.Enqueue(snapshot);

                // 限制快照数量
                while (_stateSnapshots.Count > _configuration.MaxSnapshotCount)
                {
                    _stateSnapshots.TryDequeue(out _);
                }

                // 触发快照创建事件
                OnSnapshotCreated(new UIStateSnapshotCreatedEventArgs(snapshot));

                LogManager.Info($"[UIStateSynchronizer] 成功创建状态快照: {name} ({snapshot.Id})");
                return snapshot;
            }
            catch (Exception ex)
            {
                LogManager.Error($"[UIStateSynchronizer] 创建状态快照{name}时发生异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 恢复到指定快照
        /// </summary>
        /// <param name="snapshotId">快照ID</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>恢复结果</returns>
        public async Task<UIBatchUpdateResult> RestoreFromSnapshotAsync(string snapshotId, CancellationToken cancellationToken = default)
        {
            if (!_configuration.EnableStateRecovery)
            {
                return new UIBatchUpdateResult
                {
                    IsSuccess = false,
                    Message = "状态恢复功能未启用"
                };
            }

            try
            {
                LogManager.Info($"[UIStateSynchronizer] 开始从快照恢复: {snapshotId}");

                // 查找快照
                var snapshot = _stateSnapshots.FirstOrDefault(s => s.Id == snapshotId);
                if (snapshot == null)
                {
                    return new UIBatchUpdateResult
                    {
                        IsSuccess = false,
                        Message = $"未找到快照: {snapshotId}"
                    };
                }

                // 更新期望状态为快照状态
                foreach (var stateItem in snapshot.StateData)
                {
                    _expectedStates[stateItem.Key] = stateItem.Value;
                }

                // 执行同步
                var result = await SyncAllStatesAsync(cancellationToken);
                
                if (result.IsSuccess)
                {
                    LogManager.Info($"[UIStateSynchronizer] 成功从快照{snapshotId}恢复状态");
                }
                else
                {
                    LogManager.Error($"[UIStateSynchronizer] 从快照{snapshotId}恢复状态失败: {result.Message}");
                }

                return result;
            }
            catch (Exception ex)
            {
                LogManager.Error($"[UIStateSynchronizer] 从快照{snapshotId}恢复状态时发生异常", ex);
                return new UIBatchUpdateResult
                {
                    IsSuccess = false,
                    Message = $"恢复失败: {ex.Message}",
                    AggregateException = new AggregateException(ex)
                };
            }
        }

        /// <summary>
        /// 获取所有快照
        /// </summary>
        /// <returns>快照列表</returns>
        public List<UIStateSnapshot> GetSnapshots()
        {
            return _stateSnapshots.ToList();
        }

        /// <summary>
        /// 清除所有快照
        /// </summary>
        public void ClearSnapshots()
        {
            while (_stateSnapshots.TryDequeue(out _)) { }
            LogManager.Info("[UIStateSynchronizer] 已清除所有状态快照");
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 读取所有实际状态
        /// </summary>
        private async Task ReadAllActualStatesAsync()
        {
            var tasks = _stateReaders.Select(async kvp =>
            {
                try
                {
                    var key = kvp.Key;
                    var reader = kvp.Value;
                    
                    // 在UI线程上读取状态
                    var value = await _uiUpdateService.UIStateManager.ExecuteUIUpdateAsync(reader);
                    _actualStates[key] = value;
                }
                catch (Exception ex)
                {
                    LogManager.Error($"[UIStateSynchronizer] 读取状态{kvp.Key}时发生异常", ex);
                }
            });

            await Task.WhenAll(tasks);
        }

        /// <summary>
        /// 创建同步操作
        /// </summary>
        /// <param name="key">状态键</param>
        /// <param name="expectedValue">期望值</param>
        /// <returns>同步操作</returns>
        private IUIUpdate CreateSyncOperation(string key, object expectedValue)
        {
            try
            {
                // 这里可以根据状态键的命名约定来确定同步操作类型
                // 例如：ControlName.PropertyName 格式
                
                var parts = key.Split('.');
                if (parts.Length == 2)
                {
                    var controlName = parts[0];
                    var propertyName = parts[1];
                    
                    // 假设我们有一个控件注册表
                    // 这里简化为创建属性更新操作
                    return UIUpdateFactory.UpdateProperty(new { Name = controlName }, propertyName, expectedValue);
                }
                else
                {
                    // 创建自定义操作
                    return UIUpdateFactory.WrapAction($"SyncState_{key}", () =>
                    {
                        // 这里需要根据具体的状态键实现相应的同步逻辑
                        LogManager.Debug($"[UIStateSynchronizer] 执行状态同步: {key} = {expectedValue}");
                    });
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[UIStateSynchronizer] 创建同步操作失败: {key}", ex);
                return null;
            }
        }

        /// <summary>
        /// 同步定时器事件
        /// </summary>
        private void OnSyncTimerElapsed(object sender, ElapsedEventArgs e)
        {
            if (_isDisposed || IsSyncing)
            {
                return;
            }

            _ = Task.Run(async () =>
            {
                try
                {
                    await SyncAllStatesAsync();
                }
                catch (Exception ex)
                {
                    LogManager.Error("[UIStateSynchronizer] 定时同步过程中发生异常", ex);
                }
            });
        }

        /// <summary>
        /// 验证定时器事件
        /// </summary>
        private void OnValidationTimerElapsed(object sender, ElapsedEventArgs e)
        {
            if (_isDisposed)
            {
                return;
            }

            _ = Task.Run(async () =>
            {
                try
                {
                    await ValidateAllStatesAsync();
                }
                catch (Exception ex)
                {
                    LogManager.Error("[UIStateSynchronizer] 定时验证过程中发生异常", ex);
                }
            });
        }

        #endregion

        #region 事件触发方法

        /// <summary>
        /// 触发状态不一致事件
        /// </summary>
        protected virtual void OnStateInconsistencyDetected(UIStateInconsistencyEventArgs args)
        {
            try
            {
                StateInconsistencyDetected?.Invoke(this, args);
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIStateSynchronizer] 触发状态不一致事件时发生异常", ex);
            }
        }

        /// <summary>
        /// 触发状态同步完成事件
        /// </summary>
        protected virtual void OnStateSyncCompleted(UIStateSyncCompletedEventArgs args)
        {
            try
            {
                StateSyncCompleted?.Invoke(this, args);
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIStateSynchronizer] 触发状态同步完成事件时发生异常", ex);
            }
        }

        /// <summary>
        /// 触发快照创建事件
        /// </summary>
        protected virtual void OnSnapshotCreated(UIStateSnapshotCreatedEventArgs args)
        {
            try
            {
                SnapshotCreated?.Invoke(this, args);
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIStateSynchronizer] 触发快照创建事件时发生异常", ex);
            }
        }

        #endregion

        #region IDisposable实现

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            if (_isDisposed)
            {
                return;
            }

            try
            {
                LogManager.Info("[UIStateSynchronizer] 开始释放UI状态同步器");

                // 停止定时器
                Stop();

                // 释放定时器
                _syncTimer?.Dispose();
                _validationTimer?.Dispose();

                // 清理数据
                _expectedStates.Clear();
                _actualStates.Clear();
                _stateValidators.Clear();
                _stateReaders.Clear();
                ClearSnapshots();

                _isDisposed = true;
                LogManager.Info("[UIStateSynchronizer] UI状态同步器已释放");
            }
            catch (Exception ex)
            {
                LogManager.Error("[UIStateSynchronizer] 释放UI状态同步器时发生异常", ex);
            }
        }

        #endregion
    }

    #region 事件参数类

    /// <summary>
    /// UI状态不一致事件参数
    /// </summary>
    public class UIStateInconsistencyEventArgs : EventArgs
    {
        public Dictionary<string, object> InconsistentStates { get; }
        public List<IUIUpdate> SuggestedFixes { get; }
        public DateTime DetectedTime { get; }

        public UIStateInconsistencyEventArgs(Dictionary<string, object> inconsistentStates, List<IUIUpdate> suggestedFixes)
        {
            InconsistentStates = inconsistentStates ?? new Dictionary<string, object>();
            SuggestedFixes = suggestedFixes ?? new List<IUIUpdate>();
            DetectedTime = DateTime.UtcNow;
        }
    }

    /// <summary>
    /// UI状态同步完成事件参数
    /// </summary>
    public class UIStateSyncCompletedEventArgs : EventArgs
    {
        public UIBatchUpdateResult SyncResult { get; }
        public List<string> SyncedStates { get; }
        public DateTime CompletedTime { get; }

        public UIStateSyncCompletedEventArgs(UIBatchUpdateResult syncResult, List<string> syncedStates)
        {
            SyncResult = syncResult;
            SyncedStates = syncedStates ?? new List<string>();
            CompletedTime = DateTime.UtcNow;
        }
    }

    /// <summary>
    /// UI状态快照创建事件参数
    /// </summary>
    public class UIStateSnapshotCreatedEventArgs : EventArgs
    {
        public UIStateSynchronizer.UIStateSnapshot Snapshot { get; }
        public DateTime CreatedTime { get; }

        public UIStateSnapshotCreatedEventArgs(UIStateSynchronizer.UIStateSnapshot snapshot)
        {
            Snapshot = snapshot;
            CreatedTime = DateTime.UtcNow;
        }
    }

    #endregion
}