//! RFC-008: IQA Implementation Example
//! 
//! This example demonstrates the core concepts of RFC-008:
//! 1. Imperial Seal Generation and Validation
//! 2. Real-Time Attestation Protocol
//! 3. Vitality Monitoring System
//! 4. Staking-Based Trust Verification

use std::collections::HashMap;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::RwLock;
use serde::{Serialize, Deserialize};
use sha3::{Digest, Sha3_256, Sha3_512};
use ed25519_dalek::{SigningKey, VerifyingKey, Signature, Signer, Verifier};
use rand::rngs::OsRng;

// ============================================================================
// Core Types
// ============================================================================

/// Trust Levels for IQA Seals
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TrustLevel {
    Dormant = 0,    // Basic verification, legacy latency
    Active = 1,     // <50ns matching engine access
    Radiant = 2,    // High-value diplomatic mesh access
    Revoked = 3,    // Isolated from the grid
}

/// Staking Tiers for Economic Skin-in-Game
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StakingTier {
    Basic = 1,      // 1,000 ZCMK units
    Active = 2,     // 10,000 ZCMK units
    Radiant = 3,    // 100,000 ZCMK units
}

/// Imperial Seal - 256-bit cryptographic proof
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImperialSeal {
    pub seal_id: u128,
    pub issued_to: [u8; 32],        // RFC-001 AID
    pub trust_level: TrustLevel,
    pub staking_tier: StakingTier,
    pub issuance_epoch: u64,        // µs since epoch
    pub expiration_epoch: u64,      // µs since epoch
    pub vitality_hash: [u8; 32],    // SHA3-256 of last 100 vitality pulses
    pub authority_signature: [u8; 64], // Ed25519 signature
}

impl ImperialSeal {
    /// Generate a new Imperial Seal
    pub fn generate(
        aid: [u8; 32],
        trust_level: TrustLevel,
        staking_tier: StakingTier,
        authority_key: &SigningKey,
    ) -> Self {
        let seal_id = Self::generate_seal_id(&aid, trust_level);
        let issuance_epoch = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_micros() as u64;
        
        // 24-hour validity period
        let expiration_epoch = issuance_epoch + (24 * 60 * 60 * 1_000_000);
        
        // Initial vitality hash (zero for new seal)
        let vitality_hash = [0u8; 32];
        
        // Create seal without signature first
        let mut seal = Self {
            seal_id,
            issued_to: aid,
            trust_level,
            staking_tier,
            issuance_epoch,
            expiration_epoch,
            vitality_hash,
            authority_signature: [0u8; 64],
        };
        
        // Sign the seal
        let signature = Self::sign_seal(&seal, authority_key);
        seal.authority_signature = signature.to_bytes();
        
        seal
    }
    
    /// Verify the integrity and validity of a seal
    pub fn verify(&self, authority_pubkey: &VerifyingKey) -> SealVerificationResult {
        // 1. Check expiration
        let current_epoch = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_micros() as u64;
        
        if current_epoch > self.expiration_epoch {
            return SealVerificationResult::Expired(self.expiration_epoch);
        }
        
        // 2. Validate seal ID
        let expected_id = Self::generate_seal_id(&self.issued_to, self.trust_level);
        if self.seal_id != expected_id {
            return SealVerificationResult::InvalidId;
        }
        
        // 3. Verify signature
        let signature = match Signature::from_bytes(&self.authority_signature) {
            Ok(sig) => sig,
            Err(_) => return SealVerificationResult::InvalidSignature,
        };
        
        if !self.verify_signature(authority_pubkey, &signature) {
            return SealVerificationResult::InvalidSignature;
        }
        
        // 4. Check vitality hash freshness (must be updated every 100 pulses)
        let max_staleness = 100 * 83_333; // 100 pulses * 83.333µs per pulse
        if current_epoch - self.issuance_epoch > max_staleness 
            && self.vitality_hash == [0u8; 32] {
            return SealVerificationResult::StaleVitality;
        }
        
        SealVerificationResult::Valid
    }
    
    fn generate_seal_id(aid: &[u8; 32], trust_level: TrustLevel) -> u128 {
        let mut hasher = Sha3_256::new();
        hasher.update(aid);
        hasher.update(trust_level as u8);
        let hash = hasher.finalize();
        
        // Convert first 16 bytes to u128
        let mut bytes = [0u8; 16];
        bytes.copy_from_slice(&hash[..16]);
        u128::from_le_bytes(bytes)
    }
    
