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
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0
//
// LunaOS Advanced Integration Traits
// Provides interfaces for W_temporal, gravitational indexing, and PI offload.

//! # LunaOS Advanced Integration
//!
//! This module provides trait interfaces for LunaOS-exclusive features that
//! require libluna integration. These features gracefully degrade to no-op
//! implementations when not running on LunaOS.
//!
//! ## Features
//!
//! ### W_temporal (Immutable Audit Ledger)
//!
//! A blockchain-style immutable audit log that records all filesystem operations.
//! Each entry is cryptographically linked to the previous, creating an unalterable
//! chain of custody for all data modifications.
//!
//! **Use cases:**
//! - Compliance (HIPAA, SOX, GDPR audit trails)
//! - Forensics (immutable operation history)
//! - Ransomware detection (anomalous modification patterns)
//!
//! ### Gravitational Indexing
//!
//! AI-based data placement optimization that treats data blocks as having "mass"
//! proportional to their importance. Hot data (high mass) gravitates toward fast
//! storage tiers, while cold data (low mass) sinks toward slower tiers.
//!
//! **Use cases:**
//! - Automatic tiering without explicit policies
//! - Workload-adaptive placement
//! - Energy-efficient storage (cold data to low-power tiers)
//!
//! ### Processing-in-Memory (PI)
//!
//! Offloads computation to memory-side processing units, reducing data movement
//! and CPU load. Especially effective for data-intensive operations like checksums,
//! compression, and pattern matching.
//!
//! **Use cases:**
//! - Near-memory checksums (avoid PCIe bandwidth limits)
//! - In-place compression
//! - Pattern search without CPU intervention
//!
//! ## Integration Pattern
//!
//! LunaOS implements these traits in libluna and registers providers at boot:
//!
//! ```rust,ignore
//! // In libluna initialization:
//! use lcpfs::lcpfs_lunaos::{
//!     register_wtemporal_provider,
//!     register_gravity_provider,
//!     register_pi_provider,
//! };
//!
//! static WTEMPORAL: LiblunaWTemporal = LiblunaWTemporal::new();
//! static GRAVITY: LiblunaGravity = LiblunaGravity::new();
//! static PI: LiblunaPi = LiblunaPi::new();
//!
//! pub fn init() {
//!     register_wtemporal_provider(&WTEMPORAL);
//!     register_gravity_provider(&GRAVITY);
//!     register_pi_provider(&PI);
//! }
//! ```

use alloc::string::String;
use alloc::vec::Vec;

// ═══════════════════════════════════════════════════════════════════════════════
// W_TEMPORAL - IMMUTABLE AUDIT LEDGER
// ═══════════════════════════════════════════════════════════════════════════════

/// W_temporal operation types.
///
/// Each filesystem operation that modifies data or metadata is recorded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum WTemporalOp {
    /// File or object created.
    Create = 0,
    /// Data written to file.
    Write = 1,
    /// File or object deleted.
    Delete = 2,
    /// Attribute set (permissions, times, xattrs).
    SetAttr = 3,
    /// File or directory renamed.
    Rename = 4,
    /// Hard link created.
    Link = 5,
    /// File truncated.
    Truncate = 6,
    /// Snapshot created.
    Snapshot = 7,
    /// Clone created (reflink).
    Clone = 8,
    /// Dataset created.
    DatasetCreate = 9,
    /// Dataset destroyed.
    DatasetDestroy = 10,
    /// Pool imported.
    PoolImport = 11,
    /// Pool exported.
    PoolExport = 12,
    /// Scrub started.
    ScrubStart = 13,
    /// Scrub completed.
    ScrubComplete = 14,
    /// Data repaired by scrub.
    Repair = 15,
}

impl WTemporalOp {
    /// Get the operation name.
    pub const fn name(&self) -> &'static str {
        match self {
            WTemporalOp::Create => "create",
            WTemporalOp::Write => "write",
            WTemporalOp::Delete => "delete",
            WTemporalOp::SetAttr => "setattr",
            WTemporalOp::Rename => "rename",
            WTemporalOp::Link => "link",
            WTemporalOp::Truncate => "truncate",
            WTemporalOp::Snapshot => "snapshot",
            WTemporalOp::Clone => "clone",
            WTemporalOp::DatasetCreate => "dataset_create",
            WTemporalOp::DatasetDestroy => "dataset_destroy",
            WTemporalOp::PoolImport => "pool_import",
            WTemporalOp::PoolExport => "pool_export",
            WTemporalOp::ScrubStart => "scrub_start",
            WTemporalOp::ScrubComplete => "scrub_complete",
            WTemporalOp::Repair => "repair",
        }
    }

    /// Check if this operation modifies data (vs metadata).
    pub const fn modifies_data(&self) -> bool {
        matches!(
            self,
            WTemporalOp::Write | WTemporalOp::Truncate | WTemporalOp::Repair
        )
    }

    /// Convert from u8.
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(WTemporalOp::Create),
            1 => Some(WTemporalOp::Write),
            2 => Some(WTemporalOp::Delete),
            3 => Some(WTemporalOp::SetAttr),
            4 => Some(WTemporalOp::Rename),
            5 => Some(WTemporalOp::Link),
            6 => Some(WTemporalOp::Truncate),
            7 => Some(WTemporalOp::Snapshot),
            8 => Some(WTemporalOp::Clone),
            9 => Some(WTemporalOp::DatasetCreate),
            10 => Some(WTemporalOp::DatasetDestroy),
            11 => Some(WTemporalOp::PoolImport),
            12 => Some(WTemporalOp::PoolExport),
            13 => Some(WTemporalOp::ScrubStart),
            14 => Some(WTemporalOp::ScrubComplete),
            15 => Some(WTemporalOp::Repair),
            _ => None,
        }
    }
}

/// W_temporal hash (256-bit BLAKE3).
///
/// Each entry is identified by its hash, which includes the previous hash
/// to form an immutable chain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct WTemporalHash {
    /// 256-bit hash value.
    pub bytes: [u8; 32],
}

impl WTemporalHash {
    /// Create a new hash from bytes.
    pub const fn new(bytes: [u8; 32]) -> Self {
        Self { bytes }
    }

    /// Create the genesis hash (all zeros).
    pub const fn genesis() -> Self {
        Self { bytes: [0u8; 32] }
    }

