use std::io::{self, Error, ErrorKind};

use sha2::Digest;

/// The length of recoverable ECDSA signature.
/// "github.com/decred/dcrd/dcrec/secp256k1/v3/ecdsa.SignCompact" outputs
/// 65-byte signature -- see "compactSigSize"
/// ref. "avalanchego/utils/crypto.PrivateKeySECP256K1R.SignHash"
/// ref. https://pkg.go.dev/github.com/ava-labs/avalanchego/utils/crypto#SECP256K1RSigLen
/// ref. "secp256k1::constants::SCHNORR_SIGNATURE_SIZE" + 1
pub const LEN: usize = 65;

/// Represents Ethereum-style "recoverable signatures".
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sig(k256::ecdsa::recoverable::Signature);

impl Sig {
    /// Loads the recoverable signature from the bytes.
    pub fn from_bytes(b: &[u8]) -> io::Result<Self> {
        if b.len() != LEN {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                "invalid signature length",
            ));
        }

        let sig = k256::ecdsa::recoverable::Signature::try_from(b).map_err(|e| {
            Error::new(
                ErrorKind::Other,
                format!("failed to load recoverable signature {}", e),
            )
        })?;
        Ok(Self(sig))
    }

    /// Converts the signature to bytes.
    pub fn to_bytes(&self) -> [u8; LEN] {
        let mut b = [0u8; LEN];
        b.copy_from_slice(self.0.as_ref());
        b
    }

    /// Recovers the public key from the message and its signature.
    pub fn recover_public_key(
        &self,
        msg: &[u8],
    ) -> io::Result<crate::key::secp256k1::public_key::Key> {
        let vkey = self.0.recover_verifying_key(msg).map_err(|e| {
            Error::new(
                ErrorKind::Other,
                format!("failed recover_verifying_key {}", e),
            )
        })?;
        Ok(vkey.into())
    }

    /// Recovers the public key from the message and its signature.
    pub fn recover_public_key_from_digest(
        &self,
        msg: &[u8],
    ) -> io::Result<crate::key::secp256k1::public_key::Key> {
        let mut prehash = sha2::Sha256::default();
        prehash.update(msg);

        let vkey = self
            .0
            .recover_verifying_key_from_digest(prehash)
            .map_err(|e| {
                Error::new(
                    ErrorKind::Other,
                    format!("failed recover_verifying_key {}", e),
                )
            })?;
        Ok(vkey.into())
    }
}

impl From<k256::ecdsa::recoverable::Signature> for Sig {
    fn from(sig: k256::ecdsa::recoverable::Signature) -> Self {
        Self(sig)
    }
}

impl From<Sig> for k256::ecdsa::recoverable::Signature {
    fn from(sig: Sig) -> Self {
        sig.0
    }
}

impl From<Sig> for [u8; LEN] {
    fn from(sig: Sig) -> Self {
        sig.to_bytes()
    }
}

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

    let pk = crate::key::secp256k1::private_key::Key::generate().unwrap();
    let pubkey1 = pk.to_public_key();

    let msg: Vec<u8> = vec![0, 1, 2, 3, 4, 5];
    let sig = pk.sign_recoverable_raw(&msg);
    assert_eq!(sig.to_bytes().len(), crate::key::secp256k1::signature::LEN);

    let pubkey2 = sig.recover_public_key(&msg).unwrap();
    assert_eq!(pubkey1, pubkey2);
}
