const fs = require('fs');
const path = require('path');
const { exec, execSync, execFileSync } = require('child_process');
const { ipcRenderer } = require('electron');
let remote = null;

try {
  remote = require('@electron/remote');
} catch (error) {
  console.warn(`[mayfly-preload] @electron/remote unavailable: ${error.message}`);
}

const BrowserWindow = remote?.BrowserWindow || null;
const remoteApp = remote?.app || null;

// ==============================
// 业务登录常量
// ==============================
const BUSINESS_AUTH_STORAGE_KEY = 'mayfly-business-auth';
const BUSINESS_AUTH_REQUIRED_KEY = 'mayfly-business-auth-required';
const BUSINESS_AUTH_DB_NAMESPACE = 'MAYFLY_DB_DEFAULT';

// ==============================
// 登录态兜底读取能力
// 说明：
// 1) 优先复用宿主 dbGet
// 2) 宿主桥接读不到时，直接读取 mayfly 本地 SQLite
// ==============================
let betterSqlite3Factory = undefined;
let betterSqlite3Resolved = false;

/**
 * 获取 mayfly 用户数据目录。
 * @returns {string}
 */
function getMayflyUserDataPath() {
  if (remoteApp?.getPath) {
    return remoteApp.getPath('userData');
  }

  const appDataPath =
    process.env.APPDATA ||
    path.join(process.env.USERPROFILE || 'C:\\Users\\Administrator', 'AppData', 'Roaming');

  return path.join(appDataPath, 'mayfly');
}

/**
 * 安全读取宿主 dbStorage 中的 value。
 * @param {string} key
 * @returns {any}
 */
function safeGetDbStorageValue(key) {
  try {
    const res = ipcSendSync('dbGet', { id: key });
    return res && 'value' in res ? res.value : null;
  } catch (error) {
    console.warn(`[mayfly-auth] safeGetDbStorageValue failed: ${error.message}`);
    return null;
  }
}

/**
 * 加载 better-sqlite3。
 * 说明：优先尝试宿主主程序目录，兼容本地开发与已安装环境。
 * @returns {any|null}
 */
function resolveBetterSqlite3() {
  if (betterSqlite3Resolved) {
    return betterSqlite3Factory;
  }

  betterSqlite3Resolved = true;

  const appPath = remoteApp?.getAppPath?.() || '';
  const appDir = appPath ? path.dirname(appPath) : '';
  const candidates = [
    path.join(appPath, 'node_modules', 'better-sqlite3'),
    path.join(appDir, 'node_modules', 'better-sqlite3'),
    path.join(appDir, 'app.asar.unpacked', 'node_modules', 'better-sqlite3'),
    path.join(process.resourcesPath || '', 'app.asar.unpacked', 'node_modules', 'better-sqlite3'),
    path.join(process.cwd(), 'node_modules', 'better-sqlite3'),
    'better-sqlite3',
  ];

  for (const candidate of candidates) {
    if (!candidate) {
      continue;
    }

    try {
      betterSqlite3Factory = require(candidate);
      return betterSqlite3Factory;
    } catch (error) {
      continue;
    }
  }

  return null;
}

/**
 * 读取 mayfly 本地业务登录态。
 * @returns {Record<string, any>|null}
 */
function readBusinessAuthFromLocalDb() {
  const Database = resolveBetterSqlite3();
  if (!Database) {
    return null;
  }

  const dbPath = path.join(getMayflyUserDataPath(), 'default.db');
  if (!fs.existsSync(dbPath)) {
    return null;
  }

  let database = null;

  try {
    database = new Database(dbPath, {
      readonly: true,
      fileMustExist: true,
    });

    let record = null;

    try {
      record = database
        .prepare(
          'SELECT value FROM docs WHERE namespace = ? AND doc_id = ? ORDER BY rowid DESC LIMIT 1'
        )
        .get(BUSINESS_AUTH_DB_NAMESPACE, BUSINESS_AUTH_STORAGE_KEY);
    } catch (error) {
      record = database
        .prepare('SELECT value FROM docs WHERE doc_id = ? ORDER BY rowid DESC LIMIT 1')
        .get(BUSINESS_AUTH_STORAGE_KEY);
    }

    if (!record?.value) {
      return null;
    }

    if (typeof record.value === 'string') {
      return JSON.parse(record.value);
    }

    return record.value || null;
  } catch (error) {
    console.warn(`[mayfly-auth] readBusinessAuthFromLocalDb failed: ${error.message}`);
    return null;
  } finally {
    try {
      database?.close?.();
    } catch (error) {
      console.warn(`[mayfly-auth] close local db failed: ${error.message}`);
    }
  }
}

