import cron from 'node-cron';
import { AggregatorRouteMatrixGenerator } from './aggregator-route-matrix-generator';
import { logger } from '../utils/logger';

export function startRouteMatrixScheduler(): void {
  const cronSpec = (process.env.ROUTE_MATRIX_CRON || '').trim();
  const generateOnStart = String(process.env.GENERATE_ROUTE_MATRIX_ON_START || 'false').toLowerCase() === 'true';

  if (!cronSpec && !generateOnStart) {
    return;
  }

  const generator = new AggregatorRouteMatrixGenerator();

  const runGeneration = async () => {
    try {
      const outputPath = await generator.writeToFile();
      logger.info('Planner-v2 route matrix generated', { outputPath });
    } catch (error) {
      logger.warn('Planner-v2 route matrix generation failed', {
        error: error instanceof Error ? error.message : String(error),
      });
    }
  };

  if (generateOnStart) {
    void runGeneration();
  }

  if (cronSpec) {
    cron.schedule(cronSpec, () => {
      void runGeneration();
    });
    logger.info('Planner-v2 route matrix scheduler enabled', { cronSpec });
  }
}
