const os = require('os');
const { createClient, writeJson, resultsDir } = require('./benchmark-lib');
const path = require('path');

const main = async () => {
  const client = await createClient();
  try {
    const version = await client.query('SHOW server_version;');
    const settings = await client.query(`
      SELECT name, setting, unit
      FROM pg_settings
      WHERE name IN ('max_connections', 'shared_buffers', 'work_mem', 'effective_cache_size')
      ORDER BY name;
    `);
    const activity = await client.query(`
      SELECT state, COUNT(*)::int AS total
      FROM pg_stat_activity
      WHERE datname = current_database()
      GROUP BY state
      ORDER BY state;
    `);
    const snapshot = {
      generatedAt: new Date().toISOString(),
      node: process.version,
      platform: `${process.platform} ${process.arch}`,
      osRelease: os.release(),
      cpuCount: os.cpus().length,
      totalMemoryMb: Math.round(os.totalmem() / 1024 / 1024),
      freeMemoryMb: Math.round(os.freemem() / 1024 / 1024),
      postgresVersion: version.rows[0]?.server_version,
      postgresSettings: settings.rows,
      postgresActivity: activity.rows
    };
    writeJson(path.join(resultsDir, 'resource_snapshot.json'), snapshot);
    console.log(JSON.stringify(snapshot, null, 2));
  } finally {
    await client.end();
  }
};

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