﻿using System;
using System.Runtime.InteropServices;
using UnityEngine;

namespace NeoriginPCSDK
{
    public class WinProcessHelper
    {
        
        // 窗口显示标志
        private const uint STARTF_USESHOWWINDOW = 0x00000001;

        // 窗口状态常量
        private const short SW_SHOWNORMAL = 1; // 正常大小并激活
        private const short SW_SHOWMAXIMIZED = 3; // 最大化
        private const short SW_SHOW = 5; // 显示当前的窗口状态
        
        [StructLayout(LayoutKind.Sequential)]
        public struct PROCESS_INFORMATION
        {
            public IntPtr hProcess;
            public IntPtr hThread;
            public uint dwProcessId;
            public uint dwThreadId;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct STARTUPINFO
        {
            public uint cb;
            public string lpReserved;
            public string lpDesktop;
            public string lpTitle;
            public uint dwX;
            public uint dwY;
            public uint dwXSize;
            public uint dwYSize;
            public uint dwFlags;
            public short wShowWindow;
            public short cbReserved2;
            public IntPtr lpReserved2;
            public IntPtr hStdInput;
            public IntPtr hStdOutput;
            public IntPtr hStdError;
        }

        // --- 2. 导入 CreateProcess API ---

        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern bool CreateProcess(
            string lpApplicationName,         // 模块名 (EXE 文件路径)
            string lpCommandLine,             // 命令行参数
            IntPtr lpProcessAttributes,       // 进程安全描述符
            IntPtr lpThreadAttributes,        // 线程安全描述符
            bool bInheritHandles,             // 是否继承句柄
            uint dwCreationFlags,             // 创建标志
            IntPtr lpEnvironment,             // 环境变量
            string lpCurrentDirectory,        // 进程的当前目录
            ref STARTUPINFO lpStartupInfo,    // 启动信息结构体
            out PROCESS_INFORMATION lpProcessInformation // 进程信息结构体
        );

        // --- 3. 导入关闭句柄 API (重要：避免资源泄露) ---
        
        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool CloseHandle(IntPtr hObject);
        
        // 查找窗口句柄（根据窗口类名或窗口标题）
        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        // 检查窗口是否最小化
        [DllImport("user32.dll")]
        private static extern bool IsIconic(IntPtr hWnd);

        // 恢复窗口到前台并设置显示状态
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        // 将窗口带到前台并激活
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        // 窗口状态常量
        private const int SW_RESTORE = 9; // 恢复窗口到前一个大小和位置
        
        public static bool ActivateExistingLauncherWindow()
        {
            // 关键：你必须知道 PcLancher.exe 窗口的准确标题或类名。
            // 由于通常启动器会有一个固定的标题，我们使用标题进行查找。
            // **请将 "PcLancher 主窗口标题" 替换为实际的窗口标题！**
            // 如果不知道，你可以使用工具如 Spy++ 或 WinSpy 来查看。
            string launcherWindowTitle = NeoriginLauncherInfoPath.LauncherName;

            IntPtr hWnd = FindWindow(null, launcherWindowTitle);
        
            if (hWnd == IntPtr.Zero)
            {
                // 窗口未找到，说明程序没有运行
                Debug.Log($"窗口 '{launcherWindowTitle}' 未找到。");
                return false;
            }

            // 窗口找到了，进行激活操作
            if (IsIconic(hWnd))
            {
                // 如果窗口是最小化的，先恢复它
                ShowWindow(hWnd, SW_RESTORE);
                Debug.Log("窗口已恢复。");
            }
            ShowWindow(hWnd, SW_SHOWNORMAL);
            // 将窗口带到前台并激活
            SetForegroundWindow(hWnd);
            Debug.Log("窗口已激活并置于前台。");
        
            return true;
        }

        // --- 4. 封装启动函数 ---

        /// <summary>
        /// 使用 Win32 CreateProcess API 启动外部程序并返回真正的错误码。
        /// </summary>
        /// <param name="exePath">外部程序的完整路径。</param>
        /// <param name="arguments">传递给外部程序的参数字符串。</param>
        /// <returns>成功则返回 true，失败则返回 false，真正的 Win32 错误码会打印到控制台。</returns>
        public static bool StartExternalAppWin32(string exePath, string arguments)
        {
            string workingDir = System.IO.Path.GetDirectoryName(exePath);

            // CreateProcess 接受的命令行参数，必须将 EXE 路径和参数放在一起
            // 确保 EXE 路径用双引号包裹，以防路径中包含空格
            string commandLine = $"\"{exePath}\" {arguments}";

            var startInfo = new STARTUPINFO();
            startInfo.cb = (uint)Marshal.SizeOf(startInfo);

            startInfo.dwFlags = STARTF_USESHOWWINDOW;
            startInfo.wShowWindow = SW_SHOWNORMAL; // 设置为正常大小显示
            PROCESS_INFORMATION procInfo = new PROCESS_INFORMATION();

            bool result = CreateProcess(
                null, // lpApplicationName 设为 null，让 lpCommandLine 包含完整路径
                commandLine,
                IntPtr.Zero,
                IntPtr.Zero,
                false, // 不继承句柄
                0, // dwCreationFlags (正常启动)
                IntPtr.Zero, // lpEnvironment (不传递特殊环境变量)
                workingDir, // lpCurrentDirectory (关键：设置工作目录)
                ref startInfo,
                out procInfo
            );

            if (!result)
            {
                // 🚨 获取真正的 Win32 错误码 🚨
                int errorCode = Marshal.GetLastWin32Error();

                // 打印错误码和对应的描述（虽然描述可能不总是准确，但错误码是关键）
                string errorDescription = new System.ComponentModel.Win32Exception(errorCode).Message;

                Debug.LogError($"[Win32 ERROR] CreateProcess failed.");
                Debug.LogError($"  Executable: {exePath}");
                Debug.LogError($"  CommandLine: {commandLine}");
                Debug.LogError($"  WorkingDir: {workingDir}");
                Debug.LogError($"  Win32 Error Code: {errorCode}");
                Debug.LogError($"  Error Description: {errorDescription}");
            }
            else
            {
                // 启动成功后，必须关闭返回的句柄以防止资源泄露
                CloseHandle(procInfo.hProcess);
                CloseHandle(procInfo.hThread);
                Debug.Log($"[Win32 SUCCESS] Process started successfully. PID: {procInfo.dwProcessId}");
            }

            return result;
        }
    }
}