    /// Check if this is the genesis hash.
    pub fn is_genesis(&self) -> bool {
        self.bytes == [0u8; 32]
    }

    /// Convert to hex string.
    pub fn to_hex(&self) -> String {
        let mut result = String::with_capacity(64);
        for byte in &self.bytes {
            use core::fmt::Write;
            let _ = write!(result, "{:02x}", byte);
        }
        result
    }
}

/// W_temporal ledger entry.
///
/// Each entry records a single filesystem operation with full context
/// for audit and forensic purposes.
#[derive(Debug, Clone)]
pub struct WTemporalEntry {
    /// Timestamp (nanoseconds since Unix epoch).
    pub timestamp_ns: u64,

    /// Operation type.
    pub operation: WTemporalOp,

    /// Dataset ID (pool-unique).
    pub dataset_id: u64,

    /// Object ID (file/directory within dataset).
    pub object_id: u64,

    /// User ID who performed the operation.
    pub user_id: u64,

    /// Process ID that performed the operation.
    pub process_id: u32,

    /// Hash of the previous entry (forms the chain).
    pub prev_hash: WTemporalHash,

    /// Additional context (file path, old/new values, etc.).
    pub context: Option<String>,

    /// Size of data affected (for write/truncate operations).
    pub data_size: u64,

    /// Offset for write operations.
    pub data_offset: u64,

    /// This entry's hash (computed after serialization).
    pub hash: WTemporalHash,
}

impl WTemporalEntry {
    /// Create a new entry (hash will be computed on record).
    pub fn new(
        operation: WTemporalOp,
        dataset_id: u64,
        object_id: u64,
        user_id: u64,
        prev_hash: WTemporalHash,
    ) -> Self {
        Self {
            timestamp_ns: 0, // Set by provider
            operation,
            dataset_id,
            object_id,
            user_id,
            process_id: 0,
            prev_hash,
            context: None,
            data_size: 0,
            data_offset: 0,
            hash: WTemporalHash::genesis(),
        }
    }

    /// Set the context string.
    pub fn with_context(mut self, context: String) -> Self {
        self.context = Some(context);
        self
    }

    /// Set data size and offset (for write operations).
    pub fn with_data_info(mut self, offset: u64, size: u64) -> Self {
        self.data_offset = offset;
        self.data_size = size;
        self
    }
}

impl Default for WTemporalEntry {
    fn default() -> Self {
        Self::new(WTemporalOp::Create, 0, 0, 0, WTemporalHash::genesis())
    }
}

/// W_temporal error types.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WTemporalError {
    /// Ledger is full (storage exhausted).
    LedgerFull,
    /// Chain integrity violation detected.
    ChainBroken,
    /// Entry not found.
    EntryNotFound,
    /// Invalid entry data.
    InvalidEntry,
    /// Concurrent modification detected.
    ConcurrentModification,
    /// Storage I/O error.
    StorageError,
    /// Provider not available.
    NotAvailable,
}

impl WTemporalError {
    /// Get error description.
    pub const fn description(&self) -> &'static str {
        match self {
            WTemporalError::LedgerFull => "Ledger storage exhausted",
            WTemporalError::ChainBroken => "Chain integrity violation",
            WTemporalError::EntryNotFound => "Entry not found",
            WTemporalError::InvalidEntry => "Invalid entry data",
            WTemporalError::ConcurrentModification => "Concurrent modification",
            WTemporalError::StorageError => "Storage I/O error",
            WTemporalError::NotAvailable => "W_temporal not available",
        }
    }
}

/// W_temporal ledger statistics.
#[derive(Debug, Clone, Default)]
pub struct WTemporalStats {
    /// Total entries in the ledger.
    pub total_entries: u64,
    /// Entries recorded this session.
    pub session_entries: u64,
    /// Chain verifications performed.
    pub verifications: u64,
    /// Chain verification failures.
    pub verification_failures: u64,
    /// Storage used by ledger (bytes).
    pub storage_used: u64,
    /// Hash of the current tip.
    pub tip_hash: WTemporalHash,
}

/// W_temporal ledger provider trait.
///
/// Provides blockchain-style immutable audit logging for all filesystem
/// operations. Each entry is cryptographically chained to the previous,
/// creating an unalterable history.
///
/// # LunaOS Implementation
///
/// ```rust,ignore
/// use lcpfs::lcpfs_lunaos::{
///     WTemporalProvider, WTemporalEntry, WTemporalHash, WTemporalError
/// };
///
/// pub struct LiblunaWTemporal {
///     ledger: Mutex<WTemporalLedger>,
/// }
///
/// impl WTemporalProvider for LiblunaWTemporal {
///     fn record(&self, mut entry: WTemporalEntry) -> Result<WTemporalHash, WTemporalError> {
///         let mut ledger = self.ledger.lock();
///
///         // Set timestamp from monotonic clock
///         entry.timestamp_ns = luna_time::now_ns();
///
///         // Ensure prev_hash matches current tip
///         if entry.prev_hash != ledger.tip_hash() {
///             return Err(WTemporalError::ConcurrentModification);
///         }
///
///         // Compute entry hash: BLAKE3(timestamp || op || dataset || object || prev_hash || ...)
///         let hash = compute_entry_hash(&entry);
///         entry.hash = hash;
///
///         // Persist to append-only ledger storage
///         ledger.append(entry)?;
///
///         Ok(hash)
///     }
///
///     fn verify_chain(&self, tip_hash: &WTemporalHash) -> Result<bool, WTemporalError> {
///         let ledger = self.ledger.lock();
///
///         // Walk chain from tip back to genesis, verifying each hash
///         let mut current = *tip_hash;
///         while !current.is_genesis() {
///             let entry = ledger.get(&current)?;
///             let computed = compute_entry_hash(&entry);
///             if computed != entry.hash {
///                 return Ok(false);
///             }
///             current = entry.prev_hash;
///         }
///
///         Ok(true)
///     }
///
///     fn get_entry(&self, hash: &WTemporalHash) -> Option<WTemporalEntry> {
///         self.ledger.lock().get(hash).ok()
///     }
///
///     fn tip_hash(&self) -> WTemporalHash {
///         self.ledger.lock().tip_hash()
///     }
/// }
/// ```
///
/// # Security Considerations
///
/// - Entries are append-only; once recorded, they cannot be modified
/// - Chain integrity can be verified from any point back to genesis
/// - Timestamps come from a monotonic clock to prevent backdating
/// - Hash algorithm (BLAKE3) is cryptographically secure
pub trait WTemporalProvider: Send + Sync {
    /// Record an operation to the ledger.
    ///
    /// # Arguments
    /// * `entry` - The entry to record (timestamp and hash will be set)
    ///
    /// # Returns
    /// The hash of the recorded entry, or an error.
    fn record(&self, entry: WTemporalEntry) -> Result<WTemporalHash, WTemporalError>;

