pub mod address;
pub mod keychain;
pub mod private_key;
pub mod public_key;
pub mod signature;
pub mod txs;

#[cfg(feature = "aws_kms")]
pub mod aws_kms;

#[cfg(feature = "libsecp256k1")]
pub mod libsecp256k1;

#[cfg(feature = "mnemonic")]
pub mod mnemonic;

use std::{
    collections::{HashMap, VecDeque},
    fmt,
    fs::{self, File},
    io::{self, Error, ErrorKind, Write},
    path::Path,
};

use crate::ids::short;
use async_trait::async_trait;
use lazy_static::lazy_static;
use rust_embed::RustEmbed;
use serde::{Deserialize, Serialize};

/// Key interface that "only" allows "read" operations.
pub trait ReadOnly {
    /// Implements "crypto.PublicKeySECP256K1R.Address()" and "formatting.FormatAddress".
    /// "human readable part" (hrp) must be valid output from "constants.GetHRP(networkID)".
    /// ref. https://pkg.go.dev/github.com/ava-labs/avalanchego/utils/constants
    fn get_address(&self, network_id: u32, chain_id_alias: &str) -> io::Result<String>;
    fn get_short_address(&self) -> io::Result<short::Id>;
    fn get_short_address_bytes(&self) -> io::Result<Vec<u8>>;
    fn get_eth_address(&self) -> String;
    fn get_h160_address(&self) -> primitive_types::H160;
}

/// Key interface that "only" allows "sign" operations.
/// Trait is used here to limit access to the underlying private/secret key.
/// or to enable secure remote key management service integration (e.g., KMS ECC_SECG_P256K1).
#[async_trait]
pub trait SignOnly {
    /// Signs the 32-byte SHA256 output message with the ECDSA private key and the recoverable code.
    /// "github.com/decred/dcrd/dcrec/secp256k1/v3/ecdsa.SignCompact" outputs 65-byte signature.
    /// TODO: Use "async" to support AWS KMS and ledger.
    /// ref. "avalanchego/utils/crypto.PrivateKeySECP256K1R.SignHash"
    /// ref. https://github.com/rust-bitcoin/rust-secp256k1/blob/master/src/ecdsa/recovery.rs
    /// ref. https://docs.rs/secp256k1/latest/secp256k1/struct.SecretKey.html#method.sign_ecdsa
    /// ref. https://docs.rs/secp256k1/latest/secp256k1/struct.Message.html
    /// ref. https://pkg.go.dev/github.com/ava-labs/avalanchego/utils/crypto#PrivateKeyED25519.SignHash
    async fn sign_digest(&self, digest: &[u8]) -> io::Result<[u8; 65]>;

    /// Returns the ethers signing key.
    #[cfg(feature = "ethers_core")]
    fn ethers_signing_key(&self) -> io::Result<ethers_core::k256::ecdsa::SigningKey>;
}

