using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;

namespace NavisworksTransport.Utils
{
    /// <summary>
    /// 版本信息管理工具类 - 提供统一的版本信息获取
    /// </summary>
    public static class VersionInfo
    {
        private static readonly DateTime _startupTime = DateTime.Now;
        private static readonly string _buildTimestamp;
        private static readonly string _fullVersion;
        private static readonly string _shortVersion;

        /// <summary>
        /// 静态构造函数 - 初始化版本信息
        /// </summary>
        static VersionInfo()
        {
            try
            {
                var assembly = Assembly.GetExecutingAssembly();
                var version = assembly.GetName().Version;
                
                // 短版本号: 2.0.0 (使用 AssemblyVersion 的主.次.构建)
                _shortVersion = $"{version.Major}.{version.Minor}.{version.Build}";
                
                // 获取程序集文件的构建时间 (从文件修改时间)
                DateTime buildDate = GetBuildDate(assembly);
                _buildTimestamp = buildDate.ToString("yyyy_MM_dd_HHmmss");
                
                // 完整版本: 2.0.0 Build-2025-03-09-113300
                _fullVersion = $"{_shortVersion} Build_{_buildTimestamp}";
            }
            catch (Exception ex)
            {
                LogManager.Error($"初始化版本信息失败: {ex.Message}");
                _shortVersion = "0.0.0";
                _buildTimestamp = DateTime.Now.ToString("yyyy-MM-dd-HHmmss");
                _fullVersion = $"{_shortVersion} Build_{_buildTimestamp}";
            }
        }

        /// <summary>
        /// 从程序集文件获取构建日期
        /// </summary>
        private static DateTime GetBuildDate(Assembly assembly)
        {
            try
            {
                // 方法1: 从程序集文件的最后修改时间获取
                var assemblyLocation = assembly.Location;
                if (!string.IsNullOrEmpty(assemblyLocation) && File.Exists(assemblyLocation))
                {
                    var fileInfo = new FileInfo(assemblyLocation);
                    return fileInfo.LastWriteTime;
                }
            }
            catch (Exception ex)
            {
                LogManager.Debug($"从文件获取构建日期失败: {ex.Message}");
            }

            // 回退: 使用当前时间（开发模式）
            return DateTime.Now;
        }

        /// <summary>
        /// 获取插件短版本号 (例如: 2.0.0)
        /// </summary>
        public static string ShortVersion => _shortVersion;

        /// <summary>
        /// 获取完整版本号 (包含构建时间戳)
        /// 格式: 2.0.0 Build-20250309-113300
        /// </summary>
        public static string FullVersion => _fullVersion;

        /// <summary>
        /// 获取构建时间戳
        /// 格式: 20250309-113300
        /// </summary>
        public static string BuildTimestamp => _buildTimestamp;

        /// <summary>
        /// 获取 Navisworks 版本信息
        /// </summary>
        public static string GetNavisworksVersion()
        {
            try
            {
                var version = Autodesk.Navisworks.Api.Application.Version;
                if (version != null)
                {
                    // 计算年份：主版本号 + 2003
                    // 23 + 2003 = 2026, 22 + 2003 = 2025
                    int year = version.RuntimeMajor + 2003;
                    
                    return $"{version.Runtime} {year} ({version.RuntimeLanguage})";
                }
                return "未运行";
            }
            catch (Exception ex)
            {
                LogManager.Error($"获取Navisworks版本失败: {ex.Message}");
                return "未知版本";
            }
        }

        /// <summary>
        /// 获取当前内存使用情况
        /// </summary>
        public static string GetMemoryUsage()
        {
            try
            {
                long memoryBytes = GC.GetTotalMemory(false);
                Process process = Process.GetCurrentProcess();
                long workingSetMB = process.WorkingSet64 / 1024 / 1024;
                return $"{workingSetMB} MB";
            }
            catch (Exception ex)
            {
                LogManager.Error($"获取内存使用失败: {ex.Message}");
                return "--";
            }
        }

        /// <summary>
        /// 获取插件运行时间
        /// </summary>
        public static string GetRunningTime()
        {
            try
            {
                TimeSpan elapsed = DateTime.Now - _startupTime;
                if (elapsed.TotalDays >= 1)
                {
                    return $"{elapsed.Days}天 {elapsed.Hours:D2}:{elapsed.Minutes:D2}:{elapsed.Seconds:D2}";
                }
                return $"{elapsed.Hours:D2}:{elapsed.Minutes:D2}:{elapsed.Seconds:D2}";
            }
            catch (Exception ex)
            {
                LogManager.Error($"获取运行时间失败: {ex.Message}");
                return "--";
            }
        }

        /// <summary>
        /// 获取系统信息汇总
        /// </summary>
        public static SystemInfo GetSystemInfo()
        {
            return new SystemInfo
            {
                PluginVersion = FullVersion,
                NavisworksVersion = GetNavisworksVersion(),
                MemoryUsage = GetMemoryUsage(),
                RunningTime = GetRunningTime(),
                BuildTimestamp = BuildTimestamp
            };
        }
    }

    /// <summary>
    /// 系统信息数据类
    /// </summary>
    public class SystemInfo
    {
        /// <summary>
        /// 插件版本
        /// </summary>
        public string PluginVersion { get; set; }

        /// <summary>
        /// Navisworks版本
        /// </summary>
        public string NavisworksVersion { get; set; }

        /// <summary>
        /// 内存使用
        /// </summary>
        public string MemoryUsage { get; set; }

        /// <summary>
        /// 运行时间
        /// </summary>
        public string RunningTime { get; set; }

        /// <summary>
        /// 构建时间戳
        /// </summary>
        public string BuildTimestamp { get; set; }
    }
}
