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 byModelOwner = await client.query(`
      SELECT
        COALESCE(w.params->>'model', '') AS model,
        COALESCE(p.email, '[missing-profile]') AS email,
        COALESCE(p.nickname, '') AS nickname,
        w.user_id,
        COUNT(*)::int AS count,
        COUNT(*) FILTER (WHERE w.is_public = true)::int AS public_count,
        COUNT(*) FILTER (WHERE w.is_public = false)::int AS private_count,
        MIN(w.created_at) AS first_at,
        MAX(w.created_at) AS last_at
      FROM works w
      LEFT JOIN profiles p ON p.id = w.user_id
      WHERE w.status = 'completed'
      GROUP BY model, w.user_id, p.email, p.nickname
      ORDER BY model, count DESC
    `);

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

    const ownersByPrompt = await client.query(`
      WITH orphan AS (
        SELECT id, prompt, created_at
        FROM works
        WHERE status = 'completed'
          AND is_public = true
          AND user_id = $1
          AND COALESCE(prompt, '') <> ''
      ),
      owned AS (
        SELECT w.id, w.user_id, p.email, p.nickname, w.prompt, w.created_at
        FROM works w
        JOIN profiles p ON p.id = w.user_id
        WHERE w.status = 'completed'
          AND w.user_id <> $1
          AND COALESCE(w.prompt, '') <> ''
      )
      SELECT
        orphan.id AS orphan_id,
        owned.user_id,
        owned.email,
        owned.nickname,
        COUNT(*)::int AS matches,
        MIN(ABS(EXTRACT(EPOCH FROM (owned.created_at - orphan.created_at))))::int AS best_seconds_apart
      FROM orphan
      JOIN owned ON owned.prompt = orphan.prompt
      GROUP BY orphan.id, owned.user_id, owned.email, owned.nickname
      ORDER BY matches DESC, best_seconds_apart
      LIMIT 120
    `, [SYSTEM_USER_ID]);

    const maybeAdminByDates = await client.query(`
      SELECT
        w.id,
        w.created_at,
        w.params->>'model' AS model,
        LEFT(w.prompt, 100) AS prompt,
        (
          SELECT json_agg(json_build_object(
            'user_id', nearby.user_id,
            'email', p.email,
            'nickname', p.nickname,
            'seconds_apart', ABS(EXTRACT(EPOCH FROM (nearby.created_at - w.created_at)))::int,
            'prompt', LEFT(nearby.prompt, 80)
          ) ORDER BY ABS(EXTRACT(EPOCH FROM (nearby.created_at - w.created_at))))
          FROM works nearby
          JOIN profiles p ON p.id = nearby.user_id
          WHERE nearby.user_id <> $1
            AND nearby.status = 'completed'
            AND nearby.created_at BETWEEN w.created_at - INTERVAL '1 hour' AND w.created_at + INTERVAL '1 hour'
          LIMIT 8
        ) AS nearby_owned
      FROM works w
      WHERE w.status = 'completed'
        AND w.is_public = true
        AND w.user_id = $1
      ORDER BY w.created_at DESC
      LIMIT 80
    `, [SYSTEM_USER_ID]);

    console.log(JSON.stringify({
      orphanModelTotals: orphanModelTotals.rows,
      byModelOwner: byModelOwner.rows,
      ownersByPrompt: ownersByPrompt.rows,
      nearbyOwnedByTime: maybeAdminByDates.rows,
    }, null, 2));
  } finally {
    client.release();
    await pool.end();
  }
})().catch(error => {
  console.error(error);
  process.exit(1);
});
