import { bytesToHex, hexToBytes, randomBytes } from '@noble/hashes/utils'
import { secp256k1 } from '@noble/curves/secp256k1'
import { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf'
import { hmac } from '@noble/hashes/hmac'
import { sha256 } from '@noble/hashes/sha256'
import { concatBytes } from '@noble/hashes/utils'
import { base64 } from '@scure/base'
import { chacha20 } from '@noble/ciphers/chacha'
import { equalBytes } from '@noble/ciphers/utils'

// UTF-8 encoder/decoder
const utf8Encoder = new TextEncoder()
const utf8Decoder = new TextDecoder()

const minPlaintextSize = 0x0001 // 1b msg => padded to 32b
const maxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb

function getConversationKey(privkeyA, pubkeyB) {
  console.log(`[JS] Computing conversation key`)
  console.log(`[JS] Private Key A: ${privkeyA}`)
  console.log(`[JS] Public Key B:  ${pubkeyB}`)
  
  const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33)
  console.log(`[JS] Shared Secret: ${bytesToHex(sharedX)}`)
  
  const conversationKey = hkdf_extract(sha256, sharedX, 'nip44-v2')
  console.log(`[JS] Conversation Key: ${bytesToHex(conversationKey)}`)
  
  return conversationKey
}

function getMessageKeys(conversationKey, nonce) {
  console.log(`[JS] Deriving message keys`)
  console.log(`[JS] Conversation Key: ${bytesToHex(conversationKey)}`)
  console.log(`[JS] Nonce: ${bytesToHex(nonce)}`)
  
  const keys = hkdf_expand(sha256, conversationKey, nonce, 76)
  const result = {
    chacha_key: keys.subarray(0, 32),
    chacha_nonce: keys.subarray(32, 44),
    hmac_key: keys.subarray(44, 76),
  }
  
  console.log(`[JS] ChaCha20 Key: ${bytesToHex(result.chacha_key)}`)
  console.log(`[JS] ChaCha20 Nonce: ${bytesToHex(result.chacha_nonce)}`)
  console.log(`[JS] HMAC Key: ${bytesToHex(result.hmac_key)}`)
  
  return result
}

function calcPaddedLen(len) {
  if (!Number.isSafeInteger(len) || len < 1) throw new Error('expected positive integer')
  if (len <= 32) return 32
  const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1)
  const chunk = nextPower <= 256 ? 32 : nextPower / 8
  return chunk * (Math.floor((len - 1) / chunk) + 1)
}

function writeU16BE(num) {
  if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize)
    throw new Error('invalid plaintext size: must be between 1 and 65535 bytes')
  const arr = new Uint8Array(2)
  new DataView(arr.buffer).setUint16(0, num, false)
  return arr
}

function pad(plaintext) {
  console.log(`[JS] Padding plaintext: "${plaintext}"`)
  const unpadded = utf8Encoder.encode(plaintext)
  const unpaddedLen = unpadded.length
  console.log(`[JS] Unpadded length: ${unpaddedLen}`)
  console.log(`[JS] Unpadded bytes: ${bytesToHex(unpadded)}`)
  
  const prefix = writeU16BE(unpaddedLen)
  console.log(`[JS] Length prefix: ${bytesToHex(prefix)}`)
  
  const paddedLen = calcPaddedLen(unpaddedLen)
  console.log(`[JS] Calculated padded length: ${paddedLen}`)
  
  const suffix = new Uint8Array(paddedLen - unpaddedLen)
  console.log(`[JS] Padding suffix length: ${suffix.length}`)
  
  const result = concatBytes(prefix, unpadded, suffix)
  console.log(`[JS] Final padded: ${bytesToHex(result)}`)
  
  return result
}

