use std::{
    fs::{self, File},
    io::Write,
    path::PathBuf,
};

use bft_json_crdt::keypair::{make_keypair, Ed25519KeyPair};
use fastcrypto::traits::EncodeDecodeBase64;

/// Writes a new Ed25519 keypair to the file at key_path.
pub(crate) fn write(key_path: &PathBuf) -> Result<(), std::io::Error> {
    let keys = make_keypair();

    let mut file = File::create(key_path)?;
    let out = keys.encode_base64();
    file.write(out.as_bytes())?;
    Ok(())
}

pub(crate) fn load_from_file(side_dir: &PathBuf) -> Ed25519KeyPair {
    let key_path = crate::utils::side_paths(side_dir.clone()).0;

    let data = fs::read_to_string(key_path).expect("couldn't read bft-bft-crdt key file");
    println!("data: {:?}", data);

    Ed25519KeyPair::decode_base64(&data).expect("couldn't load keypair from file")
}
