import path from 'path';
import { existsSync } from 'fs';
import * as dotenv from 'dotenv';
import { AggregatorRouteMatrixGenerator } from '../src/services/aggregator-route-matrix-generator';
import { closeDatabasePool } from '../src/database/client';

const rootEnvCandidates = [
  path.resolve(__dirname, '../../.env'),
  path.resolve(__dirname, '../../../.env'),
];

for (const candidate of rootEnvCandidates) {
  if (existsSync(candidate)) {
    dotenv.config({ path: candidate });
    break;
  }
}
dotenv.config();

async function main() {
  const outputPath = process.argv[2]
    ? path.resolve(process.cwd(), process.argv[2])
    : path.resolve(__dirname, '../../../../config/aggregator-route-matrix.json');

  const generator = new AggregatorRouteMatrixGenerator();
  try {
    const writtenPath = await generator.writeToFile(outputPath, 138);
    process.stdout.write(`${writtenPath}\n`);
  } finally {
    await closeDatabasePool();
  }
}

main()
  .then(() => {
    process.exit(0);
  })
  .catch((error) => {
    process.stderr.write(`${error instanceof Error ? error.stack || error.message : String(error)}\n`);
    process.exit(1);
  });
