import * as dotenv from 'dotenv';
import path from 'path';
import { existsSync } from 'fs';
import { ApiServer } from './api/server';
import { closeDatabasePool } from './database/client';
import { logger } from './utils/logger';
import { startRouteMatrixScheduler } from './services/route-matrix-scheduler';

// Load smom-dbis-138 root .env first (single source); works from dist/ or src/
const rootEnvCandidates = [
  path.resolve(__dirname, '../../.env'),   // from dist/
  path.resolve(__dirname, '../../../.env'), // from src/
];
for (const p of rootEnvCandidates) {
  if (existsSync(p)) {
    dotenv.config({ path: p });
    break;
  }
}
dotenv.config();
// Fill contract/token addresses from config/smart-contracts-master.json when not set (e.g. CUSDC_ADDRESS_138, CUSDT_ADDRESS_138)
try {
  const loaderPath = path.resolve(__dirname, '../../../../config/contracts-loader.cjs');
  // eslint-disable-next-line @typescript-eslint/no-var-requires
  const { loadContractsIntoProcessEnv } = require(loaderPath);
  if (typeof loadContractsIntoProcessEnv === 'function') loadContractsIntoProcessEnv([138, 1]);
} catch (_) { /* optional when run outside proxmox repo */ }

const server = new ApiServer();
startRouteMatrixScheduler();

// Start server
server.start().catch((error) => {
  logger.error('Failed to start server:', error);
  process.exit(1);
});

// Graceful shutdown
process.on('SIGTERM', async () => {
  logger.info('SIGTERM received, shutting down gracefully...');
  await server.stop();
  await closeDatabasePool();
  process.exit(0);
});

process.on('SIGINT', async () => {
  logger.info('SIGINT received, shutting down gracefully...');
  await server.stop();
  await closeDatabasePool();
  process.exit(0);
});
