lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! Cold Storage Tiering Engine
//!
//! Provides unified lifecycle management across local tiers (Gold/Silver/Bronze)
//! and cloud tiers (Hot/Warm/Cold/Archive). Automatically migrates infrequently
//! accessed data to cost-effective storage tiers based on access patterns.
//!
//! ## Overview
//!
//! The cold storage engine bridges three storage layers:
//!
//! 1. **Local Hot Tier** (NVMe/SSD): Frequently accessed data
//! 2. **Local Cold Tier** (HDD): Infrequently accessed data
//! 3. **Cloud Archive Tier** (S3/Azure/GCS): Rarely accessed, long-term storage
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────┐
//! │                   ColdStorageEngine                         │
//! │              Unified Lifecycle Management                   │
//! ├─────────────────────────────────────────────────────────────┤
//! │         ┌──────────────────┐  ┌──────────────────┐         │
//! │         │   TierManager    │  │ CloudTierManager │         │
//! │         │  (Local Tiers)   │  │ (Cloud Tiers)    │         │
//! │         └──────────────────┘  └──────────────────┘         │
//! ├─────────────────────────────────────────────────────────────┤
//! │         ┌──────────────────┐  ┌──────────────────┐         │
//! │         │ ColdStoragePolicy│  │   ObjectState    │         │
//! │         │ (Transition Rules)│ │ (State Tracking) │         │
//! │         └──────────────────┘  └──────────────────┘         │
//! └─────────────────────────────────────────────────────────────┘
//! ```

use super::tier::{AccessStats, StorageClass, TIER_MANAGER, TierManager};
use crate::cloud::tier::{
    CloudObject, CloudProvider, CloudStorageClass, CloudTierManager, CloudUploadConfig, TierPolicy,
};
use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use alloc::{format, vec};
use lazy_static::lazy_static;
use spin::Mutex;

// ═══════════════════════════════════════════════════════════════════════════════
// UNIFIED STORAGE TIER
// ═══════════════════════════════════════════════════════════════════════════════

/// Unified storage tier encompassing both local and cloud tiers.
/// Provides a single abstraction for data placement across all available storage.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum UnifiedTier {
    /// Local NVMe/DRAM - fastest, most expensive (TIER 0)
    LocalGold,
    /// Local SSD - fast, moderate cost (TIER 1)
    LocalSilver,
    /// Local HDD - slow, cheap (TIER 2)
    LocalBronze,
    /// Cloud hot storage - S3 Standard, Azure Hot (TIER 3)
    CloudHot,
    /// Cloud warm storage - S3 IA, Azure Cool (TIER 4)
    CloudWarm,
    /// Cloud cold storage - S3 Glacier, Azure Cold (TIER 5)
    CloudCold,
    /// Cloud archive - S3 Deep Archive, Azure Archive (TIER 6)
    CloudArchive,
}

impl UnifiedTier {
    /// Get tier number (0 = fastest, 6 = archive)
    pub fn tier_number(&self) -> u8 {
        match self {
            UnifiedTier::LocalGold => 0,
            UnifiedTier::LocalSilver => 1,
            UnifiedTier::LocalBronze => 2,
            UnifiedTier::CloudHot => 3,
            UnifiedTier::CloudWarm => 4,
            UnifiedTier::CloudCold => 5,
            UnifiedTier::CloudArchive => 6,
        }
    }

    /// Get relative cost factor (higher = more expensive per byte stored)
    pub fn cost_factor(&self) -> f64 {
        match self {
            UnifiedTier::LocalGold => 100.0,   // NVMe: very expensive
            UnifiedTier::LocalSilver => 30.0,  // SSD: expensive
            UnifiedTier::LocalBronze => 10.0,  // HDD: moderate
            UnifiedTier::CloudHot => 5.0,      // Cloud hot: cheaper
            UnifiedTier::CloudWarm => 2.5,     // Cloud warm
            UnifiedTier::CloudCold => 0.5,     // Cloud cold
            UnifiedTier::CloudArchive => 0.02, // Archive: cheapest
        }
    }

