"""BTCQ HD key derivation — all-hardened ML-DSA-65."""
import hmac
import hashlib


class BtcqKeyDerivation:
    def __init__(self, secret_key, public_key, chaincode, depth=0,
                 parent_fingerprint=b'\x00\x00\x00\x00', child_index=0, seed_xi=b''):
        self.secret_key = secret_key    # 4032 bytes
        self.public_key = public_key    # 1952 bytes
        self.chaincode = chaincode      # 32 bytes
        self.depth = depth
        self.parent_fingerprint = parent_fingerprint
        self.child_index = child_index
        self.seed_xi = seed_xi          # 32 bytes

    @classmethod
    def from_seed(cls, seed: bytes):
        """Create master key from 64-byte BIP32 seed."""
        from electrum.mldsa import mldsa_keygen_from_seed
        hmac_out = hmac.new(b"Bitcoin seed", seed, hashlib.sha512).digest()
        il, ir = hmac_out[:32], hmac_out[32:]
        pk, sk = mldsa_keygen_from_seed(il)
        return cls(secret_key=sk, public_key=pk, chaincode=ir, depth=0, seed_xi=il)

    def derive_child(self, index: int):
        """Derive child key. Uses rho (sk[0:32]) per Representation Invariant."""
        from electrum.mldsa import mldsa_keygen_from_seed
        from electrum.btcq_crypto import hash_160_btcq
        rho = self.secret_key[:32]
        data = b'\x00' + rho + index.to_bytes(4, 'big')
        hmac_out = hmac.new(self.chaincode, data, hashlib.sha512).digest()
        child_xi, child_cc = hmac_out[:32], hmac_out[32:]
        child_pk, child_sk = mldsa_keygen_from_seed(child_xi)
        fingerprint = hash_160_btcq(self.public_key)[:4]
        return BtcqKeyDerivation(
            secret_key=child_sk, public_key=child_pk, chaincode=child_cc,
            depth=self.depth + 1, parent_fingerprint=fingerprint,
            child_index=index, seed_xi=child_xi,
        )