lazy_static! {
    /// Test keys generated by "avalanchego/utils/crypto.FactorySECP256K1R".
    pub static ref TEST_KEYS: Vec<crate::key::secp256k1::private_key::Key> = {
        #[derive(RustEmbed)]
        #[folder = "artifacts/"]
        #[prefix = "artifacts/"]
        struct Asset;

        let key_file_no_mnemonic =
            Asset::get("artifacts/test.insecure.secp256k1.key.infos.no.mnemonic.json").unwrap();
        let key_file_mnemonic =
            Asset::get("artifacts/test.insecure.secp256k1.key.infos.mnemonic.json").unwrap();

        let key_infos_no_mnemonic: Vec<Info> =
            serde_json::from_slice(&key_file_no_mnemonic.data).unwrap();
        let key_infos_mnemonic: Vec<Info> =
            serde_json::from_slice(&key_file_mnemonic.data).unwrap();
        let mut key_infos_mnemonic: VecDeque<Info> = VecDeque::from(key_infos_mnemonic);

        let mut keys: Vec<crate::key::secp256k1::private_key::Key> = Vec::new();
        for ki in key_infos_no_mnemonic.iter() {
            keys.push(
                crate::key::secp256k1::private_key::Key::from_cb58(ki.private_key_cb58.clone())
                    .unwrap(),
            );
            if let Some(front) = key_infos_mnemonic.pop_front() {
                let k = crate::key::secp256k1::private_key::Key::from_cb58(front.private_key_cb58)
                    .unwrap();
                keys.push(k);
            }
        }
        while let Some(front) = key_infos_mnemonic.pop_front() {
            keys.push(
                crate::key::secp256k1::private_key::Key::from_cb58(front.private_key_cb58.clone())
                    .unwrap(),
            );
        }
        keys
    };

    /// Test key infos in the same order of "TEST_KEYS".
    pub static ref TEST_INFOS: Vec<Info> = {
        #[derive(RustEmbed)]
        #[folder = "artifacts/"]
        #[prefix = "artifacts/"]
        struct Asset;

        let key_file_no_mnemonic =
            Asset::get("artifacts/test.insecure.secp256k1.key.infos.no.mnemonic.json").unwrap();
        let key_file_mnemonic =
            Asset::get("artifacts/test.insecure.secp256k1.key.infos.mnemonic.json").unwrap();

        let key_infos_no_mnemonic: Vec<Info> =
            serde_json::from_slice(&key_file_no_mnemonic.data).unwrap();
        let key_infos_mnemonic: Vec<Info> =
            serde_json::from_slice(&key_file_mnemonic.data).unwrap();
        let mut key_infos_mnemonic: VecDeque<Info> = VecDeque::from(key_infos_mnemonic);

        let mut infos: Vec<Info> = Vec::new();
        for ki in key_infos_no_mnemonic {
            infos.push(ki.clone());
            if let Some(front) = key_infos_mnemonic.pop_front() {
                infos.push(front);
            }
        }
        while let Some(front) = key_infos_mnemonic.pop_front() {
            infos.push(front);
        }
        infos
    };
}

/// RUST_LOG=debug cargo test --package avalanche-types --lib -- key::secp256k1::test_keys --exact --show-output
#[test]
fn test_keys() {
    let _ = env_logger::builder()
        .filter_level(log::LevelFilter::Info)
        .is_test(true)
        .try_init();

    for k in TEST_KEYS.iter() {
        log::info!(
            "[KEY] test key eth address {:?}",
            k.to_public_key().to_eth_address()
        );
    }
    for ki in TEST_INFOS.iter() {
        log::info!("[INFO] test key eth address {:?}", ki.eth_address);
    }
    assert_eq!(TEST_KEYS.len(), TEST_INFOS.len());

    log::info!("total {} test keys are found", TEST_KEYS.len());
}

#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "snake_case")]
pub struct ChainAddresses {
    pub x_address: String,
    pub p_address: String,
    pub c_address: String,
}

// test random keys generated by "avalanchego/utils/crypto.FactorySECP256K1R"
// and make sure both generate the same addresses
// use "avalanche-rust/avalanchego-conformance/key/secp256k1"
// to generate keys and addresses with "avalanchego"
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "snake_case")]
pub struct Info {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mnemonic_phrase: Option<String>,

    /// CB58-encoded private key with the prefix "PrivateKey-" (e.g., Avalanche).
    pub private_key_cb58: String,
    /// Hex-encoded private key without the prefix "0x" (e.g., Ethereum).
    pub private_key_hex: String,

    pub addresses: HashMap<u32, ChainAddresses>,

    pub short_address: short::Id,
    pub eth_address: String,
}

impl From<&crate::key::secp256k1::private_key::Key> for Info {
    fn from(sk: &crate::key::secp256k1::private_key::Key) -> Self {
        sk.to_info(1).unwrap()
    }
}

