"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mnemonicToBip39SeedHex = mnemonicToBip39SeedHex;
exports.deriveRoleSeeds = deriveRoleSeeds;
/**
 * Midnight HD key derivation (matches Lace / the Midnight reference wallet).
 *
 * Lace derives each wallet key type from a SEPARATE BIP32 role of the BIP39
 * seed — NOT from the raw seed. Feeding the raw 32-byte seed into
 * `ZswapSecretKeys.fromSeed` lands on a different account than the user's Lace
 * wallet, so the facade sees an empty wallet and deploys fail with "could not
 * balance dust". This module reproduces Lace's derivation:
 *
 *   bip39 seed (64B) → HDWallet.fromSeed → account 0 → role
 *     {Zswap | Dust | NightExternal} → deriveKeyAt(0) → 32-byte role seed
 *     → SDK ZswapSecretKeys.fromSeed / DustSecretKey.fromSeed / createKeystore
 *
 * Verified against a live Lace preprod account via
 * `scripts/probe-seed-derivation.mjs`: role Zswap at account 0 / index 0
 * reproduces the Lace shielded address exactly.
 *
 * `@midnight-ntwrk/wallet-sdk-hd` is ESM-only; loaded via dynamic import from
 * this CommonJS module (same pattern as srv/midnight/sdk-loader.ts).
 */
// Named imports: bip39's CJS build sets `__esModule` but exposes no default
// export, so `import bip39 from 'bip39'` resolves to undefined under
// esModuleInterop's __importDefault. Named bindings map to the real exports.
const bip39_1 = require("bip39");
const ACCOUNT = 0;
const KEY_INDEX = 0;
let cachedHd;
async function loadWalletHd() {
    if (!cachedHd)
        cachedHd = await import('@midnight-ntwrk/wallet-sdk-hd');
    return cachedHd;
}
/** BIP39 mnemonic → 64-byte seed as 128-char hex. Throws on an invalid phrase. */
function mnemonicToBip39SeedHex(mnemonic) {
    const m = mnemonic.trim();
    if (!(0, bip39_1.validateMnemonic)(m)) {
        throw new Error('Invalid BIP39 mnemonic');
    }
    return (0, bip39_1.mnemonicToSeedSync)(m).toString('hex');
}
/**
 * Derive the per-role 32-byte seeds from a 64-byte BIP39 seed, matching Lace.
 * Each result is fed to the SDK's fromSeed/createKeystore for its key type.
 */
async function deriveRoleSeeds(bip39Seed) {
    const { HDWallet, Roles } = await loadWalletHd();
    const res = HDWallet.fromSeed(bip39Seed);
    if (res?.type !== 'seedOk') {
        throw new Error(`HDWallet.fromSeed failed: ${res?.error ?? 'unknown'}`);
    }
    const hd = res.hdWallet;
    try {
        return {
            zswap: deriveOne(hd, Roles.Zswap),
            dust: deriveOne(hd, Roles.Dust),
            night: deriveOne(hd, Roles.NightExternal)
        };
    }
    finally {
        hd.clear?.();
    }
}
function deriveOne(hd, role) {
    const d = hd.selectAccount(ACCOUNT).selectRole(role).deriveKeyAt(KEY_INDEX);
    if (d?.type !== 'keyDerived' || d.key?.length !== 32) {
        throw new Error(`HD key derivation failed for role ${role}: ${d?.type ?? 'no result'}`);
    }
    return d.key;
}
