﻿using System;
using System.Runtime.InteropServices;
using System.Text;
using AOT;
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);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool SetWindowPos(
            IntPtr hWnd,
            IntPtr hWndInsertAfter,
            int X,
            int Y,
            int cx,
            int cy,
            uint uFlags);

        [DllImport("user32.dll")]
        private static extern IntPtr SetWinEventHook(
            uint eventMin,
            uint eventMax,
            IntPtr hmodWinEventProc,
            WinEventDelegate lpfnWinEventProc,
            uint idProcess,
            uint idThread,
            uint dwFlags);

        [DllImport("user32.dll")]
        private static extern bool UnhookWinEvent(IntPtr hWinEventHook);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

        [DllImport("user32.dll")]
        private static extern bool IsWindowVisible(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

        [DllImport("kernel32.dll")]
        private static extern uint GetCurrentProcessId();

        // 窗口状态常量
        private const int SW_RESTORE = 9; // 恢复窗口到前一个大小和位置
        private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        private static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
        private const uint SWP_NOSIZE = 0x0001;
        private const uint SWP_NOMOVE = 0x0002;
        private const uint SWP_SHOWWINDOW = 0x0040;
        private const uint EVENT_SYSTEM_DIALOGSTART = 0x0010;
        private const uint EVENT_OBJECT_CREATE = 0x8000;
        private const uint EVENT_OBJECT_SHOW = 0x8002;
        private const int OBJID_WINDOW = 0;
        private const uint WINEVENT_OUTOFCONTEXT = 0;

        private delegate void WinEventDelegate(
            IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);

        private static IntPtr _dialogAssistHookDialogStart = IntPtr.Zero;
        private static IntPtr _dialogAssistHookObjectCreate = IntPtr.Zero;
        private static IntPtr _dialogAssistHookObjectShow = IntPtr.Zero;
        private static WinEventDelegate _dialogAssistCallback;
        private static long _lastDialogBringUpTicks = 0;
        
        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. 封装启动函数 ---

        public static void StartDialogForegroundAssist()
        {
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
            Debug.Log($"[Win32 SUCCESS] StartDialogForegroundAssist hooks: {_dialogAssistHookDialogStart}/{_dialogAssistHookObjectCreate}/{_dialogAssistHookObjectShow}");
            if (_dialogAssistHookDialogStart != IntPtr.Zero ||
                _dialogAssistHookObjectCreate != IntPtr.Zero ||
                _dialogAssistHookObjectShow != IntPtr.Zero)
            {
                return;
            }
            Debug.Log($"[Win32 SUCCESS] StartDialogForegroundAssist SetWinEventHook!");
            _dialogAssistCallback = OnDialogWindowCreated;
            _dialogAssistHookDialogStart = SetWinEventHook(
                EVENT_SYSTEM_DIALOGSTART,
                EVENT_SYSTEM_DIALOGSTART,
                IntPtr.Zero,
                _dialogAssistCallback,
                0,
                0,
                WINEVENT_OUTOFCONTEXT);

            _dialogAssistHookObjectCreate = SetWinEventHook(
                EVENT_OBJECT_CREATE,
                EVENT_OBJECT_CREATE,
                IntPtr.Zero,
                _dialogAssistCallback,
                0,
                0,
                WINEVENT_OUTOFCONTEXT);

            _dialogAssistHookObjectShow = SetWinEventHook(
                EVENT_OBJECT_SHOW,
                EVENT_OBJECT_SHOW,
                IntPtr.Zero,
                _dialogAssistCallback,
                0,
                0,
                WINEVENT_OUTOFCONTEXT);
#endif
        }

        public static void StopDialogForegroundAssist()
        {
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
            Debug.Log($"[Win32 SUCCESS] StopDialogForegroundAssist hooks: {_dialogAssistHookDialogStart}/{_dialogAssistHookObjectCreate}/{_dialogAssistHookObjectShow}");
            if (_dialogAssistHookDialogStart == IntPtr.Zero &&
                _dialogAssistHookObjectCreate == IntPtr.Zero &&
                _dialogAssistHookObjectShow == IntPtr.Zero)
            {
                return;
            }

            if (_dialogAssistHookDialogStart != IntPtr.Zero)
            {
                UnhookWinEvent(_dialogAssistHookDialogStart);
                _dialogAssistHookDialogStart = IntPtr.Zero;
            }
            if (_dialogAssistHookObjectCreate != IntPtr.Zero)
            {
                UnhookWinEvent(_dialogAssistHookObjectCreate);
                _dialogAssistHookObjectCreate = IntPtr.Zero;
            }
            if (_dialogAssistHookObjectShow != IntPtr.Zero)
            {
                UnhookWinEvent(_dialogAssistHookObjectShow);
                _dialogAssistHookObjectShow = IntPtr.Zero;
            }
            _dialogAssistCallback = null;
#endif
        }

        [MonoPInvokeCallback(typeof(WinEventDelegate))]
        private static void OnDialogWindowCreated(
            IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
        {
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
            Debug.Log($"[Win32 SUCCESS] OnDialogWindowCreated. eventType: {eventType}, hwnd: {hwnd}, idObject: {idObject}");
            if (hwnd == IntPtr.Zero || !IsWindowVisible(hwnd))
            {
                return;
            }

            // 仅处理窗口对象，过滤子控件事件，减少噪音和误触发。
            if (idObject != OBJID_WINDOW)
            {
                return;
            }

            var className = new StringBuilder(64);
            GetClassName(hwnd, className, className.Capacity);
            if (className.ToString() != "#32770")
            {
                return;
            }

            long nowTicks = DateTime.UtcNow.Ticks;
            long debounceTicks = TimeSpan.FromMilliseconds(500).Ticks;
            if (nowTicks - _lastDialogBringUpTicks < debounceTicks)
            {
                return;
            }
            Debug.Log($"[Win32 SUCCESS] OnDialogWindowCreated. SetForegroundWindow: {hwnd}");
            _lastDialogBringUpTicks = nowTicks;

            ShowWindow(hwnd, SW_SHOWNORMAL);
            SetForegroundWindow(hwnd);
            SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
            SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
#endif
        }

        /// <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;
        }
    }
}
