'use strict';

const { provisionWithClaimCode, provisionWithControlNumber } = require('../src/agent/provisioningClient');

function arg(name) {
  const flag = `--${name}`;
  const index = process.argv.indexOf(flag);
  if (index >= 0) return process.argv[index + 1] || '';
  const prefixed = process.argv.find((item) => item.startsWith(`${flag}=`));
  return prefixed ? prefixed.slice(flag.length + 1) : '';
}

function boolArg(name) {
  return process.argv.includes(`--${name}`);
}

async function main() {
  const claimCode = arg('claimCode') || arg('claim-code') || process.env.ARKHON_CLAIM_CODE;
  const controlNumber = arg('controlNumber') || arg('control-number') || process.env.ARKHON_LICENSE_CONTROL_NUMBER;
  const controlPassword = arg('controlPassword') || arg('control-password') || process.env.ARKHON_LICENSE_CONTROL_PASSWORD;
  const baseOptions = {
    cloudUrl: arg('cloudUrl') || arg('cloud-url') || undefined,
    configPath: arg('configPath') || arg('config-path') || undefined,
    deviceId: arg('deviceId') || arg('device-id') || undefined,
    installId: arg('installId') || arg('install-id') || undefined,
    hardwareId: arg('hardwareId') || arg('hardware-id') || undefined,
    hostname: arg('hostname') || undefined,
    version: arg('version') || undefined,
    skipLicenseValidation: boolArg('skip-license-validation'),
  };
  const result = controlNumber || controlPassword
    ? await provisionWithControlNumber({ ...baseOptions, controlNumber, controlPassword })
    : await provisionWithClaimCode({ ...baseOptions, claimCode });
  const license = result.license || {};
  console.log(JSON.stringify({
    ok: result.ok,
    provisioningStatus: result.provisioningStatus,
    canSign: result.canSign,
    tenantId: result.tenantId,
    branchId: result.branchId,
    agentId: result.agentId,
    agentKeyId: result.agentKeyId,
    license: {
      allowed: license.allowed === true,
      reason: license.reason || null,
      agent: license.agent ? { hwidAuthorized: license.agent.hwidAuthorized === true } : null,
      features: license.features ? { updater: license.features.updater === true } : null,
      update: license.update ? { allowed: license.update.allowed === true } : null,
      status: license.license?.status || license.status || null,
      skipped: license.skipped === true,
    },
  }, null, 2));
}

main().catch((err) => {
  const payload = err.payload || {};
  console.error(JSON.stringify({
    ok: false,
    error: payload.reason || payload.error || err.code || err.message,
    status: err.status || null,
  }, null, 2));
  process.exit(1);
});