    fn sign_seal(seal: &Self, authority_key: &SigningKey) -> Signature {
        let message = seal.signing_message();
        authority_key.sign(&message)
    }
    
    fn signing_message(&self) -> Vec<u8> {
        let mut message = Vec::new();
        message.extend_from_slice(&self.seal_id.to_le_bytes());
        message.extend_from_slice(&self.issued_to);
        message.extend_from_slice(&[self.trust_level as u8]);
        message.extend_from_slice(&[self.staking_tier as u8]);
        message.extend_from_slice(&self.issuance_epoch.to_le_bytes());
        message.extend_from_slice(&self.expiration_epoch.to_le_bytes());
        message.extend_from_slice(&self.vitality_hash);
        message
    }
    
    fn verify_signature(&self, pubkey: &VerifyingKey, signature: &Signature) -> bool {
        let message = self.signing_message();
        pubkey.verify(&message, signature).is_ok()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SealVerificationResult {
    Valid,
    Expired(u64),
    InvalidId,
    InvalidSignature,
    StaleVitality,
    InsufficientStake,
    ComplianceViolation,
}

// ============================================================================
// Vitality Monitoring System
// ============================================================================

/// Vitality Pulse - Health status of a node
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VitalityPulse {
    pub seal_id: u128,
    pub source_aid: [u8; 32],
    pub pulse_number: u64,
    pub homeostasis_score: f64,  // 0.0 to 1.0
    pub resource_metrics: ResourceMetrics,
    pub compliance_events: Vec<ComplianceEvent>,
    pub signature: [u8; 64],
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceMetrics {
    pub cpu_utilization: f64,     // 0.0 to 1.0
    pub memory_utilization: f64,  // 0.0 to 1.0
    pub network_bandwidth: f64,   // Gbps
    pub latency_95th: u32,        // µs
    pub error_rate: f64,          // 0.0 to 1.0
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplianceEvent {
    pub timestamp: u64,
    pub event_type: ComplianceEventType,
    pub severity: u8,           // 1-10
    pub description: String,
    pub corrective_action: Option<String>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum ComplianceEventType {
    PolicyViolation,
    PerformanceDrift,
    SecurityAnomaly,
    ResourceExhaustion,
    NetworkPartition,
    ProtocolViolation,
}

/// Vitality Monitor - Real-time health tracking
pub struct VitalityMonitor {
    node_metrics: RwLock<HashMap<u128, NodeHealthSnapshot>>,
    pulse_counter: RwLock<HashMap<u128, u64>>,
    health_threshold: f64, // 0.7 = 70% minimum health
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeHealthSnapshot {
    pub aid: [u8; 32],
    pub homeostasis_score: f64,
    pub last_pulse_time: u64,
    pub pulse_count: u64,
    pub recent_compliance_events: Vec<ComplianceEvent>,
    pub performance_trend: PerformanceTrend,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum PerformanceTrend {
    Improving,
    Stable,
    Declining,
    Critical,
}

impl VitalityMonitor {
    pub fn new(health_threshold: f64) -> Self {
        Self {
            node_metrics: RwLock::new(HashMap::new()),
            pulse_counter: RwLock::new(HashMap::new()),
            health_threshold,
        }
    }
    
    pub async fn process_vitality_pulse(
        &self,
        pulse: VitalityPulse,
    ) -> VitalityProcessingResult {
        let start_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_micros();
        
        // 1. Verify pulse signature (simplified)
        // In production, would verify with node's public key
        
        // 2. Update pulse counter
        let pulse_num = {
            let mut counters = self.pulse_counter.write().await;
            let count = counters.entry(pulse.seal_id).or_insert(0);
            *count += 1;
            *count
        };
        
        // 3. Calculate homeostasis score
        let hs = self.calculate_homeostasis_score(&pulse).await;
        
        // 4. Update node metrics
        let snapshot = NodeHealthSnapshot {
            aid: pulse.source_aid,
            homeostasis_score: hs,
            last_pulse_time: start_time,
            pulse_count: pulse_num,
            recent_compliance_events: pulse.compliance_events.clone(),
            performance_trend: self.assess_trend(pulse_num, hs).await,
        };
        
        self.node_metrics.write().await
            .insert(pulse.seal_id, snapshot);
        
        // 5. Check health status
        let status = if hs < self.health_threshold {
            NodeHealthStatus::Critical(hs)
        } else if hs < 0.85 {
            NodeHealthStatus::Warning(hs)
        } else {
            NodeHealthStatus::Healthy(hs)
        };
        
        let end_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_micros();
        
        let latency = (end_time - start_time) as u32;
        
        VitalityProcessingResult {
            status,
            latency,
            pulse_number: pulse_num,
            trend: snapshot.performance_trend,
        }
    }
    
    async fn calculate_homeostasis_score(&self, pulse: &VitalityPulse) -> f64 {
        let metrics = &pulse.resource_metrics;
        
        // Weighted scoring based on RFC-008 requirements
        let cpu_score = 1.0 - metrics.cpu_utilization.min(1.0);
        let memory_score = 1.0 - metrics.memory_utilization.min(1.0);
        let network_score = if metrics.network_bandwidth > 1.0 { 1.0 } else { metrics.network_bandwidth };
        let latency_score = if metrics.latency_95th <= 200 { 1.0 } else { 0.5 };
        let error_score = 1.0 - metrics.error_rate.min(1.0);
        
        // Apply compliance penalty
        let compliance_penalty = self.calculate_compliance_penalty(&pulse.compliance_events).await;
        
        // Weighted average (RFC-008 balanced scoring)
        let base_score = (
            cpu_score * 0.25 +
            memory_score * 0.20 +
            network_score * 0.20 +
            latency_score * 0.25 +
            error_score * 0.10
        ).max(0.0).min(1.0);
        
        // Apply penalty
        (base_score - compliance_penalty).max(0.0)
    }
    
    async fn calculate_compliance_penalty(&self, events: &[ComplianceEvent]) -> f64 {
        let mut penalty = 0.0;
        
        for event in events {
            // Weight by severity and recency
            let severity_weight = event.severity as f64 / 10.0;
            let time_weight = self.calculate_time_weight(event.timestamp).await;
            penalty += severity_weight * time_weight * 0.1; // Max 10% penalty per event
        }
        
        penalty.min(0.5) // Cap at 50% penalty
    }
    
    async fn calculate_time_weight(&self, event_time: u64) -> f64 {
        let current_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_micros() as u64;
        
        let elapsed = current_time - event_time;
        let hour_micros = 60 * 60 * 1_000_000;
        
        // Exponential decay: recent events have higher weight
        if elapsed < hour_micros {
            1.0
        } else if elapsed < 24 * hour_micros {
            0.5
        } else {
            0.1
        }
    }
    
    async fn assess_trend(&self, pulse_count: u64, current_hs: f64) -> PerformanceTrend {
        // Simplified trend analysis
        // In production, would analyze historical data
        
        if current_hs < 0.7 {
            PerformanceTrend::Critical
        } else if current_hs < 0.8 {
            PerformanceTrend::Declining
        } else if current_hs < 0.9 {
            PerformanceTrend::Stable
        } else {
            PerformanceTrend::Improving
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VitalityProcessingResult {
    pub status: NodeHealthStatus,
    pub latency: u32, // µs
    pub pulse_number: u64,
    pub trend: PerformanceTrend,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum NodeHealthStatus {
    Healthy(f64),
    Warning(f64),
    Critical(f64),
}

// ============================================================================
// IQA Engine
// ============================================================================

/// IQA Engine - Main orchestrator for RFC-008
pub struct IqaEngine {
    authority_key: SigningKey,
    verifying_key: VerifyingKey,
    vitality_monitor: Arc<VitalityMonitor>,
    seal_registry: RwLock<HashMap<u128, ImperialSeal>>,
    revocation_list: RwLock<HashMap<u128, RevocationRecord>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AttestationRequest {
    pub request_id: u128,
    pub target_aid: [u8; 32],
    pub staking_proof: ZCMKStakeReceipt,
    pub compliance_manifest: [u8; 32],
    pub performance_metrics: ResourceMetrics,
    pub requested_trust_level: TrustLevel,
    pub timestamp: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZCMKStakeReceipt {
    pub vault_address: [u8; 32],
    pub stake_amount: u64,
    pub lock_period: u64, // µs
    pub transaction_hash: [u8; 32],
    pub signature: [u8; 64],
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AttestationResponse {
    pub request_id: u128,
    pub status: AttestationStatus,
    pub issued_seal: Option<ImperialSeal>,
    pub vitality_requirements: VitalitySpec,
    pub next_attestation_deadline: u64,
    pub error_details: Option<AttestationError>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AttestationStatus {
    Granted(ImperialSeal),
    Denied(DenialReason),
    Pending(Vec<Requirement>),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DenialReason {
    InsufficientStake,
    ComplianceFailure,
    PerformanceInadequate,
    ReputationLow,
    TechnicalError,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VitalitySpec {
    pub monitoring_frequency: u32, // Hz
    pub minimum_homeostasis: f64,
    pub reporting_interval: u64,   // pulses
    pub alert_threshold: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AttestationError {
    pub code: String,
    pub message: String,
    pub details: Option<String>,
    pub recovery_action: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RevocationRecord {
    pub seal_id: u128,
    pub aid: [u8; 32],
    pub reason: RevocationReason,
    pub timestamp: u64,
    pub slashed_amount: u64,
    pub quarantine_duration: u64,
    pub authority_signature: [u8; 64],
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RevocationReason {
    SealExpired,
    StakingWithdrawn,
    VitalityFailed,
    ComplianceViolation,
    SignatureForgery,
    NetworkAttack,
}

impl IqaEngine {
    pub fn new() -> Self {
        let authority_key = SigningKey::generate(&mut OsRng);
        let verifying_key = authority_key.verifying_key();
        
        Self {
            authority_key,
            verifying_key,
            vitality_monitor: Arc::new(VitalityMonitor::new(0.7)),
            seal_registry: RwLock::new(HashMap::new()),
            revocation_list: RwLock::new(HashMap::new()),
        }
    }
    
    pub async fn submit_attestation(
        &self,
        request: AttestationRequest,
    ) -> Result<AttestationResponse, Box<dyn std::error::Error>> {
        let start_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_micros();
        
        // 1. Check for existing revocation
        if self.is_revoked(&request.target_aid).await {
            return Ok(AttestationResponse {
                request_id: request.request_id,
                status: AttestationStatus::Denied(DenialReason::ComplianceFailure),
                issued_seal: None,
                vitality_requirements: VitalitySpec::default(),
                next_attestation_deadline: 0,
                error_details: Some(AttestationError {
                    code: "IQA-009".to_string(),
                    message: "Node is on revocation list".to_string(),
                    details: Some("Previous compliance violation".to_string()),
                    recovery_action: Some("Appeal to authority".to_string()),
                }),
            });
        }
        
        // 2. Validate staking proof (simplified)
        let staking_tier = self.validate_staking(&request.staking_proof).await?;
        
        // 3. Check performance metrics
        let performance_ok = self.check_performance(&request.performance_metrics).await;
        
        if !performance_ok {
            return Ok(AttestationResponse {
                request_id: request.request_id,
                status: AttestationStatus::Denied(DenialReason::PerformanceInadequate),
                issued_seal: None,
                vitality_requirements: VitalitySpec::default(),
                next_attestation_deadline: 0,
                error_details: Some(AttestationError {
                    code: "IQA-003".to_string(),
                    message: "Performance metrics below threshold".to_string(),
                    details: Some("Latency too high or resources exhausted".to_string()),
                    recovery_action: Some("Optimize node performance".to_string()),
                }),
            });
        }
        
        // 4. Determine trust level
        let trust_level = self.determine_trust_level(
            request.requested_trust_level,
            staking_tier,
            &request.performance_metrics,
        ).await;
        
        // 5. Generate Imperial Seal
        let seal = ImperialSeal::generate(
            request.target_aid,
            trust_level,
            staking_tier,
            &self.authority_key,
        );
        
        // 6. Register the seal
        self.seal_registry.write().await
            .insert(seal.seal_id, seal.clone());
        
        // 7. Calculate latency
        let end_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_micros();
        let latency = (end_time - start_time) as u32;
        
        // 8. Return response
        Ok(AttestationResponse {
            request_id: request.request_id,
            status: AttestationStatus::Granted(seal.clone()),
            issued_seal: Some(seal),
            vitality_requirements: VitalitySpec {
                monitoring_frequency: 120,
                minimum_homeostasis: 0.7,
                reporting_interval: 100,
                alert_threshold: 0.85,
            },
            next_attestation_deadline: seal.expiration_epoch - 1_000_000, // 1 second before expiry
            error_details: None,
        })
    }
    
    async fn validate_staking(&self, receipt: &ZCMKStakeReceipt) -> Result<StakingTier, Box<dyn std::error::Error>> {
        // Simplified validation
        // In production, would verify on-chain
        
        match receipt.stake_amount {
            s if s >= 100_000 => Ok(StakingTier::Radiant),
            s if s >= 10_000 => Ok(StakingTier::Active),
            s if s >= 1_000 => Ok(StakingTier::Basic),
            _ => Err("Insufficient stake amount".into()),
        }
    }
    
    async fn check_performance(&self, metrics: &ResourceMetrics) -> bool {
        // RFC-008 performance requirements
        metrics.latency_95th <= 200 &&      // < 200µs latency
        metrics.cpu_utilization <= 0.9 &&   // < 90% CPU
        metrics.memory_utilization <= 0.9 && // < 90% memory
        metrics.error_rate <= 0.01          // < 1% error rate
    }
    
    async fn determine_trust_level(
        &self,
        requested: TrustLevel,
        staking_tier: StakingTier,
        metrics: &ResourceMetrics,
    ) -> TrustLevel {
        // Simplified trust level determination
        // In production, would consider more factors
        
        match (requested, staking_tier) {
            (TrustLevel::Radiant, StakingTier::Radiant) => {
                if metrics.latency_95th <= 150 {
                    TrustLevel::Radiant
                } else {
                    TrustLevel::Active
                }
            }
            (TrustLevel::Active, StakingTier::Active) => TrustLevel::Active,
            _ => TrustLevel::Dormant,
        }
    }
    
    async fn is_revoked(&self, aid: &[u8; 32]) -> bool {
        let revocations = self.revocation_list.read().await;
        
        // Check if any seal for this AID is revoked
        revocations.values()
            .any(|record| &record.aid == aid)
    }
    
    pub async fn revoke_seal(
        &self,
        seal_id: u128,
        reason: RevocationReason,
        slashed_amount: u64,
        quarantine_duration: u64,
    ) -> Result<(), Box<dyn std::error::Error>> {
        // 1. Get the seal
        let seal = self.seal_registry.read().await
            .get(&seal_id)
            .ok_or("Seal not found")?
            .clone();
        
        // 2. Create revocation record
        let record = RevocationRecord {
            seal_id,
            aid: seal.issued_to,
            reason,
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_micros() as u64,
            slashed_amount,
            quarantine_duration,
            authority_signature: self.authority_key
                .sign(&seal_id.to_le_bytes())
                .to_bytes(),
        };
        
        // 3. Add to revocation list
        self.revocation_list.write().await
            .insert(seal_id, record);
        
        // 4. Remove from seal registry
        self.seal_registry.write().await
            .remove(&seal_id);
        
        println!("Seal {} revoked for reason: {:?}", seal_id, reason);
        println!("Slashed {} ZCMK units", slashed_amount);
        println!("Quarantine duration: {}µs", quarantine_duration);
        
        Ok(())
    }
}

impl Default for VitalitySpec {
    fn default() -> Self {
        Self {
            monitoring_frequency: 120,
            minimum_homeostasis: 0.7,
            reporting_interval: 100,
            alert_threshold: 0.85,
        }
    }
}

// ============================================================================
// Example Usage
// ============================================================================

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("RFC-008: IQA Implementation Example");
    println!("====================================\n");
    
    // Initialize IQA Engine
    let iqa_engine = IqaEngine::new();
    println!("✓ IQA Engine initialized");
    
    // Generate a test AID (RFC-001)
    let mut aid = [0u8; 32];
    OsRng.fill_bytes(&mut aid);
    println!("✓ Test AID generated: {}", hex::encode(&aid[..8]));
    
    // Create attestation request
    let request = AttestationRequest {
        request_id: 987654321,
        target_aid: aid,
        staking_proof: ZCMKStakeReceipt {
            vault_address: [1u8; 32],
            stake_amount: 50_000,
            lock_period: 24 * 60 * 60 * 1_000_000, // 24 hours
            transaction_hash: [2u8; 32],
            signature: [3u8; 64],
        },
        compliance_manifest: [4u8; 32],
        performance_metrics: ResourceMetrics {
            cpu_utilization: 0.65,
            memory_utilization: 0.70,
            network_bandwidth: 10.0,
            latency_95th: 150,
            error_rate: 0.005,
        },
        requested_trust_level: TrustLevel::Radiant,
        timestamp: SystemTime::now()
            .duration_since(UNIX_EPOCH)?
            .as_micros() as u64,
    };
    
    println!("\nSubmitting attestation request...");
    println!("  Requested Trust Level: {:?}", request.requested_trust_level);
    println!("  Stake Amount: {} ZCMK", request.staking_proof.stake_amount);
    println!("  Latency 95th: {}µs", request.performance_metrics.latency_95th);
    
    // Submit attestation
    let response = iqa_engine.submit_attestation(request).await?;
    
    match response.status {
        AttestationStatus::Granted(seal) => {
            println!("\n✓ Attestation GRANTED!");
            println!("  Seal ID: {}", seal.seal_id);
            println!("  Trust Level: {:?}", seal.trust_level);
            println!("  Staking Tier: {:?}", seal.staking_tier);
            println!("  Issued At: {} (epoch)", seal.issuance_epoch);
            println!("  Expires At: {} (epoch)", seal.expiration_epoch);
            println!("  Processing Latency: {}µs", response.latency);
            
            // Verify the seal
            let verification = seal.verify(&iqa_engine.verifying_key);
            println!("  Seal Verification: {:?}", verification);
            
            // Start vitality monitoring
            println!("\nStarting vitality monitoring...");
            println!("  Frequency: {}Hz", response.vitality_requirements.monitoring_frequency);
            println!("  Minimum Homeostasis: {:.0}%", response.vitality_requirements.minimum_homeostasis * 100.0);
            
            // Simulate a vitality pulse
            let pulse = VitalityPulse {
                seal_id: seal.seal_id,
                source_aid: aid,
                pulse_number: 1,
                homeostasis_score: 0.85,
                resource_metrics: ResourceMetrics {
                    cpu_utilization: 0.70,
                    memory_utilization: 0.75,
                    network_bandwidth: 9.5,
                    latency_95th: 160,
                    error_rate: 0.008,
                },
                compliance_events: vec![],
                signature: [5u8; 64],
            };
            
            let vitality_result = iqa_engine.vitality_monitor
                .process_vitality_pulse(pulse)
                .await;
            
            println!("  Vitality Status: {:?}", vitality_result.status);
            println!("  Processing Latency: {}µs", vitality_result.latency);
            println!("  Pulse Number: {}", vitality_result.pulse_number);
            println!("  Performance Trend: {:?}", vitality_result.trend);
        }
        AttestationStatus::Denied(reason) => {
            println!("\n✗ Attestation DENIED!");
            println!("  Reason: {:?}", reason);
            
            if let Some(error) = response.error_details {
                println!("  Error Code: {}", error.code);
                println!("  Message: {}", error.message);
                if let Some(details) = error.details {
                    println!("  Details: {}", details);
                }
            }
        }
        AttestationStatus::Pending(requirements) => {
            println!("\n⏳ Attestation PENDING");
            println!("  Requirements: {:?}", requirements);
        }
    }
    
    // Demonstrate revocation
    println!("\n--- Revocation Demonstration ---");
    
    let revocation_result = iqa_engine.revoke_seal(
        123456789,
        RevocationReason::ComplianceViolation,
        25_000, // Slash 50% of 50,000 stake
        7 * 24 * 60 * 60 * 1_000_000, // 7 days quarantine
    ).await;
    
    match revocation_result {
        Ok(_) => println!("✓ Seal revocation successful"),
        Err(e) => println!("✗ Revocation failed: {}", e),
    }
    
    println!("\n====================================");
    println!("RFC-008 Implementation Example Complete");
    println!("Imperial Seal Protocol: ACTIVE");
    println!("Real-Time Attestation: OPERATIONAL");
    println!("Vitality Monitoring: ENABLED");
    
    Ok(())
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::time::{timeout, Duration};
    
    #[tokio::test]
    async fn test_seal_generation() {
        let authority_key = SigningKey::generate(&mut OsRng);
        let aid = [1u8; 32];
        
        let seal = ImperialSeal::generate(
            aid,
            TrustLevel::Active,
            StakingTier::Active,
            &authority_key,
        );
        
        assert_eq!(seal.issued_to, aid);
        assert_eq!(seal.trust_level, TrustLevel::Active);
        assert!(seal.expiration_epoch > seal.issuance_epoch);
    }
    
    #[tokio::test]
    async fn test_seal_verification() {
        let authority_key = SigningKey::generate(&mut OsRng);
        let verifying_key = authority_key.verifying_key();
        let aid = [2u8; 32];
        
        let seal = ImperialSeal::generate(
            aid,
            TrustLevel::Radiant,
            StakingTier::Radiant,
            &authority_key,
        );
        
        let result = seal.verify(&verifying_key);
        assert!(matches!(result, SealVerificationResult::Valid));
    }
    
    #[tokio::test]
    async fn test_vitality_monitoring() {
        let monitor = VitalityMonitor::new(0.7);
        
        let pulse = VitalityPulse {
            seal_id: 999,
            source_aid: [3u8; 32],
            pulse_number: 1,
            homeostasis_score: 0.8,
            resource_metrics: ResourceMetrics {
                cpu_utilization: 0.6,
                memory_utilization: 0.7,
                network_bandwidth: 8.0,
                latency_95th: 180,
                error_rate: 0.01,
            },
            compliance_events: vec![],
            signature: [4u8; 64],
        };
        
        // Test that processing completes within RFC-008 limits
        let result = timeout(
            Duration::from_micros(100), // < 100µs target
            monitor.process_vitality_pulse(pulse)
        ).await;
        
        assert!(result.is_ok(), "Vitality processing must complete within 100µs");
    }
    
    #[tokio::test]
    async fn test_attestation_latency() {
        let iqa_engine = IqaEngine::new();
        let aid = [5u8; 32];
        
        let request = AttestationRequest {
            request_id: 111222333,
            target_aid: aid,
            staking_proof: ZCMKStakeReceipt {
                vault_address: [6u8; 32],
                stake_amount: 20_000,
                lock_period: 24 * 60 * 60 * 1_000_000,
                transaction_hash: [7u8; 32],
                signature: [8u8; 64],
            },
            compliance_manifest: [9u8; 32],
            performance_metrics: ResourceMetrics {
                cpu_utilization: 0.5,
                memory_utilization: 0.6,
                network_bandwidth: 12.0,
                latency_95th: 140,
                error_rate: 0.002,
            },
            requested_trust_level: TrustLevel::Active,
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_micros() as u64,
        };
        
        // Test attestation completes within 1ms (RFC-008 target)
        let result = timeout(
            Duration::from_micros(1000),
            iqa_engine.submit_attestation(request)
        ).await;
        
        assert!(result.is_ok(), "Attestation must complete within 1ms");
    }
    
    #[tokio::test]
    async fn test_revocation_propagation() {
        let iqa_engine = IqaEngine::new();
        let aid = [10u8; 32];
        
        // First, create and attest a node
        let request = AttestationRequest {
            request_id: 444555666,
            target_aid: aid,
            staking_proof: ZCMKStakeReceipt {
                vault_address: [11u8; 32],
                stake_amount: 30_000,
                lock_period: 24 * 60 * 60 * 1_000_000,
                transaction_hash: [12u8; 32],
                signature: [13u8; 64],
            },
            compliance_manifest: [14u8; 32],
            performance_metrics: ResourceMetrics {
                cpu_utilization: 0.4,
                memory_utilization: 0.5,
                network_bandwidth: 15.0,
                latency_95th: 120,
                error_rate: 0.001,
            },
            requested_trust_level: TrustLevel::Radiant,
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_micros() as u64,
        };
        
        let response = iqa_engine.submit_attestation(request).await.unwrap();
        
        if let AttestationStatus::Granted(seal) = response.status {
            // Now revoke the seal and test propagation
            let start = SystemTime::now();
            
            iqa_engine.revoke_seal(
                seal.seal_id,
                RevocationReason::VitalityFailed,
                15_000,
                24 * 60 * 60 * 1_000_000,
            ).await.unwrap();
            
            let elapsed = start.elapsed().unwrap();
            let elapsed_micros = elapsed.as_micros();
            
            // Check that revocation completes within 850µs (RFC-008 target)
            assert!(
                elapsed_micros <= 850,
                "Revocation must propagate within 850µs, took {}µs",
                elapsed_micros
            );
            
            // Verify node is now revoked
            let is_revoked = iqa_engine.is_revoked(&aid).await;
            assert!(is_revoked, "Node should be on revocation list after revocation");
        }
    }
}