#!/usr/bin/env node

// Test script to send a Nostr note using nostr-tools
// Usage: node send_test_note.js <nsec> <relay_url> <message>

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

async function sendTestNote(nsecInput, relayUrl, message) {
  try {
    // Parse the private key
    let privateKey;
    if (nsecInput.startsWith('nsec')) {
      const decoded = nip19.decode(nsecInput);
      privateKey = decoded.data;
    } else {
      // Assume hex
      privateKey = Buffer.from(nsecInput, 'hex');
    }

    const publicKey = getPublicKey(privateKey);
    const npub = nip19.npubEncode(publicKey);

    console.log(`Sending note from: ${npub}`);
    console.log(`Hex pubkey: ${publicKey}`);
    console.log(`To relay: ${relayUrl}`);
    console.log(`Message: ${message}`);
    console.log('');
    console.log('💡 To make this an admin post, add this hex pubkey to .env:');
    console.log(`   "${publicKey}"`);
    console.log('');

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

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

    // Connect to relay and publish
    const pool = new SimplePool();
    const relays = [relayUrl];

    console.log('Connecting to relay...');
    await pool.publish(relays, signedEvent);

    console.log('✅ Event published successfully!');
    console.log('Event ID:', signedEvent.id);
    
    // Wait a bit then close
    setTimeout(() => {
      pool.close(relays);
      process.exit(0);
    }, 2000);

  } catch (error) {
    console.error('❌ Failed to send note:', error.message);
    process.exit(1);
  }
}

// Parse command line arguments
const args = process.argv.slice(2);
if (args.length < 3) {
  console.log('Usage: node send_test_note.js <nsec> <relay_url> <message>');
  console.log('Example: node send_test_note.js nsec1abc123... wss://relay.example.com "Hello world!"');
  process.exit(1);
}

const [nsec, relayUrl, message] = args;
sendTestNote(nsec, relayUrl, message);