'use strict';

const logger = require('../utils/logger');
const { getAgentConfig, isConfigured } = require('./agentConfig');
const { startHeartbeat } = require('./heartbeatService');
const { startTunnelStatus } = require('./tunnelStatusService');
const { startSyncScheduler } = require('./syncScheduler');
const { startCloudRealtime } = require('./cloudRealtimeClient');
const { startCommandPoller } = require('./commandPoller');
const { startLiveTablesScheduler } = require('./liveTablesScheduler');
const { createInstallationWizardRouter } = require('./installationWizardApi');
const multibranchSync = require('../modules/multibranch-sync');

function startAgent(app) {
  const config = getAgentConfig();
  if (!config.enabled) return { enabled: false };

  app.use('/api/installation-wizard', createInstallationWizardRouter(config));

  if (!isConfigured(config)) {
    logger.warn({ event: 'agent_not_configured', message: 'Local connector enabled but cloud identity is incomplete.' });
    return { enabled: true, configured: false };
  }

  startHeartbeat(config);
  startTunnelStatus(config);
  startSyncScheduler(config);
  startLiveTablesScheduler(config);
  startCommandPoller(config);
  startCloudRealtime(config);
  multibranchSync.start(config);
  logger.info({ event: 'agent_started', agent_id: config.agentId, branch_id: config.branchId });
  return { enabled: true, configured: true };
}

module.exports = { startAgent };
