import * as dotenv from 'dotenv';
import path from 'path';
import { existsSync } from 'fs';
import { HistoricalPricingBackfillService } from './services/historical-pricing-backfill';

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();

function readInt(name: string, fallback: number): number {
  const raw = String(process.env[name] || '').trim();
  if (!raw) return fallback;
  const parsed = Number(raw);
  return Number.isFinite(parsed) ? parsed : fallback;
}

async function main(): Promise<void> {
  const chainId = readInt('BACKFILL_CHAIN_ID', 138);
  const days = readInt('BACKFILL_DAYS', 30);
  const chunkSize = readInt('BACKFILL_CHUNK_SIZE', 2500);
  const poolLimit = readInt('BACKFILL_POOL_LIMIT', 500);

  const service = new HistoricalPricingBackfillService();
  const summary = await service.backfillChain({
    chainId,
    days,
    chunkSize,
    poolLimit,
  });

  // eslint-disable-next-line no-console
  console.log(JSON.stringify(summary, null, 2));
}

main().catch((error) => {
  // eslint-disable-next-line no-console
  console.error(error);
  process.exit(1);
});
