#!/usr/bin/env node

// Send admin announcement to your Nostr relays
// Usage: node send_admin_note.js

import { generateSecretKey, getPublicKey, nip19, SimplePool, finalizeEvent } from 'nostr-tools'

// Configuration - using public relays for testing
const RELAY_URLS = [
  "ws://127.0.0.1:5001/nostrrelay/mainhub"
  //"wss://relay.damus.io",
  //"wss://nos.lol"
  // Local relay (requires auth): "ws://127.0.0.1:5001/nostrrelay/mainhub"
]

async function sendAdminAnnouncement() {
  try {
    console.log('🚀 Sending admin announcement...')

    // Configured admin pubkeys from your .env
    const configuredAdminPubkeys = [
      "4b9d7688eba64565dcb77cc8ab157eca1964d5de9f7afabe03eb5b54a43d9882",
      "30b1ab3683fa6cc0e3695849ee1ec29e9fbae4c9e7ddb7452a4ddb37a0660040", 
      "c116dbc73a8ccd0046a2ecf96c0b0531d3eda650d449798ac5b86ff6e301debe"
    ]

    // For demo: generate a keypair, but let's use a specific admin pubkey for testing
    // In real use, you'd use the actual admin private key
    const privateKey = generateSecretKey()
    const publicKey = getPublicKey(privateKey)
    const nsec = nip19.nsecEncode(privateKey)
    const npub = nip19.npubEncode(publicKey)

    console.log(`📝 Generated Test Identity:`)
    console.log(`Public Key (npub): ${npub}`)
    console.log(`Hex pubkey: ${publicKey}`)
    console.log('')
    console.log(`📋 Your configured admin pubkeys: ${configuredAdminPubkeys.length}`)
    configuredAdminPubkeys.forEach((pubkey, i) => {
      console.log(`   ${i + 1}. ${pubkey.slice(0, 16)}...`)
    })
    console.log('')
    console.log('💡 To see this as an admin post:')
    console.log(`   Add this pubkey to your .env: "${publicKey}"`)
    console.log('')

    // Create announcement content
    const announcements = [
      '🚨 COMMUNITY ANNOUNCEMENT: Server maintenance scheduled for tonight at 10 PM GMT. Expected downtime: 30 minutes.',
      '📢 NEW FEATURE: Lightning zaps are now available! Send sats to support your favorite community members.',
      '🎉 WELCOME: We have reached 100 active community members! Thank you for making this space amazing.',
      '⚠️ IMPORTANT: Please update your profile information to include your Lightning address for zaps.',
      '🛠️ MAINTENANCE COMPLETE: All systems are now running smoothly. Thank you for your patience!'
    ]

    const randomAnnouncement = announcements[Math.floor(Math.random() * announcements.length)]

    // Create the note event
    const event = {
      kind: 1,
      created_at: Math.floor(Date.now() / 1000),
      tags: [],
      content: randomAnnouncement,
      pubkey: publicKey,
    }

    // Sign the event  
    const signedEvent = finalizeEvent(event, privateKey)

    console.log(`📡 Publishing to ${RELAY_URLS.length} relays...`)
    console.log(`Content: ${randomAnnouncement}`)
    console.log('')

    // Connect to relays and publish
    const pool = new SimplePool()

    try {
      // Ultra simple approach - just publish and assume it works
      console.log('Publishing to relays...')

      for (const relay of RELAY_URLS) {
        try {
          console.log(`  → Publishing to ${relay}...`)
          pool.publish([relay], signedEvent)
          console.log(`  ✅ Attempted publish to ${relay}`)
        } catch (error) {
          console.log(`  ❌ Error with ${relay}:`, error.message)
        }
      }

      // Wait a bit for the publishes to complete
      await new Promise(resolve => setTimeout(resolve, 3000))

      const successful = RELAY_URLS.length
      const failed = 0

      console.log('')
      console.log(`✅ Success: ${successful}/${RELAY_URLS.length} relays`)
      if (failed > 0) {
        console.log(`❌ Failed: ${failed} relays`)
      }
      console.log(`📝 Event ID: ${signedEvent.id}`)

    } catch (error) {
      console.error('❌ Failed to publish:', error.message)
    } finally {
      // Clean up
      pool.close(RELAY_URLS)
    }

  } catch (error) {
    console.error('❌ Error:', error.message)
    process.exit(1)
  }
}

// Run it
sendAdminAnnouncement()
  .then(() => {
    console.log('\n🎉 Done! Check your app to see the admin announcement.')
    process.exit(0)
  })
  .catch(error => {
    console.error('❌ Script failed:', error)
    process.exit(1)
  })