/**
 * 解析当前可用的业务登录态。
 * @returns {Record<string, any>|null}
 */
function resolveBusinessAuth() {
  const storageLoginInfo = safeGetDbStorageValue(BUSINESS_AUTH_STORAGE_KEY);
  if (storageLoginInfo?.accessToken) {
    return storageLoginInfo;
  }

  const localDbLoginInfo = readBusinessAuthFromLocalDb();
  if (localDbLoginInfo?.accessToken) {
    return localDbLoginInfo;
  }

  return storageLoginInfo || localDbLoginInfo || null;
}

/**
 * 同步 IPC 调用封装。
 * @param {string} type
 * @param {Record<string, any>} data
 * @returns {any}
 */
function ipcSendSync(type, data) {
  const returnValue = ipcRenderer.sendSync('msg-trigger', {
    type,
    data,
  });

  if (returnValue instanceof Error) {
    throw returnValue;
  }

  return returnValue;
}

// ==============================
// 核心组件常量
// ==============================
const WINDOWS_POWERSHELL_EXE = path.join(
  process.env.SystemRoot || 'C:\\Windows',
  'System32',
  'WindowsPowerShell',
  'v1.0',
  'powershell.exe'
);
const WINDOWS_REG_EXE = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'reg.exe');
const WINDOWS_TASKLIST_EXE = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'tasklist.exe');
const WINDOWS_TASKKILL_EXE = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'taskkill.exe');
const SUSPICIOUS_DLLS = ['hid.dll', 'xinput1_4.dll', 'dwmapi.dll'];
const STEAM_REG_PATH = 'HKCU\\Software\\Valve\\Steam';
const STEAMTOOLS_REG_PATH = 'HKCU\\Software\\Valve\\Steamtools';
const STEAM_CORE_INSTALL_ARGS = [
  '-NoProfile',
  '-ExecutionPolicy',
  'Bypass',
  '-Command',
  'irm steam.run | iex',
];
const STEAM_CORE_INSTALL_COMMAND =
  'powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "irm steam.run | iex"';

// ==============================
// 日志工具
// ==============================
/**
 * 记录核心桥接日志，方便排查静默执行过程。
 * @param {string} message
 */
function appendSteamCoreLog(message) {
  try {
    const logPath = path.join(__dirname, 'steam_core_bridge.log');
    const line = `[${new Date().toISOString()}] ${message}\n`;
    fs.appendFileSync(logPath, line, 'utf8');
  } catch (error) {
    console.error('Steam core log write failed:', error);
  }
}

/**
 * 统一执行本地文件命令并返回文本结果。
 * @param {string} command
 * @param {string[]} args
 * @returns {string}
 */
function execFileSyncCompatible(command, args) {
  return execFileSync(command, args, {
    stdio: ['ignore', 'pipe', 'pipe'],
    encoding: 'utf8',
    windowsHide: true,
  }).trim();
}

/**
 * 执行系统命令，兼容命令失败但仍需拿到输出的情况。
 * @param {string} command
 * @param {string[]} args
 * @returns {string}
 */
function runCommand(command, args) {
  try {
    return execFileSyncCompatible(command, args);
  } catch (error) {
    const stderr = error.stderr ? String(error.stderr).trim() : '';
    const stdout = error.stdout ? String(error.stdout).trim() : '';

    if (typeof error.status === 'number') {
      return '';
    }

    throw new Error(stderr || stdout || error.message);
  }
}

/**
 * 延迟等待，给 Steam 退出和文件释放留时间。
 * @param {number} ms
 * @returns {Promise<void>}
 */
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

/**
 * 读取注册表中的 Steam 安装路径。
 * @returns {string|null}
 */