    /// Verify chain integrity from genesis to the given hash.
    ///
    /// Walks the chain backwards, verifying each entry's hash matches
    /// its computed value and links correctly to its predecessor.
    ///
    /// # Arguments
    /// * `tip_hash` - Hash to verify chain up to
    ///
    /// # Returns
    /// `true` if chain is intact, `false` if corruption detected.
    fn verify_chain(&self, tip_hash: &WTemporalHash) -> Result<bool, WTemporalError>;

    /// Get an entry by its hash.
    ///
    /// # Arguments
    /// * `hash` - Hash of the entry to retrieve
    ///
    /// # Returns
    /// The entry if found.
    fn get_entry(&self, hash: &WTemporalHash) -> Option<WTemporalEntry>;

    /// Get the current tip hash (most recent entry).
    fn tip_hash(&self) -> WTemporalHash;

    /// Get ledger statistics.
    fn statistics(&self) -> WTemporalStats {
        WTemporalStats::default()
    }

    /// Query entries for a specific object.
    ///
    /// # Arguments
    /// * `dataset_id` - Dataset to query
    /// * `object_id` - Object to query
    /// * `limit` - Maximum entries to return
    ///
    /// # Returns
    /// Entries for the object, most recent first.
    fn query_object(
        &self,
        _dataset_id: u64,
        _object_id: u64,
        _limit: usize,
    ) -> Vec<WTemporalEntry> {
        Vec::new()
    }

    /// Query entries in a time range.
    ///
    /// # Arguments
    /// * `start_ns` - Start timestamp (nanoseconds)
    /// * `end_ns` - End timestamp (nanoseconds)
    /// * `limit` - Maximum entries to return
    ///
    /// # Returns
    /// Entries in the time range.
    fn query_time_range(&self, _start_ns: u64, _end_ns: u64, _limit: usize) -> Vec<WTemporalEntry> {
        Vec::new()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// GRAVITATIONAL INDEXING - AI-BASED DATA PLACEMENT
// ═══════════════════════════════════════════════════════════════════════════════

/// Access event for training the gravity model.
#[derive(Debug, Clone)]
pub struct AccessEvent {
    /// Block ID accessed.
    pub block_id: u64,
    /// Timestamp of access (nanoseconds).
    pub timestamp_ns: u64,
    /// Type of access.
    pub access_type: AccessType,
    /// Size of access in bytes.
    pub size: u32,
    /// Latency of access in nanoseconds.
    pub latency_ns: u32,
}

/// Access type for gravitational model.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum AccessType {
    /// Sequential read.
    SequentialRead = 0,
    /// Random read.
    RandomRead = 1,
    /// Sequential write.
    SequentialWrite = 2,
    /// Random write.
    RandomWrite = 3,
    /// Metadata access.
    Metadata = 4,
    /// Prefetch (speculative).
    Prefetch = 5,
}

impl AccessType {
    /// Check if this is a read operation.
    pub const fn is_read(&self) -> bool {
        matches!(
            self,
            AccessType::SequentialRead | AccessType::RandomRead | AccessType::Prefetch
        )
    }

    /// Check if this is a write operation.
    pub const fn is_write(&self) -> bool {
        matches!(self, AccessType::SequentialWrite | AccessType::RandomWrite)
    }

    /// Check if this is sequential access.
    pub const fn is_sequential(&self) -> bool {
        matches!(
            self,
            AccessType::SequentialRead | AccessType::SequentialWrite
        )
    }
}

/// Storage tier for placement suggestions.
///
/// Mirrors CxlTier but is defined here to avoid circular dependencies.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(u8)]
pub enum StorageTier {
    /// Local DRAM (fastest).
    LocalDram = 0,
    /// Near CXL memory.
    CxlNear = 1,
    /// Far CXL memory.
    CxlFar = 2,
    /// NVMe/SSD storage.
    Nvme = 3,
    /// HDD storage.
    Hdd = 4,
    /// Cloud/archive storage (slowest).
    Cloud = 5,
}

impl StorageTier {
    /// Get the tier name.
    pub const fn name(&self) -> &'static str {
        match self {
            StorageTier::LocalDram => "local_dram",
            StorageTier::CxlNear => "cxl_near",
            StorageTier::CxlFar => "cxl_far",
            StorageTier::Nvme => "nvme",
            StorageTier::Hdd => "hdd",
            StorageTier::Cloud => "cloud",
        }
    }

    /// Get typical latency in nanoseconds.
    pub const fn typical_latency_ns(&self) -> u64 {
        match self {
            StorageTier::LocalDram => 100,
            StorageTier::CxlNear => 300,
            StorageTier::CxlFar => 1000,
            StorageTier::Nvme => 10_000,
            StorageTier::Hdd => 5_000_000,
            StorageTier::Cloud => 50_000_000,
        }
    }
}

/// Placement suggestion from the gravity model.
#[derive(Debug, Clone)]
pub struct PlacementSuggestion {
    /// Suggested storage tier.
    pub tier: StorageTier,
    /// Priority for migration (0.0-1.0, higher = more urgent).
    pub priority: f64,
    /// Confidence in this suggestion (0.0-1.0).
    pub confidence: f64,
    /// Estimated benefit of migration (latency reduction in ns).
    pub estimated_benefit_ns: u64,
    /// Estimated cost of migration (bytes to move).
    pub migration_cost_bytes: u64,
}

impl PlacementSuggestion {
    /// Create a default suggestion (stay in current tier).
    pub fn stay_put() -> Self {
        Self {
            tier: StorageTier::Nvme,
            priority: 0.0,
            confidence: 1.0,
            estimated_benefit_ns: 0,
            migration_cost_bytes: 0,
        }
    }

    /// Check if migration is recommended.
    pub fn should_migrate(&self) -> bool {
        self.priority > 0.5 && self.confidence > 0.7
    }
}

