/// Demonstration of OnionCoin's Revolutionary Inheritance System
///
/// World's first cryptocurrency with NATIVE inheritance built into the blockchain!
///
/// Features:
/// - Time-locked contracts with progressive unlock
/// - Heartbeat system (proof of life)
/// - Shamir secret sharing (3-of-5)
/// - Anti-scam protections
/// - Dispute resolution

use onioncoin_inheritance::*;
use onioncoin_inheritance::contract::ContractStatus;
use onioncoin_inheritance::unlock::UnlockScheduleType;
use onioncoin_inheritance::recovery::{DisputeReason, Evidence, EvidenceType, ResolutionType, ResolutionAction};

fn main() {
    println!("=== OnionCoin Inheritance System Demo ===\n");

    demo_basic_inheritance();
    println!("\n{}\n", "=".repeat(60));

    demo_progressive_unlock();
    println!("\n{}\n", "=".repeat(60));

    demo_heartbeat_system();
    println!("\n{}\n", "=".repeat(60));

    demo_shamir_secret_sharing();
    println!("\n{}\n", "=".repeat(60));

    demo_dispute_resolution();
    println!("\n{}\n", "=".repeat(60));

    demo_complete_scenario();
}

fn demo_basic_inheritance() {
    println!("📜 BASIC INHERITANCE CONTRACT");
    println!("=============================");

    // Create beneficiaries
    let beneficiaries = vec![
        Beneficiary::new([1u8; 32], 60).unwrap(), // Wife: 60%
        Beneficiary::new([2u8; 32], 40).unwrap(), // Child: 40%
    ];

    // Create contract
    let contract = InheritanceContract::new(
        [0u8; 32],                          // Owner pubkey
        beneficiaries,
        InheritanceConfig::default(),       // 90 days + 30 days grace
        100_000,                            // 100,000 ONC locked
        0,
    ).unwrap();

    println!("Contract Created:");
    println!("  Owner: {:?}...", &contract.owner[0..4]);
    println!("  Locked Amount: {} ONC", contract.locked_amount);
    println!("  Beneficiaries: {}", contract.beneficiaries.len());

    for (i, b) in contract.beneficiaries.iter().enumerate() {
        let amount = b.calculate_amount(contract.locked_amount);
        println!("    {}. {}% = {} ONC", i + 1, b.percentage, amount);
    }

    println!("\nHeartbeat Requirements:");
    println!("  Interval: {} days", contract.config.heartbeat_interval / (24 * 3600));
    println!("  Grace Period: {} days", contract.config.grace_period / (24 * 3600));
    println!("  Total Timeout: {} days", contract.config.total_timeout() / (24 * 3600));

    println!("\n✅ NO OTHER CRYPTO HAS THIS BUILT-IN!");
}

fn demo_progressive_unlock() {
    println!("🔓 PROGRESSIVE UNLOCK (INNOVATIVE!)");
    println!("===================================");

    let beneficiaries = vec![Beneficiary::new([1u8; 32], 100).unwrap()];

    let mut contract = InheritanceContract::new(
        [0u8; 32],
        beneficiaries,
        InheritanceConfig::default(),
        100_000,
        0,
    ).unwrap();

    println!("Why Progressive Unlock?");
    println!("  ❌ Traditional dead man's switch: ALL funds unlock at once");
    println!("  ✅ OnionCoin: Gradual unlock gives owner time to recover!\n");

    // Simulate timeout
    contract.status = ContractStatus::Unlocking;

    // Initialize progressive unlock
    ProgressiveUnlock::initialize(&mut contract, UnlockScheduleType::Standard).unwrap();

    let schedule = contract.unlock_schedule.as_ref().unwrap();

    println!("Standard 4-Tier Schedule:");
    for tier in &schedule.tiers {
        println!("  Tier {}: Day +{} → Unlock {}%",
            tier.tier,
            tier.days_after_expiry,
            tier.unlock_percentage);
    }

    println!("\nExample Timeline:");
    println!("  Day 0:   Grace period expires");
    println!("  Day 30:  Tier 1 unlocks → 10,000 ONC available (10%)");
    println!("  Day 60:  Tier 2 unlocks → 25,000 ONC more (35% total)");
    println!("  Day 90:  Tier 3 unlocks → 35,000 ONC more (70% total)");
    println!("  Day 120: Tier 4 unlocks → 30,000 ONC more (100% total)");

    println!("\n💡 If owner wakes up from coma on day 50:");
    println!("   Only 35% unlocked, can dispute and recover 65%!");
}

