const { Pool } = require('pg');
require('dotenv').config({ path: '.env.local' });

const SYSTEM_USER_ID = '00000000-0000-0000-0000-000000000000';

(async () => {
  const pool = new Pool({ connectionString: process.env.LOCAL_DB_URL });
  const client = await pool.connect();
  try {
    const apiKeys = await client.query(`
      SELECT id, user_id, provider, supplier_name, model_name, note, type, created_at
      FROM user_api_keys
      ORDER BY created_at DESC
      LIMIT 200
    `);

    const modelCounts = await client.query(`
      SELECT params->>'model' AS model, COUNT(*)::int AS count
      FROM works
      WHERE is_public = true
        AND status = 'completed'
        AND user_id = $1
      GROUP BY params->>'model'
      ORDER BY count DESC
    `, [SYSTEM_USER_ID]);

    const directMatches = await client.query(`
      SELECT
        w.params->>'model' AS work_model,
        COUNT(*)::int AS work_count,
        k.id AS api_key_id,
        k.user_id,
        p.email,
        p.nickname,
        k.provider,
        k.supplier_name,
        k.model_name,
        k.note
      FROM works w
      JOIN user_api_keys k ON w.params->>'model' = CONCAT('custom:', k.id::text)
      JOIN profiles p ON p.id = k.user_id
      WHERE w.is_public = true
        AND w.status = 'completed'
        AND w.user_id = $1
      GROUP BY w.params->>'model', k.id, k.user_id, p.email, p.nickname, k.provider, k.supplier_name, k.model_name, k.note
      ORDER BY work_count DESC
    `, [SYSTEM_USER_ID]);

    console.log(JSON.stringify({
      userApiKeys: apiKeys.rows,
      anonymousGalleryModelCounts: modelCounts.rows,
      directMatches: directMatches.rows,
    }, null, 2));
  } finally {
    client.release();
    await pool.end();
  }
})().catch((error) => {
  console.error(error);
  process.exit(1);
});
