import fs from 'node:fs';
import mysql from 'mysql2/promise';
const cfg = JSON.parse(fs.readFileSync('sites.config.json', 'utf8'));
const want = process.argv[2]; // optionally: node schema-dump.mjs <site-id>
const site = (want && cfg.sites.find((s) => s.id === want))
  || cfg.sites.find((s) => s.db?.host && /hyundai/i.test(s.name))
  || cfg.sites.find((s) => s.db?.host);
console.log('Using site:', site.name, '→ database', site.db.database);
const conn = await mysql.createConnection({
  host: site.db.host, port: site.db.port || 3306,
  user: site.db.user, password: site.db.password, database: site.db.database,
  ssl: { rejectUnauthorized: false },
});
let out = 'SITE: ' + site.name + ' · DB: ' + site.db.database + '\n\n';
const [rowsInfo] = await conn.query(
  'SELECT TABLE_NAME AS t, TABLE_ROWS AS n FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() ORDER BY TABLE_ROWS DESC');
out += 'TABLES (' + rowsInfo.length + ') with approx rows:\n'
  + rowsInfo.map((r) => '  ' + r.t + '  ~' + r.n).join('\n') + '\n\n';
for (const r of rowsInfo) {
  try {
    const [cols] = await conn.query('DESCRIBE `' + r.t + '`');
    out += '== ' + r.t + '\n' + cols.map((c) => '  ' + c.Field + '  ' + c.Type + (c.Key ? '  [' + c.Key + ']' : '')).join('\n') + '\n\n';
  } catch (e) { out += '== ' + r.t + '  ERROR: ' + e.message + '\n\n'; }
}
if (rowsInfo.some((r) => r.t === 'detail_release_statistics')) {
  const [acts] = await conn.query(
    'SELECT action, COUNT(*) AS events, MIN(created_at) AS first, MAX(created_at) AS last FROM detail_release_statistics GROUP BY action');
  out += 'ACTION CODES in detail_release_statistics:\n' + JSON.stringify(acts, null, 1) + '\n';
}
fs.writeFileSync('db-structure.txt', out);
console.log('Wrote db-structure.txt — attach this file to the chat.');
await conn.end();