fn demo_heartbeat_system() {
    println!("💓 HEARTBEAT SYSTEM");
    println!("==================");

    let beneficiaries = vec![Beneficiary::new([1u8; 32], 100).unwrap()];

    let mut contract = InheritanceContract::new(
        [0u8; 32],
        beneficiaries,
        InheritanceConfig::default(),
        10000,
        0,
    ).unwrap();

    let mut manager = HeartbeatManager::new();
    manager.register_contract(contract.contract_id, 0);

    println!("How It Works:");
    println!("  1. Owner must 'check in' every 90 days");
    println!("  2. Heartbeat = Send 0.00000001 ONC to yourself");
    println!("  3. Privacy-preserving (no one knows why you sent it)");
    println!("  4. Can do via Tor for extra privacy\n");

    // Simulate heartbeats
    println!("Simulating Owner Activity:");

    // Day 30
    manager.process_heartbeat(&mut contract, 30 * 24 * 3600).unwrap();
    println!("  Day 30: ✓ Heartbeat sent");

    // Day 65
    manager.process_heartbeat(&mut contract, 65 * 24 * 3600).unwrap();
    println!("  Day 65: ✓ Heartbeat sent");

    let stats = manager.get_stats(&contract.contract_id).unwrap();
    println!("\nStatistics:");
    println!("  Total Heartbeats: {}", stats.heartbeat_count);
    println!("  Average Interval: {:.1} days", stats.avg_interval_days);
    println!("  Last Heartbeat: {} days ago",
        (65 * 24 * 3600 - stats.last_heartbeat) / (24 * 3600));

    println!("\n  Recommendation: {}", manager.suggest_frequency(&contract.contract_id).unwrap());

    // Simulate warning
    println!("\nWarning System:");
    let notifications = manager.check_contracts(&[&contract], 65 * 24 * 3600 + 75 * 24 * 3600);

    if !notifications.is_empty() {
        println!("  ⚠️  {}", notifications[0].message);
    }
}

fn demo_shamir_secret_sharing() {
    println!("🔐 SHAMIR SECRET SHARING (3-of-5)");
    println!("=================================");

    println!("Scenario: Split seed phrase among 5 trusted people");
    println!("  Any 3 can recover, but 2 or fewer cannot\n");

    let seed_phrase = b"abandon ability able about above absent absorb abstract absurd abuse access accident";

    // Create 5 guardians
    let guardians = vec![
        [1u8; 32], // Best friend
        [2u8; 32], // Sister
        [3u8; 32], // Lawyer
        [4u8; 32], // Colleague
        [5u8; 32], // Trusted advisor
    ];

    println!("Guardians:");
    let guardian_names = ["Best Friend", "Sister", "Lawyer", "Colleague", "Advisor"];
    for (i, name) in guardian_names.iter().enumerate() {
        println!("  {}. {} ({:?}...)", i + 1, name, &guardians[i][0..4]);
    }

    // Create Shamir scheme
    let mut shamir = ShamirShares::new(3, 5).unwrap();
    let shares = shamir.split_secret(seed_phrase, &guardians).unwrap();

    println!("\n✅ Secret split into 5 shares");
    println!("   Each guardian receives their encrypted share\n");

    // Simulate recovery scenario
    println!("Recovery Scenario:");
    println!("  Owner passed away, beneficiaries contact guardians\n");

    // Only 2 shares - fails
    println!("  Attempt 1: Guardian 1 + Guardian 2 (2 shares)");
    let result = shamir.recover_secret(&shares[0..2]);
    println!("    ❌ Failed: Need minimum 3 shares\n");

    // 3 shares - success!
    println!("  Attempt 2: Guardian 1 + Guardian 3 + Guardian 5 (3 shares)");
    let recovered = shamir.recover_secret(&[shares[0].clone(), shares[2].clone(), shares[4].clone()]).unwrap();
    println!("    ✅ Success: Seed phrase recovered!");

    if recovered == seed_phrase {
        println!("    ✅ Verified: Matches original seed\n");
    }

    println!("Security:");
    println!("  ✅ No single guardian can access funds");
    println!("  ✅ Collusion of 3+ required");
    println!("  ✅ Redundancy: Can lose 2 shares and still recover");
}

fn demo_dispute_resolution() {
    println!("⚖️  DISPUTE RESOLUTION (ANTI-SCAM)");
    println!("=================================");

    let beneficiaries = vec![Beneficiary::new([1u8; 32], 100).unwrap()];

    let mut contract = InheritanceContract::new(
        [0u8; 32],
        beneficiaries,
        InheritanceConfig::default(),
        50000,
        0,
    ).unwrap();

    let mut recovery_manager = RecoveryManager::default();

    println!("Scenario: Owner in hospital, unable to send heartbeat");
    println!("  Grace period expires, unlock starts...\n");

    // Simulate unlock starting
    contract.status = ContractStatus::Unlocking;

    println!("Owner Recovers and Files Dispute:");
    recovery_manager.file_dispute(
        &mut contract,
        [0u8; 32], // Owner
        DisputeReason::TemporaryIncapacitation,
        1000,
    ).unwrap();

    println!("  ✅ Dispute filed successfully");
    println!("  Status: {:?}", contract.status);

    // Add evidence
    let evidence = Evidence {
        evidence_type: EvidenceType::MedicalCertificate,
        data: vec![1, 2, 3], // Encrypted medical cert
        submitted_at: 1100,
    };

    recovery_manager.add_evidence(&contract.contract_id, evidence).unwrap();
    println!("  ✅ Medical certificate submitted\n");

    // Resolve dispute
    println!("Resolution:");
    let resolution = DisputeResolution {
        resolution_type: ResolutionType::ResetHeartbeat,
        actions: vec![ResolutionAction::HeartbeatReset],
        resolved_at: 2000,
        notes: Some("Owner verified alive, medical emergency confirmed".to_string()),
    };

    recovery_manager.resolve_dispute(&mut contract, resolution, 2000).unwrap();

    println!("  ✅ Heartbeat reset");
    println!("  ✅ Contract resumed: {:?}", contract.status);
    println!("  ✅ Funds secure, owner has full control\n");

    println!("Anti-Scam Protection:");
    println!("  ✅ Maximum 3 disputes allowed (prevent abuse)");
    println!("  ✅ 7-day cooldown between disputes");
    println!("  ✅ Evidence required (proof of life)");
    println!("  ✅ Suspicious activity detection");
}