    /// Get retrieval latency in seconds
    pub fn retrieval_latency_sec(&self) -> u64 {
        match self {
            UnifiedTier::LocalGold => 0,
            UnifiedTier::LocalSilver => 0,
            UnifiedTier::LocalBronze => 0,
            UnifiedTier::CloudHot => 1,
            UnifiedTier::CloudWarm => 5,
            UnifiedTier::CloudCold => 3600,     // 1 hour
            UnifiedTier::CloudArchive => 43200, // 12 hours
        }
    }

    /// Check if this is a local tier
    pub fn is_local(&self) -> bool {
        matches!(
            self,
            UnifiedTier::LocalGold | UnifiedTier::LocalSilver | UnifiedTier::LocalBronze
        )
    }

    /// Check if this is a cloud tier
    pub fn is_cloud(&self) -> bool {
        !self.is_local()
    }

    /// Convert to local StorageClass if applicable
    pub fn to_local_class(&self) -> Option<StorageClass> {
        match self {
            UnifiedTier::LocalGold => Some(StorageClass::Gold),
            UnifiedTier::LocalSilver => Some(StorageClass::Silver),
            UnifiedTier::LocalBronze => Some(StorageClass::Bronze),
            _ => None,
        }
    }

    /// Convert to CloudStorageClass if applicable
    pub fn to_cloud_class(&self) -> Option<CloudStorageClass> {
        match self {
            UnifiedTier::CloudHot => Some(CloudStorageClass::Hot),
            UnifiedTier::CloudWarm => Some(CloudStorageClass::Warm),
            UnifiedTier::CloudCold => Some(CloudStorageClass::Cold),
            UnifiedTier::CloudArchive => Some(CloudStorageClass::Archive),
            _ => None,
        }
    }

    /// Convert from local StorageClass
    pub fn from_local(class: StorageClass) -> Self {
        match class {
            StorageClass::Gold => UnifiedTier::LocalGold,
            StorageClass::Silver => UnifiedTier::LocalSilver,
            StorageClass::Bronze => UnifiedTier::LocalBronze,
        }
    }

    /// Convert from CloudStorageClass
    pub fn from_cloud(class: CloudStorageClass) -> Self {
        match class {
            CloudStorageClass::Hot => UnifiedTier::CloudHot,
            CloudStorageClass::Warm => UnifiedTier::CloudWarm,
            CloudStorageClass::Cold => UnifiedTier::CloudCold,
            CloudStorageClass::Archive => UnifiedTier::CloudArchive,
        }
    }

