const { performance } = require('perf_hooks');
const {
  config,
  createClient,
  ensureDir,
  explainSql,
  explainSummary,
  query02Dir,
  query02Sql,
  summarizeRows,
  writeCsv,
  writeJson
} = require('./query02-lib');

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

const runOne = async (client, repetition, measured) => {
  const timestamp = new Date().toISOString();
  const started = performance.now();
  const result = await client.query(explainSql(query02Sql));
  const total = performance.now() - started;
  const summary = explainSummary(result.rows[0]['QUERY PLAN'][0]);
  return {
    phase: 'query02_optimized',
    query_id: 'query_02',
    query_name: 'Catalogo general paginado LIMIT 25',
    query_group: 'estructurada',
    repetition,
    measured,
    timestamp,
    endpoint_total_ms: total,
    sql_ms: summary.execution_ms,
    planning_ms: summary.planning_ms,
    execution_ms: summary.execution_ms,
    rows_returned: summary.actual_rows,
    estimated_rows: summary.estimated_rows,
    actual_rows: summary.actual_rows,
    shared_hit_blocks: summary.shared_hit_blocks,
    shared_read_blocks: summary.shared_read_blocks,
    temp_read_blocks: summary.temp_read_blocks,
    temp_written_blocks: summary.temp_written_blocks,
    active_pg_connections: 1,
    cpu_percent_process: 0,
    memory_rss_mb: process.memoryUsage().rss / 1024 / 1024,
    disk_fs_read_ops: 0,
    disk_fs_write_ops: 0,
    success: true,
    error_message: ''
  };
};

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

  try {
    for (let i = 1; i <= warmups; i += 1) {
      await runOne(client, i, false);
      process.stdout.write(`query02 warmup ${i}/${warmups}\n`);
    }
    for (let i = 1; i <= repetitions; i += 1) {
      const row = await runOne(client, i, true);
      raw.push(row);
      process.stdout.write(`query02 optimized ${i}/${repetitions} ${row.endpoint_total_ms.toFixed(2)}ms\n`);
    }
  } finally {
    await client.end();
  }

  const summary = summarizeRows(raw, ['phase', 'query_id', 'query_name', 'query_group']);
  writeCsv(`${query02Dir}/optimized_raw.csv`, raw);
  writeCsv(`${query02Dir}/optimized_summary.csv`, summary);
  writeJson(`${query02Dir}/optimized.json`, {
    generatedAt: new Date().toISOString(),
    warmups,
    repetitions,
    summary
  });
};

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