'use strict';

const path = require('path');
require('dotenv').config({ path: path.join(process.cwd(), '.env') });
require('dotenv').config({ path: path.join(process.env.ProgramData || 'C:\\ProgramData', 'ARKHON', 'Agent', '.env') });

const { getBillingPrintConfig } = require('../src/modules/billing-print/billing-print.config');
const { buildBillingUrl, maskBillingUrl, resolveQrAuthorization, publicAuthorizationSummary } = require('../src/modules/billing-print/billing-print.service');
const evidence = require('../src/modules/billing-print/billing-print.evidence');

function main() {
  const config = getBillingPrintConfig();
  const parsed = {
    cfacturacion: process.env.ARKHON_QR_DIAG_BILLING_CODE || 'DIAGNOSTICO',
    ticketToken: process.env.ARKHON_QR_DIAG_TICKET_TOKEN || '',
  };
  const auth = resolveQrAuthorization(config, parsed);
  const summary = publicAuthorizationSummary(auth);
  let qrUrl = null;
  let qrUrlMasked = null;
  let urlError = null;

  if (auth.allowed) {
    try {
      qrUrl = buildBillingUrl({ ...config, branchSlug: auth.slug || config.branchSlug }, parsed.cfacturacion, {
        ticketToken: parsed.ticketToken || parsed.cfacturacion,
      });
      qrUrlMasked = maskBillingUrl(qrUrl);
    } catch (err) {
      urlError = err.message;
    }
  } else {
    evidence.appendLog('qr-print-diagnose.log', 'QR_SKIPPED_SECURITY_BLOCK', {
      reason: auth.reason,
      authorization: summary,
    });
  }

  const report = {
    ok: true,
    mode: 'diagnose',
    printerName: config.outputPrinterName || config.printerName || null,
    capturePrinterName: config.capturePrinterName || null,
    qr: {
      enabled: config.qrEnabled,
      mode: config.qrMode,
      paperWidth: config.qrPaperWidth,
      size: config.qrSize || (config.qrPaperWidth <= 58 ? config.qrSize58 : config.qrSize80),
      errorCorrection: config.qrErrorCorrection,
      feedBefore: config.qrFeedBefore,
      feedAfter: config.qrFeedAfter,
      requireCloudAuthorization: config.qrRequireCloudAuthorization,
    },
    portalBase: config.portalUrl ? '[configured]' : null,
    branchCode: config.branchCode || null,
    branchSlug: config.branchSlug || summary.slug || null,
    authorization: summary,
    qrUrlMasked,
    urlError,
    evidenceDir: evidence.billingEvidenceDir(),
  };

  evidence.appendLog('qr-print-diagnose.log', 'QR_DIAGNOSE', report);
  evidence.writeEvidence(report);
  process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
}

main();
