use device_signer::identity::DeviceIdentity;
use sha2::{Sha256, Digest};

/// Determinism test: same hardware inputs always produce the same keys.
#[test]
fn test_identity_determinism() {
    let id1 = DeviceIdentity::new(Some("TEST-CAM-001".to_string())).unwrap();
    let id2 = DeviceIdentity::new(Some("TEST-CAM-001".to_string())).unwrap();

    assert_eq!(id1.info.eth_address, id2.info.eth_address,
        "Ethereum addresses must be deterministic across calls");
    assert_eq!(id1.info.nostr_pubkey_hex, id2.info.nostr_pubkey_hex,
        "Nostr public keys must be deterministic across calls");
}

/// Ethereum address must be 40 hex chars with 0x prefix (20 bytes).
#[test]
fn test_eth_address_format() {
    let id = DeviceIdentity::new(None).unwrap();
    let addr = &id.info.eth_address;

    assert!(addr.starts_with("0x"), "Ethereum address must start with 0x");
    assert_eq!(addr.len(), 42, "Ethereum address must be 42 chars (0x + 40 hex)");
    assert!(addr[2..].chars().all(|c| c.is_ascii_hexdigit()),
        "Ethereum address must be hex");
}

/// An ECDSA hash signature from sign_hash_ecdsa must be 64 bytes (hex 128 chars).
#[test]
fn test_sign_hash_ecdsa_format() {
    let id = DeviceIdentity::new(None).unwrap();
    let mut hasher = Sha256::new();
    hasher.update(b"test image data from camera");
    let image_hash: [u8; 32] = hasher.finalize().into();

    let sig_hex = id.sign_hash_ecdsa(&image_hash).unwrap();
    assert_eq!(sig_hex.len(), 128, "ECDSA DER signature should be 64 bytes = 128 hex chars");
}

/// Nostr public key must be 64 lowercase hex chars (32 bytes — x-coordinate).
#[test]
fn test_nostr_pubkey_format() {
    let id = DeviceIdentity::new(None).unwrap();
    let npk = &id.info.nostr_pubkey_hex;

    assert_eq!(npk.len(), 64, "Nostr pubkey must be 64 hex chars (32 bytes)");
    assert!(npk.chars().all(|c| c.is_ascii_hexdigit() && !c.is_uppercase()),
        "Nostr pubkey must be lowercase hex");
}

/// Nostr npub must start with "npub1" (bech32 NIP-19 encoding).
#[test]
fn test_nostr_npub_format() {
    let id = DeviceIdentity::new(None).unwrap();
    let npub = &id.info.nostr_npub;

    assert!(npub.starts_with("npub1"), "Nostr npub must start with 'npub1'");
    // A valid bech32-encoded 32-byte npub is always 63 chars
    assert_eq!(npub.len(), 63, "npub1 string for 32 bytes must be 63 chars");
}

/// Schnorr signature from sign_nostr_event must be 64 bytes (128 hex chars).
#[test]
fn test_sign_nostr_event_format() {
    let id = DeviceIdentity::new(None).unwrap();
    let event_id: [u8; 32] = Sha256::digest(b"[0,\"pubkey\",1700000000,1,[],\"hello nostr\"]").into();

    let sig_hex = id.sign_nostr_event(&event_id).unwrap();
    assert_eq!(sig_hex.len(), 128, "Schnorr signature must be 64 bytes = 128 hex chars");
    assert!(sig_hex.chars().all(|c| c.is_ascii_hexdigit()),
        "Schnorr signature must be hex");
}
