#!/usr/bin/env python3
"""Derive a BIP39 mnemonic and first 20 BIP84 addresses from 256 entropy bits."""

import getpass
import hashlib
import re

from embit import bip32, bip39, networks, script


def main() -> None:
    raw = getpass.getpass("Paste exactly 256 entropy bits (input is hidden): ")
    bits = re.sub(r"\s+", "", raw)
    if len(bits) != 256 or set(bits) - {"0", "1"}:
        raise SystemExit("Error: enter exactly 256 characters containing only 0 and 1.")

    entropy = int(bits, 2).to_bytes(32, "big")
    checksum = f"{hashlib.sha256(entropy).digest()[0]:08b}"
    mnemonic = bip39.mnemonic_from_bytes(entropy)
    words = mnemonic.split()

    print(f"\nChecksum: {checksum}\n")
    print("24 BIP39 words:")
    for number, word in enumerate(words, 1):
        print(f"{number:2}. {word}")

    seed = bip39.mnemonic_to_seed(mnemonic)
    account = bip32.HDKey.from_seed(seed).derive("m/84h/0h/0h")
    print("\nFirst 20 mainnet Native SegWit addresses (BIP84):")
    for index in range(20):
        child = account.derive(f"0/{index}")
        address = script.p2wpkh(child.key).address(networks.NETWORKS["main"])
        print(f"{index + 1:2}. {address}")


if __name__ == "__main__":
    main()
