/*
 * Single Test Vector to Debug Segfault
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../nostr_core/nostr_core.h"

void hex_to_bytes(const char* hex_str, unsigned char* bytes) {
    size_t len = strlen(hex_str);
    for (size_t i = 0; i < len; i += 2) {
        sscanf(hex_str + i, "%2hhx", &bytes[i / 2]);
    }
}

int main(void) {
    printf("=== Single Test Vector Debug ===\n");
    
    // Initialize the library
    printf("Initializing library...\n");
    if (nostr_init() != NOSTR_SUCCESS) {
        printf("ERROR: Failed to initialize NOSTR library\n");
        return 1;
    }
    printf("✅ Library initialized\n");
    
    // Test Vector 1 data
    const char* sk1_hex = "91ba716fa9e7ea2fcbad360cf4f8e0d312f73984da63d90f524ad61a6a1e7dbe";
    const char* sk2_hex = "96f6fa197aa07477ab88f6981118466ae3a982faab8ad5db9d5426870c73d220";
    const char* pk1_hex = "b38ce15d3d9874ee710dfabb7ff9801b1e0e20aace6e9a1a05fa7482a04387d1";
    const char* pk2_hex = "dcb33a629560280a0ee3b6b99b68c044fe8914ad8a984001ebf6099a9b474dc3";
    const char* plaintext = "nanana";
    
    printf("Converting hex keys...\n");
    unsigned char sk1[32], sk2[32], pk1[32], pk2[32];
    hex_to_bytes(sk1_hex, sk1);
    hex_to_bytes(sk2_hex, sk2);
    hex_to_bytes(pk1_hex, pk1);
    hex_to_bytes(pk2_hex, pk2);
    printf("✅ Keys converted\n");
    
    printf("Testing encryption...\n");
    char encrypted[NOSTR_NIP04_MAX_ENCRYPTED_SIZE];
    int result = nostr_nip04_encrypt(sk1, pk2, plaintext, encrypted, sizeof(encrypted));
    
    if (result != NOSTR_SUCCESS) {
        printf("❌ ENCRYPTION FAILED: %s\n", nostr_strerror(result));
        nostr_cleanup();
        return 1;
    }
    printf("✅ Encryption successful: %s\n", encrypted);
    
    printf("Testing decryption...\n");
    char decrypted[NOSTR_NIP04_MAX_PLAINTEXT_SIZE];
    result = nostr_nip04_decrypt(sk2, pk1, encrypted, decrypted, sizeof(decrypted));
    
    if (result != NOSTR_SUCCESS) {
        printf("❌ DECRYPTION FAILED: %s\n", nostr_strerror(result));
        nostr_cleanup();
        return 1;
    }
    printf("✅ Decryption successful: \"%s\"\n", decrypted);
    
    if (strcmp(plaintext, decrypted) == 0) {
        printf("✅ TEST PASSED - Round-trip successful!\n");
    } else {
        printf("❌ TEST FAILED - Messages don't match\n");
        nostr_cleanup();
        return 1;
    }
    
    printf("Cleaning up...\n");
    nostr_cleanup();
    printf("✅ Test completed successfully!\n");
    
    return 0;
}