function unpad(padded) {
  console.log(`[JS] Unpadding data: ${bytesToHex(padded)}`)
  const unpaddedLen = new DataView(padded.buffer).getUint16(0)
  console.log(`[JS] Read length from prefix: ${unpaddedLen}`)
  
  const unpadded = padded.subarray(2, 2 + unpaddedLen)
  console.log(`[JS] Extracted unpadded: ${bytesToHex(unpadded)}`)
  
  if (
    unpaddedLen < minPlaintextSize ||
    unpaddedLen > maxPlaintextSize ||
    unpadded.length !== unpaddedLen ||
    padded.length !== 2 + calcPaddedLen(unpaddedLen)
  ) {
    console.log(`[JS] Padding validation failed:`)
    console.log(`[JS]   unpaddedLen: ${unpaddedLen} (should be ${minPlaintextSize}-${maxPlaintextSize})`)
    console.log(`[JS]   unpadded.length: ${unpadded.length}`)
    console.log(`[JS]   padded.length: ${padded.length}`)
    console.log(`[JS]   expected padded length: ${2 + calcPaddedLen(unpaddedLen)}`)
    throw new Error('invalid padding')
  }
  
  const result = utf8Decoder.decode(unpadded)
  console.log(`[JS] Decoded plaintext: "${result}"`)
  return result
}

function hmacAad(key, message, aad) {
  if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes')
  console.log(`[JS] Computing HMAC`)
  console.log(`[JS] HMAC Key: ${bytesToHex(key)}`)
  console.log(`[JS] AAD: ${bytesToHex(aad)}`)
  console.log(`[JS] Message: ${bytesToHex(message)}`)
  
  const combined = concatBytes(aad, message)
  console.log(`[JS] Combined AAD+Message: ${bytesToHex(combined)}`)
  
  const result = hmac(sha256, key, combined)
  console.log(`[JS] HMAC Result: ${bytesToHex(result)}`)
  
  return result
}

function decodePayload(payload) {
  console.log(`[JS] Decoding payload: ${payload}`)
  if (typeof payload !== 'string') throw new Error('payload must be a valid string')
  const plen = payload.length
  if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen)
  if (payload[0] === '#') throw new Error('unknown encryption version')
  
  let data
  try {
    data = base64.decode(payload)
  } catch (error) {
    throw new Error('invalid base64: ' + error.message)
  }
  
  console.log(`[JS] Base64 decoded data: ${bytesToHex(data)}`)
  const dlen = data.length
  if (dlen < 99 || dlen > 65603) throw new Error('invalid data length: ' + dlen)
  const vers = data[0]
  if (vers !== 2) throw new Error('unknown encryption version ' + vers)
  
  const result = {
    nonce: data.subarray(1, 33),
    ciphertext: data.subarray(33, -32),
    mac: data.subarray(-32),
  }
  
  console.log(`[JS] Version: ${vers}`)
  console.log(`[JS] Nonce: ${bytesToHex(result.nonce)}`)
  console.log(`[JS] Ciphertext: ${bytesToHex(result.ciphertext)}`)
  console.log(`[JS] MAC: ${bytesToHex(result.mac)}`)
  
  return result
}

function encrypt(plaintext, conversationKey, nonce = randomBytes(32)) {
  console.log(`[JS] ===== ENCRYPTING "${plaintext}" =====`)
  const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)
  const padded = pad(plaintext)
  
  console.log(`[JS] Encrypting with ChaCha20`)
  const ciphertext = chacha20(chacha_key, chacha_nonce, padded)
  console.log(`[JS] ChaCha20 ciphertext: ${bytesToHex(ciphertext)}`)
  
  const mac = hmacAad(hmac_key, ciphertext, nonce)
  
  console.log(`[JS] Building final payload`)
  const payload = concatBytes(new Uint8Array([2]), nonce, ciphertext, mac)
  console.log(`[JS] Raw payload: ${bytesToHex(payload)}`)
  
  const result = base64.encode(payload)
  console.log(`[JS] Base64 encoded result: ${result}`)
  
  return result
}

