// system/ProcessHandler.h
#pragma once

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif

#include "core/Types.h"
#include <windows.h>
#include <tlhelp32.h>
#include <string>
#include <memory>
#include <vector>
#include <iostream>

template<typename F>
struct scope_exit
{
    F f;
    explicit scope_exit(F&& func) : f(std::forward<F>(func)) {}
    ~scope_exit() { f(); }
};

namespace ProcessHandler
{
    // RAII Handles
    struct HandleCloser 
    { 
        void operator()(HANDLE h) const noexcept
        {
            if (h && h != INVALID_HANDLE_VALUE)
                CloseHandle(h);
        }
    };
    using UniqueHandle = std::unique_ptr<void, HandleCloser>;

	// Process detail structures
    namespace detail
    {
        inline std::wstring GetCommandLineFromPid(DWORD pid)
        {
            std::wstring result;
            HANDLE hProc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ, FALSE, pid);
            if (!hProc) return result;
            auto closeProc = scope_exit([&] { CloseHandle(hProc); });

            HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
            if (!ntdll) return result;

            // 修复：使用我们自己定义的类型
            NtQueryInformationProcess_t NtQuery =
                (NtQueryInformationProcess_t)GetProcAddress(ntdll, "NtQueryInformationProcess");
            if (!NtQuery) return result;

            PROCESS_BASIC_INFORMATION pbi{};
            if (NtQuery(hProc, ProcessBasicInformation, &pbi, sizeof(pbi), nullptr) != 0)
                return result;

            PEB peb{};
            if (!ReadProcessMemory(hProc, pbi.PebBaseAddress, &peb, sizeof(peb), nullptr))
                return result;

            RTL_USER_PROCESS_PARAMETERS upp{};
            if (!ReadProcessMemory(hProc, peb.ProcessParameters, &upp, sizeof(upp), nullptr))
                return result;

            if (upp.CommandLine.Length == 0 || !upp.CommandLine.Buffer)
                return result;

            std::unique_ptr<wchar_t[]> buffer(new wchar_t[upp.CommandLine.Length / 2 + 1]);
            if (!ReadProcessMemory(hProc, upp.CommandLine.Buffer, buffer.get(), upp.CommandLine.Length, nullptr))
                return result;

            result.assign(buffer.get(), upp.CommandLine.Length / 2);
            return result;
        }
    }

    /// @brief Find all pids with given process name and return them in a list.
    inline std::vector<DWORD> FindProcessesByName(const std::wstring& exeName)
    {
        std::vector<DWORD> pids;

        UniqueHandle hSnap{ CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
        if (!hSnap || hSnap.get() == INVALID_HANDLE_VALUE)
            return pids;

        PROCESSENTRY32W pe{ sizeof(pe) };
        if (!Process32FirstW(hSnap.get(), &pe))
            return pids;

        do {
            if (_wcsicmp(pe.szExeFile, exeName.c_str()) == 0)
                pids.push_back(pe.th32ProcessID);
        } while (Process32NextW(hSnap.get(), &pe));

        return pids;
    }

	/// @brief Kill specific process by its PID
    inline bool TerminateProcessByPid(DWORD pid)
    {
        UniqueHandle hProc{ OpenProcess(PROCESS_TERMINATE, FALSE, pid) };
        if (!hProc)
            return false;

        bool ok = ::TerminateProcess(hProc.get(), 0) == TRUE;
        return ok;
    }

	/// @brief Check if a process with the given executable name is running
    inline bool IsProcessRunning(const std::string& exeName)
    {
        return !FindProcessesByName(FilePath::Utf8ToWide(exeName)).empty();
    }
}