const path = require('path');
const {
  config,
  createClient,
  ensureDir,
  executeMeasured,
  loadQueries,
  resultsDir,
  summarizeRows,
  writeCsv,
  writeJson
} = require('./benchmark-lib');

const mode = process.env.BENCHMARK_MODE || 'baseline';
const rawName = mode === 'optimized' ? 'optimized_raw.csv' : 'baseline_raw.csv';
const summaryName = mode === 'optimized' ? 'optimized_summary.csv' : 'baseline_summary.csv';
const jsonName = mode === 'optimized' ? 'optimized.json' : 'baseline.json';

const warmups = Number.parseInt(process.env.BENCHMARK_WARMUPS || config.warmupRepetitions, 10);
const repetitions = Number.parseInt(process.env.BENCHMARK_REPETITIONS || config.measuredRepetitions, 10);

const main = async () => {
  ensureDir(resultsDir);
  const queries = loadQueries();
  const client = await createClient();
  const raw = [];

  try {
    for (const query of queries) {
      for (let i = 1; i <= warmups; i += 1) {
        await executeMeasured(client, query, i, `${mode}_warmup`);
      }
      for (let i = 1; i <= repetitions; i += 1) {
        const row = await executeMeasured(client, query, i, mode);
        raw.push(row);
        process.stdout.write(`${mode} ${query.id} ${i}/${repetitions} ${row.success ? 'ok' : 'fail'} ${row.endpoint_total_ms.toFixed(2)}ms\n`);
      }
    }
  } finally {
    await client.end();
  }

  const summary = summarizeRows(raw, ['phase', 'query_id', 'query_name', 'query_group']);
  writeCsv(path.join(resultsDir, rawName), raw);
  writeCsv(path.join(resultsDir, summaryName), summary);
  writeJson(path.join(resultsDir, jsonName), {
    generatedAt: new Date().toISOString(),
    mode,
    warmups,
    repetitions,
    expectedMeasuredOperations: queries.length * repetitions,
    measuredOperations: raw.length,
    summary
  });
};

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