function decrypt(payload, conversationKey) {
  console.log(`[JS] ===== DECRYPTING "${payload}" =====`)
  const { nonce, ciphertext, mac } = decodePayload(payload)
  const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)
  
  const calculatedMac = hmacAad(hmac_key, ciphertext, nonce)
  console.log(`[JS] MAC verification`)
  console.log(`[JS] Received MAC: ${bytesToHex(mac)}`)
  console.log(`[JS] Calculated MAC: ${bytesToHex(calculatedMac)}`)
  
  if (!equalBytes(calculatedMac, mac)) {
    console.log(`[JS] MAC MISMATCH!`)
    throw new Error('invalid MAC')
  }
  console.log(`[JS] MAC verification PASSED`)
  
  console.log(`[JS] Decrypting with ChaCha20`)
  const padded = chacha20(chacha_key, chacha_nonce, ciphertext)
  console.log(`[JS] ChaCha20 decrypted: ${bytesToHex(padded)}`)
  
  const result = unpad(padded)
  console.log(`[JS] Final decrypted plaintext: "${result}"`)
  
  return result
}

// Test with exact vectors that are failing in C
async function main() {
  console.log("=== NIP-44 DEBUG COMPARISON (JavaScript) ===")
  
  // Test vector 1: single char 'a' - MATCHES nostr-tools official vector
  const test1 = {
    sec1: "0000000000000000000000000000000000000000000000000000000000000001",
    sec2: "0000000000000000000000000000000000000000000000000000000000000002", 
    plaintext: "a",
    expectedPayload: "AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABee0G5VSK0/9YypIObAtDKfYEAjD35uVkHyB0F4DwrcNaCXlCWZKaArsGrY6M9wnuTMxWfp1RTN9Xga8no+kF5Vsb"
  }
  
  console.log("\n=== TEST 1: Single char 'a' ===")
  
  // Step 1: Get conversation key using sender's private key + recipient's public key
  const sec1Bytes = hexToBytes(test1.sec1)
  const sec2Bytes = hexToBytes(test1.sec2)
  const pub2 = bytesToHex(secp256k1.getPublicKey(sec2Bytes, false).subarray(1, 33)) // x-only
  console.log(`[JS] Derived pub2 from sec2: ${pub2}`)
  
  const conversationKey1 = getConversationKey(test1.sec1, pub2)
  
  // Step 2: Try to decrypt the expected payload (this should work if our C code matches)
  console.log("\n--- DECRYPTION TEST ---")
  try {
    const decrypted1 = decrypt(test1.expectedPayload, conversationKey1)
    console.log(`✅ Decryption SUCCESS: "${decrypted1}"`)
    console.log(`✅ Match: ${decrypted1 === test1.plaintext}`)
  } catch (error) {
    console.log(`❌ Decryption FAILED: ${error.message}`)
  }
  
  // Step 3: Generate fresh encryption to compare format
  console.log("\n--- ENCRYPTION TEST (with random nonce) ---")
  const encrypted1 = encrypt(test1.plaintext, conversationKey1)
  console.log(`Generated payload: ${encrypted1}`)
  
  // Step 4: Decrypt our own encryption (round-trip test)
  console.log("\n--- ROUND-TRIP TEST ---")
  try {
    const roundTrip1 = decrypt(encrypted1, conversationKey1)
    console.log(`✅ Round-trip SUCCESS: "${roundTrip1}"`)
    console.log(`✅ Match: ${roundTrip1 === test1.plaintext}`)
  } catch (error) {
    console.log(`❌ Round-trip FAILED: ${error.message}`)
  }

  // Test the other failing vectors too
  console.log("\n=== TEST 2: Emoji ===")
  const test2 = {
    sec1: "0000000000000000000000000000000000000000000000000000000000000002",
    sec2: "0000000000000000000000000000000000000000000000000000000000000001",
    plaintext: "🍕🫃",
    expectedPayload: "AvAAAAAAAAAAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAPSKSK6is9ngkX2+cSq85Th16oRTISAOfhStnixqZziKMDvB0QQzgFZdjLTPicCJaV8nDITO+QfaQ61+KbWQIOO2Yj"
  }
  
  const pub1 = bytesToHex(secp256k1.getPublicKey(hexToBytes(test2.sec2), false).subarray(1, 33))
  const conversationKey2 = getConversationKey(test2.sec1, pub1)
  
  try {
    const decrypted2 = decrypt(test2.expectedPayload, conversationKey2)
    console.log(`✅ Test 2 SUCCESS: "${decrypted2}"`)
  } catch (error) {
    console.log(`❌ Test 2 FAILED: ${error.message}`)
  }
}

main().catch(console.error)