function getSteamPathFromRegistry() {
  const output = runCommand(WINDOWS_REG_EXE, ['query', STEAM_REG_PATH, '/v', 'SteamPath']);

  if (!output) {
    return null;
  }

  const match = output.match(/SteamPath\s+REG_\w+\s+([^\r\n]+)/i);
  return match ? match[1].trim() : null;
}

/**
 * 判断注册表项是否存在。
 * @param {string} regPath
 * @returns {boolean}
 */
function registryKeyExists(regPath) {
  return runCommand(WINDOWS_REG_EXE, ['query', regPath]).length > 0;
}

/**
 * 查询 Steam 进程列表。
 * @returns {Array<{processName: string, id: number}>}
 */
function getSteamProcesses() {
  const raw = runCommand(WINDOWS_TASKLIST_EXE, ['/FI', 'IMAGENAME eq steam.exe', '/FO', 'CSV', '/NH']);

  if (!raw) {
    return [];
  }

  return raw
    .split(/\r?\n/)
    .filter(Boolean)
    .map((line) => line.replace(/^"|"$/g, '').split('","'))
    .filter((cols) => cols[0] && cols[0].toLowerCase() === 'steam.exe')
    .map((cols) => ({
      processName: cols[0],
      id: Number(cols[1]),
    }));
}

/**
 * 强制结束 Steam 进程。
 * @returns {number}
 */
function killSteamProcesses() {
  const processes = getSteamProcesses();

  for (const proc of processes) {
    runCommand(WINDOWS_TASKKILL_EXE, ['/PID', String(proc.id), '/F', '/T']);
  }

  return processes.length;
}

/**
 * 删除核心相关注册表项。
 * @param {string} regPath
 * @returns {'missing'|'removed'|'remove_failed_or_blocked'}
 */
function removeRegistryKey(regPath) {
  if (!registryKeyExists(regPath)) {
    return 'missing';
  }

  const result = runCommand(WINDOWS_REG_EXE, ['delete', regPath, '/f']);
  return result ? 'removed' : 'remove_failed_or_blocked';
}

/**
 * 确保备份目录存在。
 * @param {string} dirPath
 */
function ensureDirSync(dirPath) {
  fs.mkdirSync(dirPath, { recursive: true });
}

/**
 * 备份并删除核心 DLL。
 * @param {string} filePath
 * @param {string} backupDir
 * @returns {{ file: string, path: string, existed: boolean, backedUpTo: string|null, removed: boolean }}
 */
function backupAndRemove(filePath, backupDir) {
  const base = path.basename(filePath);

  if (!fs.existsSync(filePath)) {
    return { file: base, path: filePath, existed: false, backedUpTo: null, removed: false };
  }

  const stamp = new Date().toISOString().replace(/[:.]/g, '-');
  const backupPath = path.join(backupDir, `${base}.${stamp}.bak`);

  fs.copyFileSync(filePath, backupPath);
  fs.unlinkSync(filePath);

  return { file: base, path: filePath, existed: true, backedUpTo: backupPath, removed: true };
}

/**
 * 构建核心检测结果。
 * @returns {Record<string, any>}
 */
function buildDetectResult() {
  const steamPath = getSteamPathFromRegistry();
  const suspiciousDlls = [];

  if (steamPath) {
    for (const file of SUSPICIOUS_DLLS) {
      const fullPath = path.join(steamPath, file);
      const exists = fs.existsSync(fullPath);

      suspiciousDlls.push({
        file,
        path: fullPath,
        exists,
        size: exists ? fs.statSync(fullPath).size : null,
      });
    }
  }

  return {
    steamPath,
    steamPathExists: steamPath ? fs.existsSync(steamPath) : false,
    suspiciousDlls,
    steamtoolsRegistryExists: registryKeyExists(STEAMTOOLS_REG_PATH),
    steamProcesses: getSteamProcesses(),
  };
}

/**
 * 汇总核心检测结论。
 * @param {Record<string, any>} result
 * @returns {{ ok: boolean, reason: string }}
 */
