/* randombytes_mbedtls.c — randombytes() implementation for ESP32 firmware.
 *
 * PQClean's algorithm code calls randombytes() for:
 *   1. Key generation (keygen) — must be deterministic from the mnemonic
 *      seed so keys are recoverable. The DRBG is initialized via
 *      pq_drbg_init() before keygen, so randombytes() draws from the
 *      deterministic stream.
 *   2. Encapsulation (ML-KEM enc) — needs real cryptographic randomness.
 *      When the DRBG is NOT initialized, randombytes() falls back to
 *      esp_fill_random() which uses the ESP32 hardware RNG.
 *
 * This dual-mode behavior matches the host build (src/pq_drbg.c) where
 * the DRBG is initialized for keygen and randombytes() returns -1 if
 * called without initialization. On firmware we allow the fallback to
 * hardware RNG for encaps, which is the correct behavior.
 */
#include <string.h>
#include "esp_random.h"

/* Defined in pq_drbg_firmware.c */
extern int pq_drbg_randombytes(unsigned char *buf, size_t len);

/* Check if the DRBG is initialized (declared in pq_drbg_firmware.c).
 * We use a helper to avoid exposing the static directly. */
extern int pq_drbg_is_initialized(void);

int randombytes(unsigned char *buf, size_t len) {
    if (buf == NULL) {
        return -1;
    }

    /* If the deterministic DRBG is active (keygen mode), use it. */
    if (pq_drbg_is_initialized()) {
        return pq_drbg_randombytes(buf, len);
    }

    /* Otherwise, use the ESP32 hardware RNG for real randomness (encaps). */
    esp_fill_random(buf, len);
    return 0;
}
