#!/usr/bin/env node

// Debug what admin posts exist in the relay
import { SimplePool } from 'nostr-tools'

const RELAY_URL = "ws://127.0.0.1:5001/nostrrelay/mainhub"
const ADMIN_PUBKEYS = [
  "4b9d7688eba64565dcb77cc8ab157eca1964d5de9f7afabe03eb5b54a43d9882",
  "30b1ab3683fa6cc0e3695849ee1ec29e9fbae4c9e7ddb7452a4ddb37a0660040", 
  "c116dbc73a8ccd0046a2ecf96c0b0531d3eda650d449798ac5b86ff6e301debe"
]

async function debugAdminPosts() {
  const pool = new SimplePool()
  
  console.log('🔍 Checking relay for admin posts...')
  console.log('Relay:', RELAY_URL)
  console.log('Admin pubkeys:', ADMIN_PUBKEYS.length)
  console.log('')
  
  try {
    // Check each admin individually
    for (let i = 0; i < ADMIN_PUBKEYS.length; i++) {
      const pubkey = ADMIN_PUBKEYS[i]
      console.log(`👤 Admin ${i + 1}: ${pubkey.slice(0, 16)}...`)
      
      const individualFilter = {
        kinds: [1],
        authors: [pubkey],
        limit: 10
      }
      
      const events = []
      const sub = pool.subscribeMany([RELAY_URL], [individualFilter], {
        onevent(event) {
          events.push(event)
        },
        oneose() {
          console.log(`   Found ${events.length} posts`)
          events.forEach((event, idx) => {
            console.log(`   ${idx + 1}. "${event.content.slice(0, 60)}${event.content.length > 60 ? '...' : ''}"`)
            console.log(`      Created: ${new Date(event.created_at * 1000).toLocaleString()}`)
          })
          console.log('')
        }
      })
      
      // Wait for events
      await new Promise(resolve => setTimeout(resolve, 1000))
      sub.close()
    }
    
    // Now test the combined filter (what the app uses)
    console.log('🔄 Testing combined filter (what the app uses)...')
    const combinedFilter = {
      kinds: [1],
      authors: ADMIN_PUBKEYS,
      limit: 50
    }
    
    const allEvents = []
    const combinedSub = pool.subscribeMany([RELAY_URL], [combinedFilter], {
      onevent(event) {
        allEvents.push(event)
      },
      oneose() {
        console.log(`📊 Combined filter result: ${allEvents.length} total posts`)
        
        // Group by author
        const byAuthor = {}
        allEvents.forEach(event => {
          const shortPubkey = event.pubkey.slice(0, 16) + '...'
          if (!byAuthor[shortPubkey]) byAuthor[shortPubkey] = 0
          byAuthor[shortPubkey]++
        })
        
        console.log('Posts by author:')
        Object.entries(byAuthor).forEach(([author, count]) => {
          console.log(`  ${author}: ${count} posts`)
        })
      }
    })
    
    await new Promise(resolve => setTimeout(resolve, 1000))
    combinedSub.close()
    
  } catch (error) {
    console.error('❌ Error:', error)
  } finally {
    pool.close([RELAY_URL])
  }
}

debugAdminPosts()