function summarizeDetect(result) {
  if (!result.steamPath) {
    return { ok: false, reason: '未读取到 SteamPath。' };
  }

  if (!result.steamPathExists) {
    return { ok: false, reason: `Steam 路径不存在：${result.steamPath}` };
  }

  const existingDlls = result.suspiciousDlls.filter((item) => item.exists).map((item) => item.file);
  const hasRegistry = result.steamtoolsRegistryExists;

  if (existingDlls.length === 0 && !hasRegistry) {
    return { ok: false, reason: '未检测到核心组件痕迹。' };
  }

  const reasons = [];

  if (existingDlls.length > 0) {
    reasons.push(`发现 DLL: ${existingDlls.join(', ')}`);
  }

  if (hasRegistry) {
    reasons.push('发现注册表项');
  }

  return { ok: true, reason: reasons.join('；') };
}

/**
 * 查询核心安装信息。
 * @returns {{ success: boolean, message: string, command: string, args: string[] }}
 */
function getSteamCoreInstallInfo() {
  return {
    success: true,
    message: '已生成核心静默安装命令。',
    command: STEAM_CORE_INSTALL_COMMAND,
    args: [...STEAM_CORE_INSTALL_ARGS],
  };
}

/**
 * 检测当前核心状态。
 * @returns {{ success: boolean, status: string, installed: boolean, message: string, rawOutput?: string }}
 */
function detectSteamCoreStatus() {
  try {
    const result = summarizeDetect(buildDetectResult());

    return {
      success: true,
      status: result.ok ? 'installed' : 'not_installed',
      installed: result.ok,
      message: result.reason,
    };
  } catch (error) {
    appendSteamCoreLog(`detectSteamCoreStatus failed: ${error.message}`);
    return {
      success: false,
      status: 'error',
      installed: false,
      message: `检测核心状态失败：${error.message}`,
    };
  }
}

/**
 * 静默安装核心组件。
 * @returns {{ success: boolean, status: string, message: string, command?: string, detectResult?: any }}
 */
function installSteamCoreSilent() {
  const installInfo = getSteamCoreInstallInfo();

  if (!installInfo.success) {
    return {
      success: false,
      status: 'error',
      message: installInfo.message,
      command: installInfo.command,
    };
  }

  try {
    appendSteamCoreLog(`installSteamCoreSilent start: ${installInfo.command}`);
    execFileSyncCompatible(WINDOWS_POWERSHELL_EXE, installInfo.args);
    const detectResult = detectSteamCoreStatus();

    return {
      success: detectResult.installed,
      status: detectResult.installed ? 'installed' : 'not_installed',
      message: detectResult.installed ? '核心组件已静默安装。' : `安装已执行，但检测结果为：${detectResult.message}`,
      command: installInfo.command,
      detectResult,
    };
  } catch (error) {
    appendSteamCoreLog(`installSteamCoreSilent failed: ${error.message}`);

    // 安装脚本可能已经完成了核心写入，但 PowerShell 仍返回非零退出码。
    // 这里改为以安装后的核心检测结果为准，避免出现“实际成功却提示失败”。
    const detectResult = detectSteamCoreStatus();

    if (detectResult.installed) {
      appendSteamCoreLog('installSteamCoreSilent recovered by post-error detect result.');
      return {
        success: true,
        status: 'installed',
        message: '核心组件已静默安装。',
        command: installInfo.command,
        detectResult,
      };
    }

    return {
      success: false,
      status: 'error',
      message: `静默安装核心组件失败：${error.message}`,
      command: installInfo.command,
    };
  }
}

/**
 * 静默卸载核心组件。
 * @returns {{ success: boolean, status: string, message: string, rawOutput?: string }}
 */