impl Info {
    pub fn load(file_path: &str) -> io::Result<Self> {
        log::info!("loading Info from {}", file_path);

        if !Path::new(file_path).exists() {
            return Err(Error::new(
                ErrorKind::NotFound,
                format!("file {} does not exists", file_path),
            ));
        }

        let f = File::open(&file_path).map_err(|e| {
            return Error::new(
                ErrorKind::Other,
                format!("failed to open {} ({})", file_path, e),
            );
        })?;
        serde_yaml::from_reader(f).map_err(|e| {
            return Error::new(ErrorKind::InvalidInput, format!("invalid YAML: {}", e));
        })
    }

    pub fn sync(&self, file_path: String) -> io::Result<()> {
        log::info!("syncing key info to '{}'", file_path);
        let path = Path::new(&file_path);
        let parent_dir = path.parent().unwrap();
        fs::create_dir_all(parent_dir)?;

        let ret = serde_json::to_vec(&self);
        let d = match ret {
            Ok(d) => d,
            Err(e) => {
                return Err(Error::new(
                    ErrorKind::Other,
                    format!("failed to serialize key info to YAML {}", e),
                ));
            }
        };
        let mut f = File::create(&file_path)?;
        f.write_all(&d)?;

        Ok(())
    }
}

/// ref. https://doc.rust-lang.org/std/string/trait.ToString.html
/// ref. https://doc.rust-lang.org/std/fmt/trait.Display.html
/// Use "Self.to_string()" to directly invoke this
impl fmt::Display for Info {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = serde_yaml::to_string(&self).unwrap();
        write!(f, "{}", s)
    }
}

/// RUST_LOG=debug cargo test --package avalanche-types --lib -- key::secp256k1::test_keys_address --exact --show-output
#[test]
fn test_keys_address() {
    let _ = env_logger::builder()
        .filter_level(log::LevelFilter::Info)
        .is_test(true)
        .try_init();

    #[derive(RustEmbed)]
    #[folder = "artifacts/"]
    #[prefix = "artifacts/"]
    struct Asset;

    for asset in vec![
        "artifacts/test.insecure.secp256k1.key.infos.mnemonic.json",
        "artifacts/test.insecure.secp256k1.key.infos.no.mnemonic.json",
    ] {
        let key_file = Asset::get(asset).unwrap();
        let key_contents = std::str::from_utf8(key_file.data.as_ref()).unwrap();
        let key_infos: Vec<Info> = serde_json::from_slice(&key_contents.as_bytes()).unwrap();
        log::info!("loaded {}", asset);

        for (pos, ki) in key_infos.iter().enumerate() {
            log::info!("checking the key info at {}", pos);

            let sk =
                crate::key::secp256k1::private_key::Key::from_cb58(&ki.private_key_cb58).unwrap();
            assert_eq!(
                sk,
                crate::key::secp256k1::private_key::Key::from_hex(&ki.private_key_hex).unwrap(),
            );
            let pubkey = sk.to_public_key();

            assert_eq!(
                pubkey.to_avax_address(1, "X").unwrap(),
                ki.addresses.get(&1).unwrap().x_address
            );
            assert_eq!(
                pubkey.to_avax_address(1, "P").unwrap(),
                ki.addresses.get(&1).unwrap().p_address
            );
            assert_eq!(
                pubkey.to_avax_address(1, "C").unwrap(),
                ki.addresses.get(&1).unwrap().c_address
            );

            assert_eq!(
                pubkey.to_avax_address(9999, "X").unwrap(),
                ki.addresses.get(&9999).unwrap().x_address
            );
            assert_eq!(
                pubkey.to_avax_address(9999, "P").unwrap(),
                ki.addresses.get(&9999).unwrap().p_address
            );
            assert_eq!(
                pubkey.to_avax_address(9999, "C").unwrap(),
                ki.addresses.get(&9999).unwrap().c_address
            );

            assert_eq!(pubkey.to_short_id().unwrap(), ki.short_address);
            assert_eq!(pubkey.to_eth_address(), ki.eth_address);
        }
    }
}
