'use strict';

const { execSync } = require('child_process');
const crypto       = require('crypto');
const os           = require('os');

const IS_WINDOWS = process.platform === 'win32';
const LICENSE_HWID_OVERRIDE = /^[A-F0-9]{32}$/i;

function configuredLicenseHwid() {
  const override = String(process.env.ARKHON_LICENSE_HWID || '').trim().toUpperCase();
  return LICENSE_HWID_OVERRIDE.test(override) ? override : null;
}

function wmicGet(query) {
  try {
    const out = execSync(`wmic ${query} /value`, { timeout: 5000 }).toString();
    const match = out.match(/=(.+)/);
    return match ? match[1].trim() : 'UNKNOWN';
  } catch (_) {
    return 'UNKNOWN';
  }
}

function getHardwareId() {
  const override = configuredLicenseHwid();
  if (override) return override;
  let raw;

  if (IS_WINDOWS) {
    const mb  = wmicGet('baseboard get SerialNumber');
    const hdd = wmicGet('diskdrive get SerialNumber');
    const mac = wmicGet('nic where "NetEnabled=true" get MACAddress');
    raw = `${mb}|${hdd}|${mac}`;
  } else {
    
    const nets = os.networkInterfaces();
    const mac  = Object.values(nets)
      .flat()
      .find(n => !n.internal && n.family === 'IPv4')?.mac || 'UNKNOWN';
    raw = `${os.hostname()}|${mac}|${process.env.USER || 'USER'}`;
  }

  
  if (raw === 'UNKNOWN|UNKNOWN|UNKNOWN') {
    raw = `${os.hostname()}|${process.env.USERNAME || process.env.USER || 'USER'}`;
  }

  return crypto
    .createHash('sha256')
    .update(raw)
    .digest('hex')
    .substring(0, 32)
    .toUpperCase();
}

module.exports = { getHardwareId };
