import { isObject } from '../src/utils/verify';
import fs from 'fs';
import path from 'path';
import machineId from 'node-machine-id';

interface PrivateConfig {
  /** 是否注册VueDevTools组件  */
  isUseVueDevTools?: boolean;
  /** 设备id */
  deviceID?: string;
}

/**
 * 获取或创建设备标识
 */
export function getPrivateConfig(): PrivateConfig {
  const CONFIG_FILE = path.resolve(process.cwd(), '.MyPrivateConfig');

  try {
    const config: PrivateConfig = { isUseVueDevTools: true };
    // 2. 尝试读取本地存储
    if (fs.existsSync(CONFIG_FILE)) {
      const content = fs.readFileSync(CONFIG_FILE, 'utf-8');
      try {
        let json: PrivateConfig = JSON.parse(content);
        json = isObject(json) ? json : {};
        config.isUseVueDevTools = json.isUseVueDevTools ?? true;
        config.deviceID = json.deviceID ?? machineId.machineIdSync(true) ?? `${Date.now()}${Math.floor(Math.random() * 10000000000)}`;

        // oxlint-disable-next-line no-unused-vars
      } catch (error: any) {}
    }
    fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf-8');
    return config;
  } catch (error: any) {
    console.error('Device ID management error:', error);
    return {};
  }
}
