const fs = require('fs');
const path = require('path');
const { benchmarkDir, createClient, ensureDir, loadQueries, resultsDir, writeJson } = require('./benchmark-lib');

const phase = process.argv[2] === 'after' ? 'after' : 'before';
const outDir = path.join(resultsDir, phase === 'after' ? 'explain_after' : 'explain_before');

const explainSql = (sql) => `EXPLAIN (ANALYZE, BUFFERS, VERBOSE, SETTINGS, FORMAT JSON) ${sql.replace(/;\s*$/, '')}`;

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

  try {
    for (const query of queries) {
      const startedAt = new Date().toISOString();
      const file = path.join(outDir, `${query.id}.json`);
      try {
        const result = await client.query(explainSql(query.sql));
        writeJson(file, {
          phase,
          generatedAt: startedAt,
          queryId: query.id,
          queryName: query.name,
          sqlFile: query.sqlFile,
          explain: result.rows[0]?.['QUERY PLAN']?.[0] || null
        });
        manifest.push({ queryId: query.id, success: true, file: path.relative(benchmarkDir, file) });
        console.log(`${phase} ${query.id} explain ok`);
      } catch (error) {
        const errorFile = path.join(outDir, `${query.id}.error.json`);
        writeJson(errorFile, {
          phase,
          generatedAt: startedAt,
          queryId: query.id,
          queryName: query.name,
          sqlFile: query.sqlFile,
          error: String(error?.message || error)
        });
        manifest.push({ queryId: query.id, success: false, file: path.relative(benchmarkDir, errorFile) });
        console.log(`${phase} ${query.id} explain fail`);
      }
    }
  } finally {
    await client.end();
  }

  writeJson(path.join(outDir, 'manifest.json'), {
    phase,
    generatedAt: new Date().toISOString(),
    items: manifest
  });
};

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