impl Default for PlacementSuggestion {
    fn default() -> Self {
        Self::stay_put()
    }
}

/// Gravity model statistics.
#[derive(Debug, Clone, Default)]
pub struct GravityStats {
    /// Total blocks tracked.
    pub blocks_tracked: u64,
    /// Access events processed.
    pub events_processed: u64,
    /// Training iterations completed.
    pub training_iterations: u64,
    /// Successful placement predictions.
    pub predictions_correct: u64,
    /// Total placement predictions.
    pub predictions_total: u64,
    /// Migrations triggered by gravity.
    pub migrations_triggered: u64,
    /// Bytes migrated.
    pub bytes_migrated: u64,
}

impl GravityStats {
    /// Calculate prediction accuracy.
    pub fn accuracy(&self) -> f64 {
        if self.predictions_total == 0 {
            return 0.0;
        }
        self.predictions_correct as f64 / self.predictions_total as f64
    }
}

/// Gravitational indexing provider trait.
///
/// Uses AI/ML to optimize data placement based on access patterns.
/// Data blocks are assigned a "mass" based on their importance, and
/// the system gravitates hot data toward fast storage while cold data
/// sinks toward slow storage.
///
/// # LunaOS Implementation
///
/// ```rust,ignore
/// use lcpfs::lcpfs_lunaos::{
///     GravityProvider, AccessEvent, PlacementSuggestion, StorageTier
/// };
///
/// pub struct LiblunaGravity {
///     model: Mutex<GravityModel>,
///     block_masses: RwLock<HashMap<u64, f64>>,
/// }
///
/// impl GravityProvider for LiblunaGravity {
///     fn calculate_mass(&self, block_id: u64, access_history: &[AccessEvent]) -> f64 {
///         // Mass formula combines:
///         // 1. Access frequency (more accesses = higher mass)
///         // 2. Recency (recent accesses weighted more heavily)
///         // 3. Access type (random reads weighted higher than sequential)
///         // 4. Temporal patterns (repeated patterns = higher mass)
///
///         let mut mass = 0.0;
///         let now = luna_time::now_ns();
///
///         for event in access_history {
///             // Exponential decay based on age
///             let age_ns = now.saturating_sub(event.timestamp_ns);
///             let decay = (-age_ns as f64 / HALF_LIFE_NS).exp();
///
///             // Weight by access type
///             let type_weight = match event.access_type {
///                 AccessType::RandomRead => 1.0,
///                 AccessType::SequentialRead => 0.3,
///                 AccessType::RandomWrite => 0.8,
///                 AccessType::SequentialWrite => 0.2,
///                 _ => 0.1,
///             };
///
///             mass += decay * type_weight;
///         }
///
///         // Apply neural network for pattern detection
///         mass *= self.model.lock().predict_importance(block_id, access_history);
///
///         mass
///     }
///
///     fn suggest_placement(&self, block_id: u64, mass: f64) -> PlacementSuggestion {
///         // Map mass to tier using learned thresholds
///         let tier = if mass > self.hot_threshold {
///             StorageTier::LocalDram
///         } else if mass > self.warm_threshold {
///             StorageTier::CxlNear
///         } else if mass > self.cool_threshold {
///             StorageTier::Nvme
///         } else {
///             StorageTier::Cloud
///         };
///
///         PlacementSuggestion {
///             tier,
///             priority: mass.min(1.0),
///             confidence: 0.9,
///             ..Default::default()
///         }
///     }
///
///     fn train(&self, events: &[AccessEvent]) {
///         self.model.lock().train_batch(events);
///     }
/// }
/// ```
///
/// # Mass Dynamics
///
/// Block mass follows gravitational dynamics:
/// - Mass increases with access frequency and recency
/// - Mass decays exponentially over time (half-life ~1 hour)
/// - High-mass blocks "fall" toward fast storage
/// - Low-mass blocks "float" toward slow storage
/// - Migration is triggered when mass crosses tier thresholds
pub trait GravityProvider: Send + Sync {
    /// Calculate the "mass" (importance) of a block.
    ///
    /// Mass determines where the block should be placed in the storage
    /// hierarchy. Higher mass = faster storage tier.
    ///
    /// # Arguments
    /// * `block_id` - Block to calculate mass for
    /// * `access_history` - Recent access events for this block
    ///
    /// # Returns
    /// Mass value (typically 0.0-10.0, but unbounded).
    fn calculate_mass(&self, block_id: u64, access_history: &[AccessEvent]) -> f64;

    /// Suggest optimal placement for a block.
    ///
    /// # Arguments
    /// * `block_id` - Block to place
    /// * `mass` - Current mass of the block
    ///
    /// # Returns
    /// Placement suggestion with tier and priority.
    fn suggest_placement(&self, block_id: u64, mass: f64) -> PlacementSuggestion;

    /// Train the gravity model on new access patterns.
    ///
    /// Should be called periodically with batches of access events.
    ///
    /// # Arguments
    /// * `events` - Access events to learn from
    fn train(&self, events: &[AccessEvent]);

    /// Get the current mass of a block (if tracked).
    fn get_mass(&self, _block_id: u64) -> Option<f64> {
        None
    }

    /// Get all blocks above a mass threshold.
    fn get_hot_blocks(&self, _min_mass: f64, _limit: usize) -> Vec<(u64, f64)> {
        Vec::new()
    }

    /// Get all blocks below a mass threshold.
    fn get_cold_blocks(&self, _max_mass: f64, _limit: usize) -> Vec<(u64, f64)> {
        Vec::new()
    }

