/**
 * Update Service — 自动更新服务
 *
 * @see docs/生产级通用 AI Agent 智能体桌面应用：完整设计与构建指南.html — 第十二章
 */

import type { BrowserWindow } from 'electron';
import log from 'electron-log';

interface UpdateInfo {
  version: string;
  releaseNotes?: string;
}

interface DownloadProgress {
  bytesPerSecond: number;
  percent: number;
  transferred: number;
  total: number;
}

export class UpdateService {
  private autoUpdater: {
    checkForUpdates: () => void;
    quitAndInstall: () => void;
    on: (event: string, callback: (...args: unknown[]) => void) => void;
    logger: unknown;
    autoInstallOnAppQuit: boolean;
    autoDownload: boolean;
  } | null = null;

  constructor(private mainWindow: BrowserWindow) {}

  initialize(): void {
    try {
      // electron-updater 可能未安装
      // eslint-disable-next-line @typescript-eslint/no-require-imports
      const { autoUpdater } = require('electron-updater');
      this.autoUpdater = autoUpdater;
      if (!this.autoUpdater) return;
      this.autoUpdater.logger = log;
      this.autoUpdater.autoInstallOnAppQuit = true;
      this.autoUpdater.autoDownload = true;

      this.autoUpdater.on('checking-for-update', () => this.sendStatus('checking'));
      this.autoUpdater.on('update-available', (info: unknown) => {
        this.sendStatus('available', { version: (info as UpdateInfo).version });
      });
      this.autoUpdater.on('download-progress', (progress: unknown) => {
        this.sendStatus('downloading', { progress });
      });
      this.autoUpdater.on('update-downloaded', (info: unknown) => {
        this.sendStatus('downloaded', { version: (info as UpdateInfo).version });
      });
      this.autoUpdater.on('error', (err: unknown) => {
        this.sendStatus('error', { error: (err as Error).message });
      });

      setTimeout(() => this.autoUpdater?.checkForUpdates(), 5_000);
    } catch {
      log.warn('electron-updater not available, auto-update disabled');
    }
  }

  checkNow(): void {
    this.autoUpdater?.checkForUpdates();
  }

  installAndRestart(): void {
    this.autoUpdater?.quitAndInstall();
  }

  private sendStatus(stage: string, data?: Record<string, unknown>): void {
    if (!this.mainWindow.isDestroyed()) {
      this.mainWindow.webContents.send('update:status', { stage, ...data });
    }
  }
}