    /// Get human-readable name
    pub fn name(&self) -> &'static str {
        match self {
            UnifiedTier::LocalGold => "Local Gold (NVMe)",
            UnifiedTier::LocalSilver => "Local Silver (SSD)",
            UnifiedTier::LocalBronze => "Local Bronze (HDD)",
            UnifiedTier::CloudHot => "Cloud Hot",
            UnifiedTier::CloudWarm => "Cloud Warm",
            UnifiedTier::CloudCold => "Cloud Cold",
            UnifiedTier::CloudArchive => "Cloud Archive",
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// COLD STORAGE POLICY
// ═══════════════════════════════════════════════════════════════════════════════

/// Policy for cold storage transitions.
/// Defines when objects should move between tiers based on age, access, and size.
#[derive(Debug, Clone)]
pub struct ColdStoragePolicy {
    /// Age in days before considering for this tier
    pub age_days: u64,
    /// Target tier for objects matching this policy
    pub target_tier: UnifiedTier,
    /// Maximum access count (objects with more accesses stay on faster tier)
    pub max_access_count: u64,
    /// Minimum object size for this policy (bytes)
    pub min_size: u64,
    /// Maximum object size for this policy (0 = no limit)
    pub max_size: u64,
    /// Priority (higher = evaluated first)
    pub priority: u32,
    /// Policy name for logging
    pub name: String,
    /// Enable LZMA compression when archiving to this tier
    pub use_archive_compression: bool,
}

impl ColdStoragePolicy {
    /// Create a new policy with defaults
    pub fn new(name: &str, age_days: u64, target_tier: UnifiedTier) -> Self {
        Self {
            age_days,
            target_tier,
            max_access_count: u64::MAX,
            min_size: 0,
            max_size: 0,
            priority: 100,
            name: name.to_string(),
            use_archive_compression: target_tier.is_cloud(),
        }
    }

    /// Set maximum access count threshold
    pub fn with_max_access(mut self, count: u64) -> Self {
        self.max_access_count = count;
        self
    }

    /// Set minimum object size
    pub fn with_min_size(mut self, size: u64) -> Self {
        self.min_size = size;
        self
    }

    /// Set maximum object size
    pub fn with_max_size(mut self, size: u64) -> Self {
        self.max_size = size;
        self
    }

    /// Set policy priority
    pub fn with_priority(mut self, priority: u32) -> Self {
        self.priority = priority;
        self
    }

    /// Enable or disable archive compression
    pub fn with_compression(mut self, enable: bool) -> Self {
        self.use_archive_compression = enable;
        self
    }

    /// Check if an object matches this policy
    pub fn matches(&self, age_days: u64, access_count: u64, size: u64) -> bool {
        if age_days < self.age_days {
            return false;
        }
        if access_count > self.max_access_count {
            return false;
        }
        if size < self.min_size {
            return false;
        }
        if self.max_size > 0 && size > self.max_size {
            return false;
        }
        true
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// OBJECT STATE TRACKING
// ═══════════════════════════════════════════════════════════════════════════════

/// State of an object in the cold storage system
#[derive(Debug, Clone)]
pub struct ObjectState {
    /// Object ID
    pub object_id: u64,
    /// Current unified tier
    pub current_tier: UnifiedTier,
    /// Size in bytes
    pub size: u64,
    /// Creation timestamp (ms)
    pub created_at: u64,
    /// Last access timestamp (ms)
    pub last_access: u64,
    /// Total access count
    pub access_count: u64,
    /// Is data compressed with archive compression
    pub archive_compressed: bool,
    /// Cloud object key (if in cloud tier)
    pub cloud_key: Option<String>,
    /// Cloud bucket (if in cloud tier)
    pub cloud_bucket: Option<String>,
    /// Cloud provider (if in cloud tier)
    pub cloud_provider: Option<CloudProvider>,
}

impl ObjectState {
    /// Create new object state
    pub fn new(object_id: u64, size: u64, timestamp: u64) -> Self {
        Self {
            object_id,
            current_tier: UnifiedTier::LocalSilver,
            size,
            created_at: timestamp,
            last_access: timestamp,
            access_count: 0,
            archive_compressed: false,
            cloud_key: None,
            cloud_bucket: None,
            cloud_provider: None,
        }
    }

    /// Calculate age in days
    pub fn age_days(&self, current_time: u64) -> u64 {
        let age_ms = current_time.saturating_sub(self.created_at);
        age_ms / (24 * 3600 * 1000)
    }

    /// Calculate idle time in days since last access
    pub fn idle_days(&self, current_time: u64) -> u64 {
        let idle_ms = current_time.saturating_sub(self.last_access);
        idle_ms / (24 * 3600 * 1000)
    }

    /// Record an access
    pub fn record_access(&mut self, timestamp: u64) {
        self.last_access = timestamp;
        self.access_count += 1;
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// COLD STORAGE ENGINE
// ═══════════════════════════════════════════════════════════════════════════════

lazy_static! {
    /// Global cold storage engine singleton
    pub static ref COLD_STORAGE_ENGINE: Mutex<ColdStorageEngine> =
        Mutex::new(ColdStorageEngine::new());
}

/// Statistics for cold storage operations
#[derive(Debug, Clone, Default)]
pub struct ColdStorageStats {
    /// Total objects tracked
    pub total_objects: u64,
    /// Objects in local tiers
    pub local_objects: u64,
    /// Objects in cloud tiers
    pub cloud_objects: u64,
    /// Total bytes in local storage
    pub local_bytes: u64,
    /// Total bytes in cloud storage
    pub cloud_bytes: u64,
    /// Migrations to colder tiers
    pub migrations_cold: u64,
    /// Migrations to warmer tiers (recalls)
    pub migrations_warm: u64,
    /// Bytes migrated to cloud
    pub bytes_to_cloud: u64,
    /// Bytes recalled from cloud
    pub bytes_from_cloud: u64,
    /// Archive compression savings (bytes)
    pub compression_savings: u64,
    /// Policy evaluations
    pub policy_evaluations: u64,
}

/// Cold storage engine for unified lifecycle management
pub struct ColdStorageEngine {
    /// Object state tracking
    objects: BTreeMap<u64, ObjectState>,
    /// Cold storage policies (sorted by priority)
    policies: Vec<ColdStoragePolicy>,
    /// Cloud tier manager for cloud operations
    cloud_manager: CloudTierManager,
    /// Default cloud provider
    default_provider: CloudProvider,
    /// Default cloud bucket
    default_bucket: String,
    /// Statistics
    stats: ColdStorageStats,
    /// Enable automatic lifecycle processing
    auto_process: bool,
}

impl Default for ColdStorageEngine {
    fn default() -> Self {
        Self::new()
    }
}

impl ColdStorageEngine {
    /// Create a new cold storage engine
    pub fn new() -> Self {
        let mut engine = Self {
            objects: BTreeMap::new(),
            policies: Vec::new(),
            cloud_manager: CloudTierManager::new(),
            default_provider: CloudProvider::AwsS3,
            default_bucket: "lcpfs-archive".to_string(),
            stats: ColdStorageStats::default(),
            auto_process: true,
        };

        // Add default policies
        engine.add_default_policies();

        engine
    }

    /// Add default lifecycle policies
    fn add_default_policies(&mut self) {
        // Local tier transitions
        self.add_policy(
            ColdStoragePolicy::new("local-warm", 7, UnifiedTier::LocalSilver)
                .with_max_access(10)
                .with_priority(200),
        );

        self.add_policy(
            ColdStoragePolicy::new("local-cold", 30, UnifiedTier::LocalBronze)
                .with_max_access(5)
                .with_priority(150),
        );

        // Cloud tier transitions
        self.add_policy(
            ColdStoragePolicy::new("cloud-hot", 60, UnifiedTier::CloudHot)
                .with_max_access(3)
                .with_min_size(1024 * 1024) // 1 MB minimum for cloud
                .with_priority(100),
        );

        self.add_policy(
            ColdStoragePolicy::new("cloud-warm", 90, UnifiedTier::CloudWarm)
                .with_max_access(2)
                .with_min_size(1024 * 1024)
                .with_priority(80),
        );

        self.add_policy(
            ColdStoragePolicy::new("cloud-cold", 180, UnifiedTier::CloudCold)
                .with_max_access(1)
                .with_min_size(1024 * 1024)
                .with_priority(60),
        );

        self.add_policy(
            ColdStoragePolicy::new("cloud-archive", 365, UnifiedTier::CloudArchive)
                .with_max_access(0)
                .with_min_size(1024 * 1024)
                .with_compression(true)
                .with_priority(40),
        );
    }

    /// Configure default cloud provider
    pub fn set_cloud_provider(&mut self, provider: CloudProvider, bucket: &str) {
        self.default_provider = provider;
        self.default_bucket = bucket.to_string();
    }

    /// Add a cold storage policy
    pub fn add_policy(&mut self, policy: ColdStoragePolicy) {
        self.policies.push(policy);
        // Sort by priority (highest first)
        self.policies.sort_by(|a, b| b.priority.cmp(&a.priority));
    }

    /// Clear all policies
    pub fn clear_policies(&mut self) {
        self.policies.clear();
    }

    /// Register an object for lifecycle management
    pub fn register_object(&mut self, object_id: u64, size: u64, timestamp: u64) {
        let state = ObjectState::new(object_id, size, timestamp);
        self.objects.insert(object_id, state);
        self.stats.total_objects += 1;
        self.stats.local_objects += 1;
        self.stats.local_bytes += size;
    }

    /// Record an access to an object
    pub fn record_access(&mut self, object_id: u64, timestamp: u64) {
        if let Some(state) = self.objects.get_mut(&object_id) {
            state.record_access(timestamp);

            // Also record in local tier manager
            TIER_MANAGER
                .lock()
                .record_access(object_id, false, timestamp, state.size);
        }
    }

    /// Get object state
    pub fn get_object(&self, object_id: u64) -> Option<&ObjectState> {
        self.objects.get(&object_id)
    }

    /// Get current tier for an object
    pub fn get_tier(&self, object_id: u64) -> Option<UnifiedTier> {
        self.objects.get(&object_id).map(|s| s.current_tier)
    }

    /// Process lifecycle for all objects
    pub fn process_lifecycle(&mut self, current_time: u64) {
        let mut migrations: Vec<(u64, UnifiedTier, bool)> = Vec::new();

        // Evaluate each object against policies
        for (object_id, state) in &self.objects {
            self.stats.policy_evaluations += 1;

            let age_days = state.age_days(current_time);

            // Find matching policy
            for policy in &self.policies {
                if policy.matches(age_days, state.access_count, state.size) {
                    // Only migrate if moving to a different tier
                    if policy.target_tier != state.current_tier {
                        // Only migrate to colder tiers (higher tier number)
                        if policy.target_tier.tier_number() > state.current_tier.tier_number() {
                            migrations.push((
                                *object_id,
                                policy.target_tier,
                                policy.use_archive_compression,
                            ));
                        }
                    }
                    break; // First matching policy wins
                }
            }
        }

        // Execute migrations
        for (object_id, target_tier, use_compression) in migrations {
            let _ = self.migrate_object(object_id, target_tier, use_compression, current_time);
        }
    }

    /// Migrate an object to a new tier
    pub fn migrate_object(
        &mut self,
        object_id: u64,
        target_tier: UnifiedTier,
        use_compression: bool,
        timestamp: u64,
    ) -> Result<(), &'static str> {
        let state = self
            .objects
            .get(&object_id)
            .ok_or("Object not found")?
            .clone();

        let source_tier = state.current_tier;
        let is_to_cloud =
            target_tier.is_cloud() && (source_tier.is_local() || source_tier.is_cloud());
        let is_from_cloud = source_tier.is_cloud() && target_tier.is_local();

        crate::lcpfs_println!(
            "[ COLD ] Migrating object {} from {} to {}{}",
            object_id,
            source_tier.name(),
            target_tier.name(),
            if use_compression { " (compressed)" } else { "" }
        );

        // Handle local-to-local migration
        if source_tier.is_local() && target_tier.is_local() {
            if let (Some(from), Some(to)) =
                (source_tier.to_local_class(), target_tier.to_local_class())
            {
                // Use TierManager for local migrations
                let decision = super::tier::MigrationDecision::Demote {
                    object_id,
                    from_tier: from,
                    to_tier: to,
                    estimated_benefit: 0.0,
                };
                TIER_MANAGER.lock().execute_migration(&decision, timestamp);
            }
        }

        // Handle local-to-cloud migration
        if source_tier.is_local() && target_tier.is_cloud() {
            let cloud_class = target_tier.to_cloud_class().ok_or("Invalid cloud tier")?;

            let key = format!("objects/{}/{}", object_id / 1000, object_id);

            let config = CloudUploadConfig {
                dataset_id: 0,
                block_offset: object_id,
                size: state.size,
                provider: self.default_provider,
                bucket: self.default_bucket.clone(),
                key: key.clone(),
                storage_class: cloud_class,
            };

            let object = CloudObject::new(config, timestamp);
            self.cloud_manager.upload(object)?;

            // Update stats
            self.stats.local_objects = self.stats.local_objects.saturating_sub(1);
            self.stats.local_bytes = self.stats.local_bytes.saturating_sub(state.size);
            self.stats.cloud_objects += 1;
            self.stats.cloud_bytes += state.size;
            self.stats.bytes_to_cloud += state.size;
            self.stats.migrations_cold += 1;

            // Update object state
            if let Some(obj_state) = self.objects.get_mut(&object_id) {
                obj_state.current_tier = target_tier;
                obj_state.cloud_key = Some(key);
                obj_state.cloud_bucket = Some(self.default_bucket.clone());
                obj_state.cloud_provider = Some(self.default_provider);
                obj_state.archive_compressed = use_compression;
            }
        }

        // Handle cloud-to-cloud migration
        if source_tier.is_cloud() && target_tier.is_cloud() {
            // Use cloud manager's policy system
            self.cloud_manager.apply_policies(timestamp);

            // Update object state
            if let Some(obj_state) = self.objects.get_mut(&object_id) {
                obj_state.current_tier = target_tier;
            }
            self.stats.migrations_cold += 1;
        }

        // Handle cloud-to-local recall
        if source_tier.is_cloud() && target_tier.is_local() {
            // Download from cloud
            if let (Some(bucket), Some(key)) = (&state.cloud_bucket, &state.cloud_key) {
                let _ = (bucket, key); // Would be used for actual download
                self.cloud_manager.download(0, object_id, timestamp)?;
            }

            // Update stats
            self.stats.cloud_objects = self.stats.cloud_objects.saturating_sub(1);
            self.stats.cloud_bytes = self.stats.cloud_bytes.saturating_sub(state.size);
            self.stats.local_objects += 1;
            self.stats.local_bytes += state.size;
            self.stats.bytes_from_cloud += state.size;
            self.stats.migrations_warm += 1;

            // Update object state
            if let Some(obj_state) = self.objects.get_mut(&object_id) {
                obj_state.current_tier = target_tier;
                obj_state.cloud_key = None;
                obj_state.cloud_bucket = None;
                obj_state.cloud_provider = None;
                obj_state.archive_compressed = false;
            }
        }

        Ok(())
    }

    /// Recall an object from cloud to local storage (on-demand)
    pub fn recall_object(
        &mut self,
        object_id: u64,
        target_tier: UnifiedTier,
        timestamp: u64,
    ) -> Result<u64, &'static str> {
        let state = self.objects.get(&object_id).ok_or("Object not found")?;

        if !state.current_tier.is_cloud() {
            return Err("Object not in cloud tier");
        }

        if !target_tier.is_local() {
            return Err("Target must be local tier");
        }

        let latency = state.current_tier.retrieval_latency_sec();

        crate::lcpfs_println!(
            "[ COLD ] Recalling object {} from {} (latency: {}s)",
            object_id,
            state.current_tier.name(),
            latency
        );

        self.migrate_object(object_id, target_tier, false, timestamp)?;

        Ok(latency)
    }

    /// Delete an object from all tiers
    pub fn delete_object(&mut self, object_id: u64) -> Result<(), &'static str> {
        let state = self.objects.remove(&object_id).ok_or("Object not found")?;

        // Delete from cloud if present
        if state.current_tier.is_cloud() {
            let _ = self.cloud_manager.delete(0, object_id);
            self.stats.cloud_objects = self.stats.cloud_objects.saturating_sub(1);
            self.stats.cloud_bytes = self.stats.cloud_bytes.saturating_sub(state.size);
        } else {
            self.stats.local_objects = self.stats.local_objects.saturating_sub(1);
            self.stats.local_bytes = self.stats.local_bytes.saturating_sub(state.size);
        }

        self.stats.total_objects = self.stats.total_objects.saturating_sub(1);

        crate::lcpfs_println!(
            "[ COLD ] Deleted object {} from {}",
            object_id,
            state.current_tier.name()
        );

        Ok(())
    }

    /// Get statistics
    pub fn stats(&self) -> ColdStorageStats {
        self.stats.clone()
    }

    /// Get storage breakdown by tier
    pub fn tier_breakdown(&self) -> BTreeMap<UnifiedTier, (u64, u64)> {
        let mut breakdown: BTreeMap<UnifiedTier, (u64, u64)> = BTreeMap::new();

        for state in self.objects.values() {
            let entry = breakdown.entry(state.current_tier).or_insert((0, 0));
            entry.0 += 1; // count
            entry.1 += state.size; // bytes
        }

        breakdown
    }

    /// Get objects in a specific tier
    pub fn objects_in_tier(&self, tier: UnifiedTier) -> Vec<u64> {
        self.objects
            .iter()
            .filter(|(_, state)| state.current_tier == tier)
            .map(|(id, _)| *id)
            .collect()
    }

    /// Get objects eligible for migration
    pub fn get_migration_candidates(&self, current_time: u64) -> Vec<(u64, UnifiedTier)> {
        let mut candidates = Vec::new();

        for (object_id, state) in &self.objects {
            let age_days = state.age_days(current_time);

            for policy in &self.policies {
                if policy.matches(age_days, state.access_count, state.size) {
                    if policy.target_tier != state.current_tier
                        && policy.target_tier.tier_number() > state.current_tier.tier_number()
                    {
                        candidates.push((*object_id, policy.target_tier));
                    }
                    break;
                }
            }
        }

        candidates
    }

    /// Estimate storage cost savings from current tier distribution
    pub fn estimate_cost_savings(&self) -> f64 {
        let mut current_cost = 0.0;
        let mut all_hot_cost = 0.0;

        for state in self.objects.values() {
            let bytes_gb = state.size as f64 / (1024.0 * 1024.0 * 1024.0);
            current_cost += bytes_gb * state.current_tier.cost_factor();
            all_hot_cost += bytes_gb * UnifiedTier::LocalGold.cost_factor();
        }

        if all_hot_cost > 0.0 {
            (all_hot_cost - current_cost) / all_hot_cost * 100.0
        } else {
            0.0
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// PUBLIC API
// ═══════════════════════════════════════════════════════════════════════════════

/// Register an object for cold storage lifecycle management
pub fn register_object(object_id: u64, size: u64, timestamp: u64) {
    COLD_STORAGE_ENGINE
        .lock()
        .register_object(object_id, size, timestamp);
}

/// Record an access to an object
pub fn record_access(object_id: u64, timestamp: u64) {
    COLD_STORAGE_ENGINE
        .lock()
        .record_access(object_id, timestamp);
}

/// Get current tier for an object
pub fn get_tier(object_id: u64) -> Option<UnifiedTier> {
    COLD_STORAGE_ENGINE.lock().get_tier(object_id)
}

/// Process lifecycle for all objects
pub fn process_lifecycle(current_time: u64) {
    COLD_STORAGE_ENGINE.lock().process_lifecycle(current_time);
}

/// Recall object from cloud to local storage
pub fn recall_object(object_id: u64, timestamp: u64) -> Result<u64, &'static str> {
    COLD_STORAGE_ENGINE
        .lock()
        .recall_object(object_id, UnifiedTier::LocalSilver, timestamp)
}

/// Get cold storage statistics
pub fn stats() -> ColdStorageStats {
    COLD_STORAGE_ENGINE.lock().stats()
}

/// Get tier breakdown (count, bytes) for each tier
pub fn tier_breakdown() -> BTreeMap<UnifiedTier, (u64, u64)> {
    COLD_STORAGE_ENGINE.lock().tier_breakdown()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_unified_tier_ordering() {
        assert!(UnifiedTier::LocalGold.tier_number() < UnifiedTier::LocalSilver.tier_number());
        assert!(UnifiedTier::LocalSilver.tier_number() < UnifiedTier::LocalBronze.tier_number());
        assert!(UnifiedTier::LocalBronze.tier_number() < UnifiedTier::CloudHot.tier_number());
        assert!(UnifiedTier::CloudHot.tier_number() < UnifiedTier::CloudWarm.tier_number());
        assert!(UnifiedTier::CloudWarm.tier_number() < UnifiedTier::CloudCold.tier_number());
        assert!(UnifiedTier::CloudCold.tier_number() < UnifiedTier::CloudArchive.tier_number());
    }

    #[test]
    fn test_unified_tier_cost() {
        assert!(UnifiedTier::LocalGold.cost_factor() > UnifiedTier::LocalSilver.cost_factor());
        assert!(UnifiedTier::LocalSilver.cost_factor() > UnifiedTier::LocalBronze.cost_factor());
        assert!(UnifiedTier::LocalBronze.cost_factor() > UnifiedTier::CloudHot.cost_factor());
        assert!(UnifiedTier::CloudArchive.cost_factor() < UnifiedTier::CloudCold.cost_factor());
    }

    #[test]
    fn test_cold_storage_policy_matching() {
        let policy = ColdStoragePolicy::new("test", 30, UnifiedTier::CloudWarm)
            .with_max_access(5)
            .with_min_size(1024);

        // Too young
        assert!(!policy.matches(29, 3, 2048));

        // Old enough, low access, good size
        assert!(policy.matches(30, 3, 2048));

        // Too many accesses
        assert!(!policy.matches(30, 10, 2048));

        // Too small
        assert!(!policy.matches(30, 3, 512));
    }

    #[test]
    fn test_object_state_age() {
        let state = ObjectState::new(1, 1024, 0);

        // 30 days in milliseconds
        let time_30_days = 30 * 24 * 3600 * 1000;
        assert_eq!(state.age_days(time_30_days), 30);

        // 365 days
        let time_365_days = 365 * 24 * 3600 * 1000;
        assert_eq!(state.age_days(time_365_days), 365);
    }

    #[test]
    fn test_engine_register_and_access() {
        let mut engine = ColdStorageEngine::new();
        engine.clear_policies(); // Clear default policies for test

        engine.register_object(1, 1024, 0);
        assert_eq!(engine.stats.total_objects, 1);
        assert_eq!(engine.stats.local_objects, 1);

        engine.record_access(1, 1000);
        let state = engine.get_object(1).unwrap();
        assert_eq!(state.access_count, 1);
        assert_eq!(state.last_access, 1000);
    }

    #[test]
    fn test_tier_is_local_cloud() {
        assert!(UnifiedTier::LocalGold.is_local());
        assert!(UnifiedTier::LocalSilver.is_local());
        assert!(UnifiedTier::LocalBronze.is_local());
        assert!(!UnifiedTier::CloudHot.is_local());
        assert!(!UnifiedTier::CloudArchive.is_local());

        assert!(!UnifiedTier::LocalGold.is_cloud());
        assert!(UnifiedTier::CloudHot.is_cloud());
        assert!(UnifiedTier::CloudArchive.is_cloud());
    }

    #[test]
    fn test_tier_conversion() {
        assert_eq!(
            UnifiedTier::LocalGold.to_local_class(),
            Some(StorageClass::Gold)
        );
        assert_eq!(
            UnifiedTier::CloudWarm.to_cloud_class(),
            Some(CloudStorageClass::Warm)
        );
        assert_eq!(UnifiedTier::LocalGold.to_cloud_class(), None);
        assert_eq!(UnifiedTier::CloudWarm.to_local_class(), None);
    }

    #[test]
    fn test_engine_tier_breakdown() {
        let mut engine = ColdStorageEngine::new();
        engine.clear_policies();

        engine.register_object(1, 1024, 0);
        engine.register_object(2, 2048, 0);
        engine.register_object(3, 4096, 0);

        let breakdown = engine.tier_breakdown();
        let (count, bytes) = breakdown.get(&UnifiedTier::LocalSilver).unwrap();
        assert_eq!(*count, 3);
        assert_eq!(*bytes, 1024 + 2048 + 4096);
    }

    #[test]
    fn test_cost_savings_estimation() {
        let mut engine = ColdStorageEngine::new();
        engine.clear_policies();

        // Register 1 GB of data
        engine.register_object(1, 1024 * 1024 * 1024, 0);

        // All in LocalSilver - some savings vs LocalGold
        let savings = engine.estimate_cost_savings();
        assert!(savings > 0.0);
        assert!(savings < 100.0);
    }
}