    /// Get model statistics.
    fn statistics(&self) -> GravityStats {
        GravityStats::default()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// PROCESSING-IN-MEMORY (PI) - NEAR-MEMORY COMPUTE
// ═══════════════════════════════════════════════════════════════════════════════

/// PI operation types that can be offloaded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum PiOperation {
    /// BLAKE3 checksum computation.
    Checksum = 0,
    /// LZ4 compression.
    CompressLz4 = 1,
    /// LZ4 decompression.
    DecompressLz4 = 2,
    /// ZSTD compression.
    CompressZstd = 3,
    /// ZSTD decompression.
    DecompressZstd = 4,
    /// Pattern search (memchr-style).
    PatternSearch = 5,
    /// Memory copy.
    MemCopy = 6,
    /// Memory compare.
    MemCompare = 7,
    /// Aggregate sum (for analytics).
    AggregateSum = 8,
    /// Aggregate count (for analytics).
    AggregateCount = 9,
    /// XOR parity computation (for RAID).
    XorParity = 10,
    /// Encryption (ChaCha20-Poly1305).
    Encrypt = 11,
    /// Decryption (ChaCha20-Poly1305).
    Decrypt = 12,
}

impl PiOperation {
    /// Get operation name.
    pub const fn name(&self) -> &'static str {
        match self {
            PiOperation::Checksum => "checksum",
            PiOperation::CompressLz4 => "compress_lz4",
            PiOperation::DecompressLz4 => "decompress_lz4",
            PiOperation::CompressZstd => "compress_zstd",
            PiOperation::DecompressZstd => "decompress_zstd",
            PiOperation::PatternSearch => "pattern_search",
            PiOperation::MemCopy => "memcpy",
            PiOperation::MemCompare => "memcmp",
            PiOperation::AggregateSum => "aggregate_sum",
            PiOperation::AggregateCount => "aggregate_count",
            PiOperation::XorParity => "xor_parity",
            PiOperation::Encrypt => "encrypt",
            PiOperation::Decrypt => "decrypt",
        }
    }

    /// Check if this operation reads data.
    pub const fn reads_data(&self) -> bool {
        true // All operations read
    }

    /// Check if this operation writes data.
    pub const fn writes_data(&self) -> bool {
        matches!(
            self,
            PiOperation::CompressLz4
                | PiOperation::DecompressLz4
                | PiOperation::CompressZstd
                | PiOperation::DecompressZstd
                | PiOperation::MemCopy
                | PiOperation::XorParity
                | PiOperation::Encrypt
                | PiOperation::Decrypt
        )
    }
}

/// PI operation result.
#[derive(Debug, Clone)]
pub struct PiResult {
    /// Operation that was performed.
    pub operation: PiOperation,
    /// Success status.
    pub success: bool,
    /// Result value (interpretation depends on operation).
    ///
    /// - Checksum: 64-bit hash (lower bits)
    /// - Compress: Output size
    /// - Search: Match offset (-1 if not found)
    /// - Aggregate: Result value
    /// - Compare: 0 if equal, -1/1 for less/greater
    pub result_value: i64,
    /// Execution time in nanoseconds.
    pub execution_time_ns: u64,
    /// Bytes processed.
    pub bytes_processed: u64,
}

impl PiResult {
    /// Create a success result.
    pub fn success(operation: PiOperation, result_value: i64) -> Self {
        Self {
            operation,
            success: true,
            result_value,
            execution_time_ns: 0,
            bytes_processed: 0,
        }
    }

    /// Create a failure result.
    pub fn failure(operation: PiOperation) -> Self {
        Self {
            operation,
            success: false,
            result_value: 0,
            execution_time_ns: 0,
            bytes_processed: 0,
        }
    }
}

impl Default for PiResult {
    fn default() -> Self {
        Self::failure(PiOperation::Checksum)
    }
}

/// PI error types.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PiError {
    /// Operation not supported by hardware.
    NotSupported,
    /// Invalid memory address.
    InvalidAddress,
    /// Memory not accessible to PI unit.
    MemoryNotAccessible,
    /// Operation timed out.
    Timeout,
    /// Hardware error.
    HardwareError,
    /// PI unit is busy.
    Busy,
    /// PI not available.
    NotAvailable,
}

impl PiError {
    /// Get error description.
    pub const fn description(&self) -> &'static str {
        match self {
            PiError::NotSupported => "Operation not supported",
            PiError::InvalidAddress => "Invalid memory address",
            PiError::MemoryNotAccessible => "Memory not accessible to PI unit",
            PiError::Timeout => "Operation timed out",
            PiError::HardwareError => "PI hardware error",
            PiError::Busy => "PI unit busy",
            PiError::NotAvailable => "PI not available",
        }
    }
}

/// PI hardware capabilities.
#[derive(Debug, Clone, Default)]
pub struct PiCapabilities {
    /// Checksum computation supported.
    pub checksum: bool,
    /// LZ4 compression supported.
    pub compress_lz4: bool,
    /// ZSTD compression supported.
    pub compress_zstd: bool,
    /// Pattern search supported.
    pub pattern_search: bool,
    /// Memory operations supported.
    pub memory_ops: bool,
    /// Aggregation supported.
    pub aggregation: bool,
    /// XOR parity supported.
    pub xor_parity: bool,
    /// Encryption supported.
    pub encryption: bool,
    /// Maximum data size per operation (bytes).
    pub max_data_size: usize,
    /// Number of PI units available.
    pub unit_count: u32,
    /// Processing bandwidth per unit (MB/s).
    pub bandwidth_mbps: u32,
}

impl PiCapabilities {
    /// Check if an operation is supported.
    pub fn supports(&self, op: PiOperation) -> bool {
        match op {
            PiOperation::Checksum => self.checksum,
            PiOperation::CompressLz4 | PiOperation::DecompressLz4 => self.compress_lz4,
            PiOperation::CompressZstd | PiOperation::DecompressZstd => self.compress_zstd,
            PiOperation::PatternSearch => self.pattern_search,
            PiOperation::MemCopy | PiOperation::MemCompare => self.memory_ops,
            PiOperation::AggregateSum | PiOperation::AggregateCount => self.aggregation,
            PiOperation::XorParity => self.xor_parity,
            PiOperation::Encrypt | PiOperation::Decrypt => self.encryption,
        }
    }
}

/// PI statistics.
#[derive(Debug, Clone, Default)]
pub struct PiStats {
    /// Operations executed.
    pub ops_executed: u64,
    /// Operations that fell back to CPU.
    pub ops_fallback: u64,
    /// Bytes processed.
    pub bytes_processed: u64,
    /// Total execution time (nanoseconds).
    pub execution_time_ns: u64,
    /// CPU cycles saved (estimated).
    pub cycles_saved: u64,
    /// Energy saved (estimated, microjoules).
    pub energy_saved_uj: u64,
}

impl PiStats {
    /// Calculate offload ratio.
    pub fn offload_ratio(&self) -> f64 {
        let total = self.ops_executed + self.ops_fallback;
        if total == 0 {
            return 0.0;
        }
        self.ops_executed as f64 / total as f64
    }

