package no.zyon.shade.fingerprint

import no.zyon.shade.crypto.CryptoProvider

/**
 * Safety number computation. Must produce byte-identical output
 * to @shade/core/fingerprint.ts.
 *
 * Format: 12 groups of 5 decimal digits.
 * Derived from: HKDF-SHA256(signingKey||dhKey, salt=32 zeros, info="ShadeFingerprint", 30)
 * then interpret each 2-byte pair as a 16-bit unsigned int mod 10^5.
 *
 * Note: the TS version uses only the first 24 bytes (2 bytes × 12 groups),
 * not all 30. We mirror that here.
 */
fun computeFingerprint(
    crypto: CryptoProvider,
    signingPublicKey: ByteArray,
    dhPublicKey: ByteArray,
): String {
    val combined = ByteArray(signingPublicKey.size + dhPublicKey.size)
    signingPublicKey.copyInto(combined, 0)
    dhPublicKey.copyInto(combined, signingPublicKey.size)

    val salt = ByteArray(32)
    val info = "ShadeFingerprint".toByteArray(Charsets.UTF_8)
    val hash = crypto.hkdf(combined, salt, info, 30)

    val groups = mutableListOf<String>()
    for (i in 0 until 12) {
        val offset = i * 2
        val value = ((hash[offset].toInt() and 0xff) shl 8) or (hash[offset + 1].toInt() and 0xff)
        groups.add(value.toString().padStart(5, '0'))
    }
    return groups.joinToString(" ")
}

fun shortFingerprint(full: String): String {
    return full.split(" ").take(4).joinToString(" ")
}
