'use strict';

function appendTicketCaptureLog(event, payload = {}) {
  try {
    require('../modules/billing-print/billing-print.evidence').appendLog('ticket-capture.log', event, payload);
  } catch (_) {}
}

function markBillingRuntime(billingPrint, value) {
  try {
    billingPrint?.service?.diagnostics?.mark?.({ serviceRuntimeHasBillingPrint: value === true, processPid: process.pid });
  } catch (_) {}
}

function startConnector({ app, runtimeMode, isConnectorRuntime, isSetupComplete, startAgent, logger }) {
  if (!isConnectorRuntime(runtimeMode)) return;
  if (!isSetupComplete()) {
    logger.info({ event: 'agent_start_deferred_until_setup_complete' });
    return;
  }
  try {
    startAgent(app);
  } catch (error) {
    logger.warn({ event: 'agent_start_failed', error: error.message });
  }
}

function startOperationalSchedulers({ runtimeMode, isCloudRuntime, isSetupComplete, billingPrint, offlineSync, arkhonCard, logger }) {
  if (!isSetupComplete()) {
    logger.info({ event: 'operational_schedulers_deferred_until_setup_complete' });
    markBillingRuntime(billingPrint, Boolean(billingPrint?.bootstrap?.bootstrapBillingModules));
    appendTicketCaptureLog('WATCHER_DISABLED', { reason: 'setup_incomplete', pid: process.pid, runtimeMode });
    return;
  }
  try { require('../services/whatsappService').iniciarScheduler(); } catch (_) {}
  if (isCloudRuntime(runtimeMode)) {
    markBillingRuntime(billingPrint, false);
    appendTicketCaptureLog('WATCHER_DISABLED', { reason: 'cloud_runtime', pid: process.pid, runtimeMode });
    return;
  }
  markBillingRuntime(billingPrint, Boolean(billingPrint?.bootstrap?.bootstrapBillingModules));
  const tasks = [
    ['billing_print_start_failed', () => billingPrint.bootstrap.bootstrapBillingModules({ source: 'runtime_start' })],
    ['offline_sync_start_failed', () => offlineSync.scheduler.startSyncScheduler()],
    ['arkhon_card_scheduler_start_failed', () => arkhonCard.scheduler.startArkhonCardScheduler()],
  ];
  for (const [event, task] of tasks) {
    try { task(); } catch (error) { logger.warn({ event, error: error.message }); }
  }
}

module.exports = { startConnector, startOperationalSchedulers };