    /// Calculate throughput in MB/s.
    pub fn throughput_mbps(&self) -> f64 {
        if self.execution_time_ns == 0 {
            return 0.0;
        }
        (self.bytes_processed as f64 / 1_000_000.0)
            / (self.execution_time_ns as f64 / 1_000_000_000.0)
    }
}

/// Processing-in-Memory provider trait.
///
/// Offloads computation to memory-side processing units, reducing data
/// movement and CPU load. Especially effective for operations that would
/// otherwise require moving large amounts of data to the CPU.
///
/// # LunaOS Implementation
///
/// ```rust,ignore
/// use lcpfs::lcpfs_lunaos::{
///     PiProvider, PiOperation, PiResult, PiError, PiCapabilities
/// };
///
/// pub struct LiblunaPi {
///     units: Vec<PiUnit>,
///     stats: AtomicStats,
/// }
///
/// impl PiProvider for LiblunaPi {
///     fn can_offload(&self, op: PiOperation) -> bool {
///         // Check if operation is supported and data is in PI-accessible memory
///         self.capabilities().supports(op)
///     }
///
///     fn execute(&self, op: PiOperation, data_addr: u64, size: usize)
///         -> Result<PiResult, PiError>
///     {
///         // Find an available PI unit
///         let unit = self.acquire_unit()?;
///
///         // Submit command to PI unit
///         let cmd = PiCommand {
///             op,
///             src_addr: data_addr,
///             size,
///             ..Default::default()
///         };
///
///         // Wait for completion (or poll)
///         let result = unit.execute_sync(cmd)?;
///
///         self.release_unit(unit);
///         Ok(result)
///     }
///
///     fn capabilities(&self) -> PiCapabilities {
///         PiCapabilities {
///             checksum: true,
///             compress_lz4: true,
///             compress_zstd: false, // Not all PI units support ZSTD
///             pattern_search: true,
///             memory_ops: true,
///             aggregation: true,
///             xor_parity: true,
///             encryption: true,
///             max_data_size: 64 * 1024 * 1024, // 64MB per op
///             unit_count: self.units.len() as u32,
///             bandwidth_mbps: 100_000, // 100 GB/s per unit
///         }
///     }
/// }
/// ```
///
/// # Performance Benefits
///
/// - **Bandwidth**: PI operates at memory bandwidth (100+ GB/s)
/// - **Latency**: Avoids PCIe round-trip (saves ~1µs)
/// - **Energy**: ~10x more efficient than CPU for bulk operations
/// - **CPU Offload**: Frees CPU for other work
pub trait PiProvider: Send + Sync {
    /// Check if an operation can be offloaded to PI.
    ///
    /// Returns `true` if the operation is supported by hardware and
    /// the current system state allows offload.
    ///
    /// # Arguments
    /// * `op` - Operation to check
    fn can_offload(&self, op: PiOperation) -> bool;

    /// Execute an operation on PI hardware.
    ///
    /// # Arguments
    /// * `op` - Operation to execute
    /// * `data_addr` - Physical/virtual address of data
    /// * `size` - Size of data in bytes
    ///
    /// # Returns
    /// Operation result or error.
    fn execute(&self, op: PiOperation, data_addr: u64, size: usize) -> Result<PiResult, PiError>;

    /// Execute operation with output buffer.
    ///
    /// For operations like compression that produce output.
    ///
    /// # Arguments
    /// * `op` - Operation to execute
    /// * `src_addr` - Source data address
    /// * `src_size` - Source data size
    /// * `dst_addr` - Destination buffer address
    /// * `dst_size` - Destination buffer size
    ///
    /// # Returns
    /// Result with output size in `result_value`.
    fn execute_with_output(
        &self,
        op: PiOperation,
        src_addr: u64,
        src_size: usize,
        _dst_addr: u64,
        _dst_size: usize,
    ) -> Result<PiResult, PiError> {
        // Default: just execute on source
        self.execute(op, src_addr, src_size)
    }

    /// Get PI hardware capabilities.
    fn capabilities(&self) -> PiCapabilities;

    /// Get PI statistics.
    fn statistics(&self) -> PiStats {
        PiStats::default()
    }

