// ============================================================
// env — 运行时环境信息（平台检测 + 设备标识）
// 合并自 platform.ts + device.ts
// ============================================================

import type { Platform } from '@shared/types';

// ========== 平台检测 ==========

export function getPlatform(): Platform {
   // 如果 preload 暴露了 platform 信息，优先使用
   if (typeof window !== 'undefined' && window.ipcRenderer) {
      const ua = navigator.userAgent.toLowerCase();
      if (ua.includes('mac os') || ua.includes('macintosh')) return 'darwin';
      if (ua.includes('windows') || ua.includes('win32') || ua.includes('win64')) return 'win32';
      if (ua.includes('linux')) return 'linux';
   }

   const ua = navigator.userAgent.toLowerCase();
   if (ua.includes('mac')) return 'darwin';
   if (ua.includes('win')) return 'win32';
   if (ua.includes('linux')) return 'linux';

   return 'win32';
}

export function isMacOS(): boolean { return getPlatform() === 'darwin'; }
export function isWindows(): boolean { return getPlatform() === 'win32'; }
export function isLinux(): boolean { return getPlatform() === 'linux'; }

export function getPlatformName(): string {
   if (isMacOS()) return 'macOS';
   if (isWindows()) return 'Windows';
   if (isLinux()) return 'Linux';
   return '未知平台';
}

export function getShortcutDisplay(key: string): string {
   return isMacOS() ? `⌘+${key}` : `Ctrl+${key}`;
}

export function getContextMenuHint(): string {
   return isMacOS() ? '右键点击 或 Ctrl+点击' : '右键点击';
}

export function isDev(): boolean { return import.meta.env.DEV; }
export function isProd(): boolean { return import.meta.env.PROD; }

// ========== 设备标识 ==========

const DEVICE_ID_KEY = 'ele-heixiu-device-id';

function generateUUID(): string {
   return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
      const r = (Math.random() * 16) | 0;
      return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
   });
}

export function getDeviceId(): string {
   try {
      let id = localStorage.getItem(DEVICE_ID_KEY);
      if (!id) {
         id = generateUUID();
         localStorage.setItem(DEVICE_ID_KEY, id);
      }
      return id;
   } catch {
      return generateUUID();
   }
}