fn demo_complete_scenario() {
    println!("🎬 COMPLETE SCENARIO");
    println!("===================");

    println!("Alice wants to ensure her crypto goes to her family if she dies\n");

    // Step 1: Create contract
    println!("Step 1: Create Inheritance Contract");
    let beneficiaries = vec![
        Beneficiary::new([1u8; 32], 70).unwrap(), // Husband
        Beneficiary::new([2u8; 32], 30).unwrap(), // Daughter
    ];

    let mut contract = InheritanceContract::new(
        [0u8; 32], // Alice
        beneficiaries,
        InheritanceConfig::default(),
        500_000, // 500,000 ONC
        0,
    ).unwrap();

    println!("  ✅ Contract created");
    println!("  ✅ 500,000 ONC locked");
    println!("  ✅ 70% to husband, 30% to daughter\n");

    // Step 2: Optional Shamir shares
    println!("Step 2: Setup Shamir Secret Sharing (Optional)");
    let guardians = vec![
        [10u8; 32],
        [11u8; 32],
        [12u8; 32],
        [13u8; 32],
        [14u8; 32],
    ];

    let distribution = ShareDistribution::standard_3_of_5(guardians).unwrap();
    println!("  ✅ Seed split among 5 trusted guardians");
    println!("  ✅ Any 3 can help family recover\n");

    // Step 3: Regular heartbeats
    println!("Step 3: Alice Sends Regular Heartbeats");
    let mut manager = HeartbeatManager::new();
    manager.register_contract(contract.contract_id, 0);

    for month in 1..=12 {
        let days = month * 30;
        manager.process_heartbeat(&mut contract, days * 24 * 3600).unwrap();
        if month % 3 == 0 {
            println!("  ✓ Month {}: Heartbeat sent", month);
        }
    }
    println!("  ✅ 12 months of regular heartbeats\n");

    // Step 4: Alice passes away (tragic scenario)
    println!("Step 4: Alice Passes Away (Simulation)");
    println!("  Last heartbeat: Month 12");
    println!("  Current time: Month 16 (120 days later)\n");

    let current_time = 16 * 30 * 24 * 3600;

    // Step 5: Grace period expires
    println!("Step 5: System Detects Timeout");
    contract.update_status(current_time);
    println!("  Status: {:?}", contract.status);

    let notifications = manager.check_contracts(&[&contract], current_time);
    println!("  Notifications sent: {}", notifications.len());
    println!("    - Critical warning to Alice (no response)");
    println!("    - Info to beneficiaries (grace period)\n");

    // Step 6: Progressive unlock
    println!("Step 6: Progressive Unlock Begins");
    contract.status = ContractStatus::Unlocking;
    ProgressiveUnlock::initialize(&mut contract, UnlockScheduleType::Standard).unwrap();

    // Simulate tier 1 unlock (30 days after grace expiry)
    let tier1_time = current_time + 30 * 24 * 3600;
    let distributions = ProgressiveUnlock::process(&mut contract, tier1_time).unwrap();

    println!("  Day 30: Tier 1 Unlocks (10%)");
    for dist in &distributions {
        println!("    → {} ONC to beneficiary {:?}...",
            dist.amount,
            &dist.beneficiary[0..4]);
    }

    println!("\n  Husband receives: 35,000 ONC (70% of 50,000)");
    println!("  Daughter receives: 15,000 ONC (30% of 50,000)\n");

    // Step 7: Full unlock
    let final_time = current_time + 120 * 24 * 3600;
    ProgressiveUnlock::process(&mut contract, final_time).unwrap();

    println!("Step 7: Full Unlock Complete (Day 120)");
    println!("  Husband total: 350,000 ONC");
    println!("  Daughter total: 150,000 ONC");
    println!("  Status: {:?}", contract.status);

    println!("\n✅ INHERITANCE SUCCESSFULLY DISTRIBUTED");
    println!("✅ NO LAWYER FEES");
    println!("✅ NO COURT PROCESS");
    println!("✅ FULLY AUTOMATED");
    println!("✅ PRIVACY PRESERVED");

    println!("\n🎉 THIS IS THE FUTURE OF CRYPTO INHERITANCE!");
}
