use std::{collections::HashMap, env::args, fs::File, io::Write};

use log::info;

use avalanche_types::key::{self, hot, mnemonic};

/// cargo run --example key_hot_mnemonic_gen_test_data -- 30 /tmp/test.key.infos.json
fn main() {
    // ref. https://github.com/env-logger-rs/env_logger/issues/47
    env_logger::init_from_env(
        env_logger::Env::default().filter_or(env_logger::DEFAULT_FILTER_ENV, "info"),
    );

    let n = args().nth(1).expect("no n given");
    let n = n.parse::<u32>().unwrap();

    let output_path = args().nth(2).expect("no output path given");

    let mut key_entries: Vec<hot::PrivateKeyInfoEntry> = Vec::new();
    for i in 0..n {
        info!("generating {}", i + 1);
        let phrase = mnemonic::gen_24();
        let key =
            hot::Key::from_mnemonic_phrase(phrase.clone(), String::from("m/44'/9000'/0'")).unwrap();

        let mut addresses: HashMap<String, key::ChainAddresses> = HashMap::new();

        let entry1 = key.private_key_info_entry(1).unwrap();
        addresses.insert("1".to_string(), entry1.addresses.get("1").unwrap().clone());
        let entry9999 = key.private_key_info_entry(9999).unwrap();
        addresses.insert(
            "9999".to_string(),
            entry9999.addresses.get("9999").unwrap().clone(),
        );

        key_entries.push(hot::PrivateKeyInfoEntry {
            mnemonic_phrase: Some(phrase),

            private_key: key.private_key,
            private_key_hex: key.private_key_hex,

            addresses,

            short_address: key.short_address,
            eth_address: key.eth_address,
        })
    }

    let d = serde_json::to_vec(&key_entries).unwrap();
    let mut f = File::create(&output_path).unwrap();
    f.write_all(&d).unwrap();

    info!("wrote to {}", output_path);
}