    /// Check if PI hardware is available and initialized.
    fn is_available(&self) -> bool {
        false
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// NO-OP PROVIDERS (FALLBACKS)
// ═══════════════════════════════════════════════════════════════════════════════

/// No-op W_temporal provider.
///
/// Used when W_temporal is not available (non-LunaOS systems).
/// All operations return errors or empty results.
pub struct NoOpWTemporalProvider;

impl NoOpWTemporalProvider {
    /// Create a new no-op provider.
    pub const fn new() -> Self {
        Self
    }
}

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

impl WTemporalProvider for NoOpWTemporalProvider {
    fn record(&self, _entry: WTemporalEntry) -> Result<WTemporalHash, WTemporalError> {
        Err(WTemporalError::NotAvailable)
    }

    fn verify_chain(&self, _tip_hash: &WTemporalHash) -> Result<bool, WTemporalError> {
        Err(WTemporalError::NotAvailable)
    }

    fn get_entry(&self, _hash: &WTemporalHash) -> Option<WTemporalEntry> {
        None
    }

    fn tip_hash(&self) -> WTemporalHash {
        WTemporalHash::genesis()
    }
}

/// Global no-op W_temporal provider.
static NOOP_WTEMPORAL: NoOpWTemporalProvider = NoOpWTemporalProvider::new();

/// No-op gravity provider.
///
/// Used when gravitational indexing is not available.
/// Returns neutral mass values and no migrations.
pub struct NoOpGravityProvider;

impl NoOpGravityProvider {
    /// Create a new no-op provider.
    pub const fn new() -> Self {
        Self
    }
}

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

impl GravityProvider for NoOpGravityProvider {
    fn calculate_mass(&self, _block_id: u64, _access_history: &[AccessEvent]) -> f64 {
        // Return neutral mass
        1.0
    }

    fn suggest_placement(&self, _block_id: u64, _mass: f64) -> PlacementSuggestion {
        // Suggest staying put
        PlacementSuggestion::stay_put()
    }

    fn train(&self, _events: &[AccessEvent]) {
        // No-op
    }
}

/// Global no-op gravity provider.
static NOOP_GRAVITY: NoOpGravityProvider = NoOpGravityProvider::new();

/// No-op PI provider.
///
/// Used when PI hardware is not available.
/// All operations fall back to CPU.
pub struct NoOpPiProvider;

impl NoOpPiProvider {
    /// Create a new no-op provider.
    pub const fn new() -> Self {
        Self
    }
}

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

impl PiProvider for NoOpPiProvider {
    fn can_offload(&self, _op: PiOperation) -> bool {
        false
    }

    fn execute(
        &self,
        _op: PiOperation,
        _data_addr: u64,
        _size: usize,
    ) -> Result<PiResult, PiError> {
        Err(PiError::NotAvailable)
    }

    fn capabilities(&self) -> PiCapabilities {
        PiCapabilities::default()
    }

    fn is_available(&self) -> bool {
        false
    }
}

/// Global no-op PI provider.
static NOOP_PI: NoOpPiProvider = NoOpPiProvider::new();

// ═══════════════════════════════════════════════════════════════════════════════
// GLOBAL PROVIDER REGISTRATION
// ═══════════════════════════════════════════════════════════════════════════════

/// Global W_temporal provider.
static WTEMPORAL_PROVIDER: spin::Once<&'static dyn WTemporalProvider> = spin::Once::new();

/// Global gravity provider.
static GRAVITY_PROVIDER: spin::Once<&'static dyn GravityProvider> = spin::Once::new();

/// Global PI provider.
static PI_PROVIDER: spin::Once<&'static dyn PiProvider> = spin::Once::new();

/// Register the W_temporal provider.
///
/// Should be called once during LunaOS initialization.
///
/// # Arguments
/// * `provider` - The provider to register (must have static lifetime)
///
/// # Example
///
/// ```rust,ignore
/// // In libluna initialization:
/// static WTEMPORAL: LiblunaWTemporal = LiblunaWTemporal::new();
///
/// pub fn init() {
///     lcpfs::lcpfs_lunaos::register_wtemporal_provider(&WTEMPORAL);
/// }
/// ```
pub fn register_wtemporal_provider(provider: &'static dyn WTemporalProvider) {
    WTEMPORAL_PROVIDER.call_once(|| provider);
}

/// Get the registered W_temporal provider.
///
/// Returns the no-op provider if none registered.
pub fn get_wtemporal_provider() -> &'static dyn WTemporalProvider {
    WTEMPORAL_PROVIDER.get().copied().unwrap_or(&NOOP_WTEMPORAL)
}

/// Check if W_temporal is available.
pub fn is_wtemporal_available() -> bool {
    WTEMPORAL_PROVIDER.get().is_some()
}

/// Register the gravity provider.
///
/// Should be called once during LunaOS initialization.
pub fn register_gravity_provider(provider: &'static dyn GravityProvider) {
    GRAVITY_PROVIDER.call_once(|| provider);
}

/// Get the registered gravity provider.
///
/// Returns the no-op provider if none registered.
pub fn get_gravity_provider() -> &'static dyn GravityProvider {
    GRAVITY_PROVIDER.get().copied().unwrap_or(&NOOP_GRAVITY)
}

/// Check if gravitational indexing is available.
pub fn is_gravity_available() -> bool {
    GRAVITY_PROVIDER.get().is_some()
}

/// Register the PI provider.
///
/// Should be called once during LunaOS initialization.
pub fn register_pi_provider(provider: &'static dyn PiProvider) {
    PI_PROVIDER.call_once(|| provider);
}

/// Get the registered PI provider.
///
/// Returns the no-op provider if none registered.
pub fn get_pi_provider() -> &'static dyn PiProvider {
    PI_PROVIDER.get().copied().unwrap_or(&NOOP_PI)
}

/// Check if PI hardware is available.
pub fn is_pi_available() -> bool {
    PI_PROVIDER.get().is_some_and(|p| p.is_available())
}

// ═══════════════════════════════════════════════════════════════════════════════
// CONVENIENCE FUNCTIONS
// ═══════════════════════════════════════════════════════════════════════════════

/// Record an operation to the W_temporal ledger.
///
/// Returns the entry hash, or None if W_temporal is not available.
pub fn record_operation(entry: WTemporalEntry) -> Option<WTemporalHash> {
    if !is_wtemporal_available() {
        return None;
    }
    get_wtemporal_provider().record(entry).ok()
}

/// Calculate block mass using the gravity provider.
pub fn calculate_block_mass(block_id: u64, access_history: &[AccessEvent]) -> f64 {
    get_gravity_provider().calculate_mass(block_id, access_history)
}

/// Get placement suggestion for a block.
pub fn suggest_block_placement(block_id: u64, mass: f64) -> PlacementSuggestion {
    get_gravity_provider().suggest_placement(block_id, mass)
}

/// Execute a PI operation if available, otherwise return error.
pub fn execute_pi_operation(
    op: PiOperation,
    data_addr: u64,
    size: usize,
) -> Result<PiResult, PiError> {
    let provider = get_pi_provider();
    if !provider.can_offload(op) {
        return Err(PiError::NotSupported);
    }
    provider.execute(op, data_addr, size)
}

