const { generateSecretKey, getPublicKey, nip04 } = require('nostr-tools');
const { bytesToHex } = require('@noble/hashes/utils');

function generateTestVector(testName, plaintext) {
    // Generate random keys
    const sk1 = generateSecretKey();
    const pk1 = getPublicKey(sk1);
    const sk2 = generateSecretKey();
    const pk2 = getPublicKey(sk2);
    
    // Encrypt from Alice (sk1) to Bob (pk2)
    const encrypted = nip04.encrypt(sk1, pk2, plaintext);
    
    // Verify decryption works (Bob using sk2 to decrypt from Alice pk1)
    const decrypted = nip04.decrypt(sk2, pk1, encrypted);
    
    if (decrypted !== plaintext) {
        throw new Error(`Decryption failed for ${testName}`);
    }
    
    return {
        testName,
        sk1: bytesToHex(sk1),
        pk1: pk1,
        sk2: bytesToHex(sk2),
        pk2: pk2,
        plaintext: plaintext,
        encrypted: encrypted
    };
}

console.log('=== NIP-04 Test Vector Generation ===\n');

// Generate 3 test vectors with different plaintexts
const testVectors = [
    generateTestVector('TEST_VECTOR_2', 'Hello, NOSTR!'),
    generateTestVector('TEST_VECTOR_3', 'This is a longer message to test encryption with more content. 🚀'),
    generateTestVector('TEST_VECTOR_4', 'Short')
];

// Output in C format for easy integration
testVectors.forEach((vector, index) => {
    console.log(`=== ${vector.testName}: ${vector.plaintext.replace(/\n/g, '\\n')} ===`);
    console.log(`SK1 (Alice): ${vector.sk1}`);
    console.log(`PK1 (Alice): ${vector.pk1}`);
    console.log(`SK2 (Bob):   ${vector.sk2}`);
    console.log(`PK2 (Bob):   ${vector.pk2}`);
    console.log(`Plaintext:   "${vector.plaintext}"`);
    console.log(`Expected:    ${vector.encrypted}`);
    console.log('');
});

// Also output as C code that can be copied directly
console.log('=== C CODE FOR INTEGRATION ===\n');

testVectors.forEach((vector, index) => {
    const testNum = index + 2; // Start from 2 since we already have TEST_VECTOR_1
    console.log(`    // ${vector.testName}: ${vector.plaintext.replace(/"/g, '\\"')}`);
    console.log(`    {`);
    console.log(`        "${vector.sk1}",`);
    console.log(`        "${vector.pk1}",`);
    console.log(`        "${vector.sk2}",`);
    console.log(`        "${vector.pk2}",`);
    console.log(`        "${vector.plaintext.replace(/"/g, '\\"')}",`);
    console.log(`        "${vector.encrypted}"`);
    console.log(`    }${index < testVectors.length - 1 ? ',' : ''}`);
});

console.log('\n=== Generation Complete ===');