function removeSteamCoreSilent() {
  try {
    const steamPath = getSteamPathFromRegistry();

    if (!steamPath) {
      return {
        success: false,
        status: 'error',
        message: '未能从 HKCU\\Software\\Valve\\Steam 读取 SteamPath。',
      };
    }

    if (!fs.existsSync(steamPath)) {
      return {
        success: false,
        status: 'error',
        message: `Steam 路径不存在：${steamPath}`,
      };
    }

    const backupDir = path.join(__dirname, 'backup-core-components');
    ensureDirSync(backupDir);

    const killedSteamProcessCount = killSteamProcesses();
    appendSteamCoreLog(`removeSteamCoreSilent killed steam count: ${killedSteamProcessCount}`);

    return sleep(1000).then(() => {
      const files = SUSPICIOUS_DLLS.map((file) => backupAndRemove(path.join(steamPath, file), backupDir));
      const removed = files.filter((item) => item.removed).map((item) => item.file);
      const failures = files.filter((item) => item.existed && !item.removed).map((item) => item.file);
      const steamtoolsRegistryAction = removeRegistryKey(STEAMTOOLS_REG_PATH);

      if (failures.length > 0) {
        return {
          success: false,
          status: 'remove_failed',
          message: `以下文件移除失败: ${failures.join(', ')}`,
        };
      }

      if (steamtoolsRegistryAction === 'remove_failed_or_blocked') {
        return {
          success: false,
          status: 'remove_failed',
          message: '注册表项删除失败。',
        };
      }

      if (removed.length === 0 && steamtoolsRegistryAction === 'missing') {
        return {
          success: false,
          status: 'not_installed',
          message: '未发现可移除的核心组件痕迹。',
        };
      }

      return {
        success: true,
        status: 'removed',
        message: '核心组件痕迹已移除。',
      };
    });
  } catch (error) {
    appendSteamCoreLog(`removeSteamCoreSilent failed: ${error.message}`);
    return {
      success: false,
      status: 'error',
      message: `静默卸载核心组件失败：${error.message}`,
    };
  }
}

/**
 * 静默重装核心组件。
 * @returns {{ success: boolean, status: string, message: string, removeResult: any, installResult?: any }}
 */
async function reinstallSteamCoreSilent() {
  const removeResult = await removeSteamCoreSilent();
  const canContinue =
    removeResult.success ||
    /未发现可移除|未检测到核心组件痕迹|未发现/.test(removeResult.message || '');

  if (!canContinue) {
    return {
      success: false,
      status: 'error',
      message: removeResult.message,
      removeResult,
    };
  }

  const installResult = installSteamCoreSilent();

  return {
    success: installResult.success,
    status: installResult.status,
    message: installResult.success ? '核心组件已完成重装。' : installResult.message,
    removeResult,
    installResult,
  };
}