// ═══════════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════════

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

    #[test]
    fn test_wtemporal_op_properties() {
        assert!(WTemporalOp::Write.modifies_data());
        assert!(!WTemporalOp::Create.modifies_data());
        assert!(!WTemporalOp::Delete.modifies_data());
        assert!(WTemporalOp::Truncate.modifies_data());
        assert!(WTemporalOp::Repair.modifies_data());
    }

    #[test]
    fn test_wtemporal_op_from_u8() {
        assert_eq!(WTemporalOp::from_u8(0), Some(WTemporalOp::Create));
        assert_eq!(WTemporalOp::from_u8(1), Some(WTemporalOp::Write));
        assert_eq!(WTemporalOp::from_u8(255), None);
    }

    #[test]
    fn test_wtemporal_hash() {
        let genesis = WTemporalHash::genesis();
        assert!(genesis.is_genesis());

        let hash = WTemporalHash::new([1u8; 32]);
        assert!(!hash.is_genesis());
        assert_eq!(hash.to_hex().len(), 64);
    }

    #[test]
    fn test_wtemporal_entry_builder() {
        let entry = WTemporalEntry::new(WTemporalOp::Write, 1, 2, 1000, WTemporalHash::genesis())
            .with_context("test.txt".into())
            .with_data_info(0, 1024);

        assert_eq!(entry.operation, WTemporalOp::Write);
        assert_eq!(entry.dataset_id, 1);
        assert_eq!(entry.object_id, 2);
        assert_eq!(entry.user_id, 1000);
        assert_eq!(entry.context, Some("test.txt".into()));
        assert_eq!(entry.data_size, 1024);
    }

    #[test]
    fn test_access_type_properties() {
        assert!(AccessType::SequentialRead.is_read());
        assert!(AccessType::RandomRead.is_read());
        assert!(!AccessType::SequentialWrite.is_read());

        assert!(AccessType::SequentialWrite.is_write());
        assert!(AccessType::RandomWrite.is_write());
        assert!(!AccessType::SequentialRead.is_write());

        assert!(AccessType::SequentialRead.is_sequential());
        assert!(AccessType::SequentialWrite.is_sequential());
        assert!(!AccessType::RandomRead.is_sequential());
    }

    #[test]
    fn test_storage_tier_latency() {
        assert!(
            StorageTier::LocalDram.typical_latency_ns() < StorageTier::CxlNear.typical_latency_ns()
        );
        assert!(
            StorageTier::CxlNear.typical_latency_ns() < StorageTier::CxlFar.typical_latency_ns()
        );
        assert!(StorageTier::CxlFar.typical_latency_ns() < StorageTier::Nvme.typical_latency_ns());
        assert!(StorageTier::Nvme.typical_latency_ns() < StorageTier::Hdd.typical_latency_ns());
        assert!(StorageTier::Hdd.typical_latency_ns() < StorageTier::Cloud.typical_latency_ns());
    }

    #[test]
    fn test_placement_suggestion() {
        let stay = PlacementSuggestion::stay_put();
        assert!(!stay.should_migrate());

        let migrate = PlacementSuggestion {
            tier: StorageTier::LocalDram,
            priority: 0.9,
            confidence: 0.95,
            ..Default::default()
        };
        assert!(migrate.should_migrate());

        let low_confidence = PlacementSuggestion {
            tier: StorageTier::LocalDram,
            priority: 0.9,
            confidence: 0.5,
            ..Default::default()
        };
        assert!(!low_confidence.should_migrate());
    }

    #[test]
    fn test_gravity_stats() {
        let stats = GravityStats {
            predictions_correct: 80,
            predictions_total: 100,
            ..Default::default()
        };
        assert!((stats.accuracy() - 0.8).abs() < 0.01);
    }

    #[test]
    fn test_pi_operation_properties() {
        assert!(PiOperation::CompressLz4.writes_data());
        assert!(PiOperation::Checksum.reads_data());
        assert!(!PiOperation::Checksum.writes_data());
        assert!(PiOperation::MemCopy.writes_data());
    }

    #[test]
    fn test_pi_capabilities() {
        let caps = PiCapabilities {
            checksum: true,
            compress_lz4: true,
            compress_zstd: false,
            ..Default::default()
        };

        assert!(caps.supports(PiOperation::Checksum));
        assert!(caps.supports(PiOperation::CompressLz4));
        assert!(!caps.supports(PiOperation::CompressZstd));
    }

    #[test]
    fn test_pi_stats() {
        let stats = PiStats {
            ops_executed: 90,
            ops_fallback: 10,
            bytes_processed: 1_000_000_000,
            execution_time_ns: 1_000_000_000,
            ..Default::default()
        };

        assert!((stats.offload_ratio() - 0.9).abs() < 0.01);
        assert!((stats.throughput_mbps() - 1000.0).abs() < 1.0);
    }

    #[test]
    fn test_noop_wtemporal_provider() {
        let provider = NoOpWTemporalProvider::new();
        assert!(provider.record(WTemporalEntry::default()).is_err());
        assert!(provider.verify_chain(&WTemporalHash::genesis()).is_err());
        assert!(provider.get_entry(&WTemporalHash::genesis()).is_none());
        assert!(provider.tip_hash().is_genesis());
    }

    #[test]
    fn test_noop_gravity_provider() {
        let provider = NoOpGravityProvider::new();
        let mass = provider.calculate_mass(1, &[]);
        assert!((mass - 1.0).abs() < 0.01);

        let suggestion = provider.suggest_placement(1, 1.0);
        assert!(!suggestion.should_migrate());
    }

    #[test]
    fn test_noop_pi_provider() {
        let provider = NoOpPiProvider::new();
        assert!(!provider.can_offload(PiOperation::Checksum));
        assert!(provider.execute(PiOperation::Checksum, 0, 0).is_err());
        assert!(!provider.is_available());

        let caps = provider.capabilities();
        assert!(!caps.checksum);
    }

    #[test]
    fn test_global_providers_fallback() {
        // Should return no-op providers
        let wtemporal = get_wtemporal_provider();
        assert!(wtemporal.tip_hash().is_genesis());

        let gravity = get_gravity_provider();
        let mass = gravity.calculate_mass(0, &[]);
        assert!((mass - 1.0).abs() < 0.01);

        let pi = get_pi_provider();
        assert!(!pi.is_available());
    }

    #[test]
    fn test_convenience_functions() {
        // Without registration, these should return defaults/errors
        assert!(record_operation(WTemporalEntry::default()).is_none());

        let mass = calculate_block_mass(0, &[]);
        assert!((mass - 1.0).abs() < 0.01);

        let suggestion = suggest_block_placement(0, 1.0);
        assert!(!suggestion.should_migrate());

        assert!(execute_pi_operation(PiOperation::Checksum, 0, 0).is_err());
    }

    #[test]
    fn test_pi_result() {
        let success = PiResult::success(PiOperation::Checksum, 12345);
        assert!(success.success);
        assert_eq!(success.result_value, 12345);

        let failure = PiResult::failure(PiOperation::Checksum);
        assert!(!failure.success);
    }

    #[test]
    fn test_wtemporal_error_descriptions() {
        assert!(!WTemporalError::LedgerFull.description().is_empty());
        assert!(!WTemporalError::ChainBroken.description().is_empty());
        assert!(!WTemporalError::NotAvailable.description().is_empty());
    }

    #[test]
    fn test_pi_error_descriptions() {
        assert!(!PiError::NotSupported.description().is_empty());
        assert!(!PiError::NotAvailable.description().is_empty());
        assert!(!PiError::HardwareError.description().is_empty());
    }
}