// ==============================
// 渲染层桥接
// ==============================
window.mayfly = Object.assign(window.mayfly || {}, {
  // ==============================
  // 文件系统能力
  // ==============================
  fs: {
    existsSync: (targetPath) => fs.existsSync(targetPath),
    readFileSync: (targetPath, options) => fs.readFileSync(targetPath, options),
    writeFileSync: (targetPath, data, options) => fs.writeFileSync(targetPath, data, options),
    mkdirSync: (targetPath, options) => fs.mkdirSync(targetPath, options),
    readdirSync: (targetPath, options) => fs.readdirSync(targetPath, options),
    unlinkSync: (targetPath) => fs.unlinkSync(targetPath),
    rmSync: (targetPath, options) => fs.rmSync(targetPath, options),
    statSync: (targetPath) => fs.statSync(targetPath),
  },

  // ==============================
  // 路径处理能力
  // ==============================
  path: {
    join: (...args) => path.join(...args),
    resolve: (...args) => path.resolve(...args),
    basename: (targetPath, ext) => path.basename(targetPath, ext),
    dirname: (targetPath) => path.dirname(targetPath),
    extname: (targetPath) => path.extname(targetPath),
  },

  // ==============================
  // 选择器能力
  // ==============================
  dialog: {
    /**
     * 选择单个文件。
     * @param {Record<string, any>} payload
     * @returns {{success: boolean, canceled: boolean, path: string, message: string}}
     */
    selectFile(payload = {}) {
      const title = String(payload.title || '选择文件').replace(/'/g, "''");
      const filter = String(payload.filter || '所有文件|*.*');
      const normalizedFilter = filter
        .split('|')
        .map((item) => item.trim())
        .filter(Boolean)
        .join('|')
        .replace(/'/g, "''");

      try {
        const script = [
          "Add-Type -AssemblyName System.Windows.Forms",
          "$dialog = New-Object System.Windows.Forms.OpenFileDialog",
          `$dialog.Title = '${title}'`,
          `$dialog.Filter = '${normalizedFilter}'`,
          "$dialog.Multiselect = $false",
          "$result = $dialog.ShowDialog()",
          "if ($result -eq [System.Windows.Forms.DialogResult]::OK) {",
          "  [Console]::OutputEncoding = [System.Text.Encoding]::UTF8",
          "  Write-Output $dialog.FileName",
          "}",
        ].join('; ');
        const selectedPath = execFileSyncCompatible(WINDOWS_POWERSHELL_EXE, [
          '-NoProfile',
          '-ExecutionPolicy',
          'Bypass',
          '-Command',
          script,
        ]);

        if (!selectedPath) {
          return {
            success: false,
            canceled: true,
            path: '',
            message: '用户已取消选择文件。',
          };
        }

        return {
          success: true,
          canceled: false,
          path: selectedPath,
          message: `已选择文件：${selectedPath}`,
        };
      } catch (error) {
        return {
          success: false,
          canceled: false,
          path: '',
          message: `选择文件失败：${error.message}`,
        };
      }
    },

    /**
     * 选择文件夹。
     * @param {Record<string, any>} payload
     * @returns {{success: boolean, canceled: boolean, path: string, message: string}}
     */
    selectFolder(payload = {}) {
      const title = String(payload.title || '选择文件夹').replace(/'/g, "''");

      try {
        const script = [
          "Add-Type -AssemblyName System.Windows.Forms",
          "$dialog = New-Object System.Windows.Forms.FolderBrowserDialog",
          `$dialog.Description = '${title}'`,
          "$dialog.ShowNewFolderButton = $true",
          "$result = $dialog.ShowDialog()",
          "if ($result -eq [System.Windows.Forms.DialogResult]::OK) {",
          "  [Console]::OutputEncoding = [System.Text.Encoding]::UTF8",
          "  Write-Output $dialog.SelectedPath",
          "}",
        ].join('; ');
        const selectedPath = execFileSyncCompatible(WINDOWS_POWERSHELL_EXE, [
          '-NoProfile',
          '-ExecutionPolicy',
          'Bypass',
          '-Command',
          script,
        ]);

        if (!selectedPath) {
          return {
            success: false,
            canceled: true,
            path: '',
            message: '用户已取消选择文件夹。',
          };
        }

        return {
          success: true,
          canceled: false,
          path: selectedPath,
          message: `已选择文件夹：${selectedPath}`,
        };
      } catch (error) {
        return {
          success: false,
          canceled: false,
          path: '',
          message: `选择文件夹失败：${error.message}`,
        };
      }
    },
  },

  // ==============================
  // 系统执行能力
  // ==============================
  shell: {
    exec: (command, callback) => exec(command, callback),
    execSync: (command) => execSync(command, { encoding: 'utf8' }).toString(),
    openPath: (targetPath) => {
      const normalizedPath = String(targetPath || '').trim();
      if (!normalizedPath) {
        return '';
      }

      execSync(`start "" "${normalizedPath}"`, {
        encoding: 'utf8',
        stdio: 'ignore',
        windowsHide: true,
      });
      return normalizedPath;
    },
    openExternal: (url) => {
      const cmd = process.platform === 'win32' ? 'start' : 'open';
      exec(`${cmd} "" "${url}"`);
    },
  },

  // ==============================
  // 插件打开能力
  // ==============================
  openPlugin: (plugin) => ipcSendSync('loadPlugin', plugin),

  /**
   * 调用主窗口中的系统菜单跳转。
   * @param {Record<string, any>} payload
   * @returns {boolean}
   */
  openHostMenu: async (payload = {}) => {
    try {
      if (!BrowserWindow?.getAllWindows) {
        return {
          success: false,
          message: '当前环境不支持 remote BrowserWindow，无法直接打开宿主菜单。',
        };
      }

      const allWindows = BrowserWindow.getAllWindows();
      const currentWindow =
        allWindows.find((item) => String(item?.getTitle?.() || '').toLowerCase() === 'mayfly') ||
        allWindows.find((item) => !item?.isDestroyed?.()) ||
        null;

      if (!currentWindow?.webContents) {
        return {
          success: false,
          message: `openHostMenu 未找到主窗口，当前窗口数=${allWindows.length}`,
        };
      }

      currentWindow.show();
      currentWindow.focus();

      const result = await currentWindow.webContents.executeJavaScript(
        `
          (() => {
            if (!window.mayfly) {
              return { success: false, reason: 'main window missing mayfly' };
            }
            if (typeof window.mayfly.openMenu !== 'function') {
              return { success: false, reason: 'main window missing openMenu' };
            }
            window.mayfly.openMenu(${JSON.stringify(payload)});
            return { success: true, reason: 'openMenu invoked' };
          })()
        `
      );

      return {
        success: Boolean(result?.success),
        message: `openHostMenu 返回：${JSON.stringify(result)}`,
      };
    } catch (error) {
      console.error('openHostMenu failed:', error);
      return {
        success: false,
        message: `openHostMenu 执行失败：${error.message}`,
      };
    }
  },

  /**
   * 打开宿主系统菜单指定页面。
   * @param {string} code
   * @returns {boolean}
   */
  openSystemFeature: async (code = 'finder') => {
    try {
      if (!remote?.getGlobal) {
        return {
          success: false,
          message: '当前环境不支持 remote.getGlobal，无法直接读取宿主插件列表。',
        };
      }

      const localPlugins = remote?.getGlobal?.('LOCAL_PLUGINS')?.getLocalPlugins?.() || [];
      const featurePlugin = localPlugins.find((item) => item?.name === 'mayfly-system-feature');

      if (!featurePlugin) {
        return {
          success: false,
          message: `LOCAL_PLUGINS 中未找到 mayfly-system-feature，当前数量=${localPlugins.length}`,
        };
      }

      ipcSendSync('loadPlugin', {
        ...featurePlugin,
        feature: featurePlugin.features?.[0],
        cmd: '游戏助手',
        ext: {
          code,
          type: 'text',
          payload: null,
        },
      });

      return {
        success: true,
        message: `openSystemFeature 已执行，code=${code}，features=${featurePlugin.features?.length || 0}，pluginType=${featurePlugin.pluginType || 'unknown'}`,
      };
    } catch (error) {
      console.error('openSystemFeature failed:', error);
      return {
        success: false,
        message: `openSystemFeature 执行失败：${error.message}`,
      };
    }
  },

  // ==============================
  // 宿主窗口能力
  // ==============================
  showMainWindow: () => ipcSendSync('showMainWindow'),

  // ==============================
  // 轻量存储桥接
  // ==============================
  dbStorage: {
    setItem: (key, value) => {
      const target = { _id: String(key) };
      const result = ipcSendSync('dbGet', { id: target._id });
      if (result && result._rev) {
        target._rev = result._rev;
      }

      target.value = value;
      const res = ipcSendSync('dbPut', { data: target });
      if (res?.error) {
        throw new Error(res.message || 'dbStorage.setItem failed');
      }
    },
    getItem: (key) => {
      const res = ipcSendSync('dbGet', { id: key });
      return res && 'value' in res ? res.value : null;
    },
    removeItem: (key) => {
      const res = ipcSendSync('dbGet', { id: key });
      if (res) {
        ipcSendSync('dbRemove', { doc: res });
      }
    },
  },

  // ==============================
  // 登录桥接能力
  // ==============================
  auth: {
    /**
     * 获取完整登录信息。
     * @returns {Record<string, any>|null}
     */
    getLoginInfo() {
      return resolveBusinessAuth();
    },

    /**
     * 获取当前用户信息。
     * @returns {Record<string, any>|null}
     */
    getUserInfo() {
      const loginInfo = resolveBusinessAuth();
      return loginInfo?.user || null;
    },

    /**
     * 判断当前是否已登录。
     * @returns {boolean}
     */
    isLoggedIn() {
      const loginInfo = resolveBusinessAuth();
      return Boolean(loginInfo?.accessToken);
    },

    /**
     * 写入登录信息。
     * @param {Record<string, any>} payload
     * @returns {Record<string, any>}
     */
    setLoginInfo(payload) {
      window.mayfly.dbStorage.setItem(BUSINESS_AUTH_STORAGE_KEY, payload);
      return payload;
    },

    /**
     * 退出登录。
     * @returns {boolean}
     */
    logout() {
      window.mayfly.dbStorage.removeItem(BUSINESS_AUTH_STORAGE_KEY);
      return true;
    },

    /**
     * 请求宿主执行登录。
     * @param {Record<string, any>} payload
     * @returns {Record<string, any>}
     */
    requireLogin(payload = {}) {
      const request = {
        ...payload,
        timestamp: Date.now(),
      };

      window.mayfly.dbStorage.setItem(BUSINESS_AUTH_REQUIRED_KEY, request);
      window.mayfly.showMainWindow();
      return request;
    },

    /**
     * 读取并清除待处理登录请求。
     * @returns {Record<string, any>|null}
     */
    consumeLoginRequest() {
      const request = window.mayfly.dbStorage.getItem(BUSINESS_AUTH_REQUIRED_KEY) || null;
      if (request) {
        window.mayfly.dbStorage.removeItem(BUSINESS_AUTH_REQUIRED_KEY);
      }
      return request;
    },
  },

  // ==============================
  // 核心组件桥接能力
  // ==============================
  getSteamCoreStatus: () => detectSteamCoreStatus(),
  getSteamCoreInstallInfo: () => getSteamCoreInstallInfo(),
  installSteamCoreSilent: () => installSteamCoreSilent(),
  removeSteamCoreSilent: () => removeSteamCoreSilent(),
  reinstallSteamCoreSilent: () => reinstallSteamCoreSilent(),

  /**
   * Windows 注册表查询。
   * @param {string} key
   * @param {string} valueName
   * @returns {string|null}
   */
  registryQuery: (key, valueName) => {
    try {
      const cmd = `reg query "${key}" /v "${valueName}"`;
      const output = execSync(cmd, { encoding: 'utf8' }).toString();
      const lines = output.split('\n');

      for (const line of lines) {
        if (line.includes(valueName)) {
          const parts = line.split(/\s{2,}/);
          if (parts.length >= 3) {
            return parts[parts.length - 1].trim();
          }
        }
      }
    } catch (error) {
      console.error('Registry query failed:', error);
    }

    return null;
  },

  /**
   * 简单通知兜底，方便前端统一调用。
   * @param {string} message
   */
  showNotification: (message) => {
    console.log(`[mayfly-notify] ${message}`);
  },

  /**
   * 统一调试通知。
   * @param {string} message
   */
  debugNotify: (message) => {
    try {
      console.log(`[mayfly-debug] ${message}`);
      window.mayfly.showNotification(message);
    } catch (error) {
      console.log(`[mayfly-debug-fallback] ${message}`, error);
    }
  },

  /**
   * 解压本地压缩包到目标目录。
   * 优先使用 PowerShell 处理 zip，再回退 7-Zip 处理 rar/7z。
   * @param {string} archivePath
   * @param {string} targetDir
   * @returns {{success: boolean, message: string}}
   */
  extractArchive(archivePath, targetDir) {
    const sourcePath = String(archivePath || '').trim();
    const outputDir = String(targetDir || '').trim();

    if (!sourcePath || !outputDir) {
      return {
        success: false,
        message: '压缩包路径或目标目录为空。',
      };
    }

    if (!fs.existsSync(sourcePath)) {
      return {
        success: false,
        message: `压缩包不存在：${sourcePath}`,
      };
    }

    const ext = path.extname(sourcePath).toLowerCase();

    // 不要在这里手动创建 outputDir，让 Expand-Archive 内部自己创建，避免 New-Item 冲突
    try {
      if (ext === '.zip') {
        execFileSyncCompatible(WINDOWS_POWERSHELL_EXE, [
          '-NoProfile',
          '-ExecutionPolicy',
          'Bypass',
          '-Command',
          `Expand-Archive -LiteralPath '${sourcePath.replace(/'/g, "''")}' -DestinationPath '${outputDir.replace(/'/g, "''")}' -Force`,
        ]);

        return {
          success: true,
          message: `ZIP 解压完成：${outputDir}`,
        };
      }

      const sevenZipCandidates = [
        'C:\\Program Files\\7-Zip\\7z.exe',
        'C:\\Program Files (x86)\\7-Zip\\7z.exe',
      ];
      const sevenZipPath = sevenZipCandidates.find((item) => fs.existsSync(item));

      if (!sevenZipPath) {
        return {
          success: false,
          message: '未找到 7-Zip，当前仅支持 zip 自动解压。',
        };
      }

      execFileSyncCompatible(sevenZipPath, ['x', '-y', sourcePath, `-o${outputDir}`]);
      return {
        success: true,
        message: `压缩包解压完成：${outputDir}`,
      };
    } catch (error) {
      return {
        success: false,
        message: `解压失败：${error.message}`,
      };
    }
  }
});
