oxigrid 0.1.2

Pure Rust Energy Systems Simulation & Optimization Library
Documentation
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
//! Battery lifecycle marketplace: asset registration, listing, trading,
//! and second-life value assessment.
//!
//! Models the emerging battery swap and secondary-use market where
//! used battery packs (e.g. from EVs) are assessed, valued, and
//! traded for second-life applications such as grid storage.
//!
//! # References
//! - Harper et al., "Recycling lithium-ion batteries from electric vehicles",
//!   Nature, 2019.
//! - Canals Casals et al., "Reused second life batteries for aggregated
//!   demand response services", 2017.

use serde::{Deserialize, Serialize};
use std::fmt;
use std::time::{SystemTime, UNIX_EPOCH};

// ─────────────────────────────────────────────────────────────────────────────
// Error
// ─────────────────────────────────────────────────────────────────────────────

/// Errors from marketplace operations.
#[derive(Debug, Clone, PartialEq)]
pub enum MarketError {
    /// Asset with given ID not found in the marketplace.
    AssetNotFound(u64),
    /// Asset is already listed for sale.
    AlreadyListed(u64),
    /// Asset is not currently listed for sale.
    NotForSale(u64),
}

impl fmt::Display for MarketError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::AssetNotFound(id) => write!(f, "asset {id} not found"),
            Self::AlreadyListed(id) => write!(f, "asset {id} is already listed"),
            Self::NotForSale(id) => write!(f, "asset {id} is not for sale"),
        }
    }
}

impl std::error::Error for MarketError {}

// ─────────────────────────────────────────────────────────────────────────────
// Battery Chemistry
// ─────────────────────────────────────────────────────────────────────────────

/// Electrochemical cell chemistry of the battery asset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BatteryChemistry {
    /// Lithium Nickel Manganese Cobalt Oxide — high energy density EV cells.
    NmcLithiumIon,
    /// Lithium Iron Phosphate — safe, long-cycle-life stationary cells.
    LfpLithiumIron,
    /// Lithium Titanate — extremely fast charge, very long cycle life.
    LtoLithiumTitanate,
    /// Lithium Nickel Cobalt Aluminum Oxide — high energy (Tesla 18650/21700).
    NcaLithiumNickel,
    /// Flooded or sealed lead-acid — lowest cost, lowest energy density.
    LeadAcid,
    /// Sodium-ion — emerging low-cost alternative to lithium-ion.
    SodiumIon,
}

impl BatteryChemistry {
    /// Reference market price for second-life cells \[USD/kWh\].
    ///
    /// Based on 2025 approximate market data; NMC > NCA > LTO > LFP > NaI > PbA.
    pub fn second_life_price_per_kwh(self) -> f64 {
        match self {
            Self::NmcLithiumIon => 150.0,
            Self::LfpLithiumIron => 120.0,
            Self::LtoLithiumTitanate => 200.0,
            Self::NcaLithiumNickel => 160.0,
            Self::LeadAcid => 60.0,
            Self::SodiumIon => 100.0,
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Application
// ─────────────────────────────────────────────────────────────────────────────

/// Primary or intended application of the battery asset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BatteryApplication {
    /// Battery Electric Vehicle or Plug-in Hybrid.
    ElectricVehicle,
    /// Utility-scale or behind-the-meter grid energy storage.
    GridStorage,
    /// Uninterruptible Power Supply / critical backup.
    Ups,
    /// Portable consumer electronics or power tools.
    Portable,
    /// Already operating in a second-life role.
    SecondLife,
}

// ─────────────────────────────────────────────────────────────────────────────
// Lifecycle Events
// ─────────────────────────────────────────────────────────────────────────────

/// Type of lifecycle event recorded for an asset.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LifecycleEventType {
    /// Battery pack manufactured and assembled.
    Manufactured,
    /// Pack sold to first owner (OEM or end-user).
    Sold,
    /// Pack put into first operational use.
    FirstUseStart,
    /// Physical battery swap (module replaced or exchanged).
    SwapEvent,
    /// State-of-health assessment recorded.
    SohAssessment {
        /// Measured SoH at time of assessment \[%\].
        soh_pct: f64,
    },
    /// Pack repurposed for a second-life application.
    SecondLifeStart,
    /// Pack retired and sent for material recycling.
    Recycled,
}

/// A single lifecycle event attached to a battery asset.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatteryLifecycleEvent {
    /// Calendar date of the event as `(year, month, day)`.
    pub timestamp: (usize, usize, usize),
    /// The type of lifecycle event.
    pub event_type: LifecycleEventType,
    /// Monetary value associated with the event \[USD\].
    pub value_usd: f64,
}

// ─────────────────────────────────────────────────────────────────────────────
// Battery Asset
// ─────────────────────────────────────────────────────────────────────────────

/// A battery asset tracked in the marketplace.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatteryAsset {
    /// Unique marketplace asset identifier.
    pub id: u64,
    /// Electrochemical chemistry of the pack.
    pub chemistry: BatteryChemistry,
    /// Factory-rated usable energy capacity \[kWh\].
    pub original_capacity_kwh: f64,
    /// Current usable energy capacity after degradation \[kWh\].
    pub current_capacity_kwh: f64,
    /// State of health — current / original capacity × 100 \[%\].
    pub current_soh_pct: f64,
    /// Equivalent full charge cycles accumulated.
    pub cycle_count: f64,
    /// Calendar age from manufacture date \[years\].
    pub calendar_age_years: f64,
    /// Application the battery was originally designed/sold for.
    pub original_application: BatteryApplication,
    /// Index of the current owner (marketplace participant ID).
    pub current_owner: usize,
    /// Ordered log of lifecycle events.
    pub history: Vec<BatteryLifecycleEvent>,
}

impl BatteryAsset {
    /// Convenience constructor.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        id: u64,
        chemistry: BatteryChemistry,
        original_capacity_kwh: f64,
        current_soh_pct: f64,
        cycle_count: f64,
        calendar_age_years: f64,
        original_application: BatteryApplication,
        owner: usize,
    ) -> Self {
        let current_capacity_kwh = original_capacity_kwh * current_soh_pct / 100.0;
        Self {
            id,
            chemistry,
            original_capacity_kwh,
            current_capacity_kwh,
            current_soh_pct,
            cycle_count,
            calendar_age_years,
            original_application,
            current_owner: owner,
            history: Vec::new(),
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Marketplace Offer
// ─────────────────────────────────────────────────────────────────────────────

/// A listing posted to the battery marketplace.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MarketplaceOffer {
    /// Asset being offered for sale.
    pub asset_id: u64,
    /// Seller's asking price \[USD\].
    pub asking_price_usd: f64,
    /// Applications this asset is suitable for.
    pub application_fit: Vec<BatteryApplication>,
    /// Estimated remaining useful life in a second-life role \[years\].
    pub remaining_useful_life_years: f64,
    /// Seller's guarantee: minimum energy throughput \[kWh\].
    pub warranty_kwh: f64,
}

// ─────────────────────────────────────────────────────────────────────────────
// Civil date helpers
// ─────────────────────────────────────────────────────────────────────────────

/// Convert a count of days since 1970-01-01 (Unix epoch) to a proleptic
/// Gregorian civil date `(year, month, day)`.
///
/// Uses Howard Hinnant's integer-only algorithm which is correct for all
/// positive day offsets and handles the pre-epoch case via signed arithmetic.
fn days_to_civil(days: i64) -> (usize, usize, usize) {
    // Shift epoch from 1970-01-01 to the civil calendar's internal era anchor.
    let z: i64 = days + 719_468;
    // Era: 400-year Gregorian cycle index.
    let era: i64 = if z >= 0 { z } else { z - 146_096 } / 146_097;
    // Day-of-era [0, 146 096].
    let doe: u32 = (z - era * 146_097) as u32;
    // Year-of-era [0, 399].
    let yoe: u32 = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    // Calendar year (may be off by 1 for Jan/Feb — corrected below).
    let mut y: i64 = yoe as i64 + era * 400;
    // Day-of-year within the era-year [0, 365].
    let doy: u32 = doe - (365 * yoe + yoe / 4 - yoe / 100);
    // Month prime [0, 11] (March = 0 in Hinnant's internal calendar).
    let mp: u32 = (5 * doy + 2) / 153;
    // Day [1, 31].
    let d: u32 = doy - (153 * mp + 2) / 5 + 1;
    // Month [1, 12] mapped back to January-start.
    let m: u32 = if mp < 10 { mp + 3 } else { mp - 9 };
    // Adjust year: Jan/Feb belong to the next civil year in Hinnant's system.
    if m <= 2 {
        y += 1;
    }
    (y as usize, m as usize, d as usize)
}

/// Return today's date as `(year, month, day)` using the system clock.
///
/// Falls back to the Unix epoch `(1970, 1, 1)` if the system clock is
/// unavailable or returns a time before the epoch.
fn current_civil_date() -> (usize, usize, usize) {
    let secs: i64 = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs() as i64;
    let days = secs / 86_400;
    days_to_civil(days)
}

// ─────────────────────────────────────────────────────────────────────────────
// Marketplace
// ─────────────────────────────────────────────────────────────────────────────

/// Battery asset marketplace — registration, listing, trading, and analytics.
#[derive(Debug, Default, Clone)]
pub struct BatteryMarketplace {
    /// All registered battery assets (including sold ones).
    assets: Vec<BatteryAsset>,
    /// Active sale listings.
    offers: Vec<MarketplaceOffer>,
    /// Transaction log: `(asset_id, buyer_id, price_usd, soh_pct_at_sale)`.
    transaction_history: Vec<(u64, usize, f64, f64)>,
}

impl BatteryMarketplace {
    /// Create an empty marketplace.
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a new battery asset and return its assigned ID.
    ///
    /// If the asset already has an ID of 0, a new ID is auto-assigned.
    pub fn register_asset(&mut self, mut asset: BatteryAsset) -> u64 {
        // Auto-assign ID = current length + 1 if asset.id == 0
        if asset.id == 0 {
            asset.id = self.assets.len() as u64 + 1;
        }
        let id = asset.id;
        self.assets.push(asset);
        id
    }

    /// List an asset for sale at the given asking price \[USD\].
    ///
    /// Returns an error if the asset is not found or is already listed.
    pub fn list_for_sale(
        &mut self,
        asset_id: u64,
        asking_price_usd: f64,
    ) -> Result<(), MarketError> {
        // Verify asset exists
        let asset = self
            .assets
            .iter()
            .find(|a| a.id == asset_id)
            .ok_or(MarketError::AssetNotFound(asset_id))?;

        // Check not already listed
        if self.offers.iter().any(|o| o.asset_id == asset_id) {
            return Err(MarketError::AlreadyListed(asset_id));
        }

        // Determine application fit based on SoH
        let soh = asset.current_soh_pct;
        let mut fit = Vec::new();
        if soh >= 80.0 {
            fit.push(BatteryApplication::ElectricVehicle);
            fit.push(BatteryApplication::GridStorage);
            fit.push(BatteryApplication::Ups);
        } else if soh >= 70.0 {
            fit.push(BatteryApplication::GridStorage);
            fit.push(BatteryApplication::Ups);
            fit.push(BatteryApplication::SecondLife);
        } else if soh >= 60.0 {
            fit.push(BatteryApplication::Ups);
            fit.push(BatteryApplication::SecondLife);
        } else {
            // Low SoH: only secondary
            fit.push(BatteryApplication::SecondLife);
        }

        // Estimated remaining life: each 1% SoH above 60% ≈ 0.2 years
        let rul_years = ((soh - 60.0).max(0.0) * 0.2).min(15.0);

        // Warranty throughput: current_capacity × remaining_cycles_estimate
        let remaining_cycles = ((soh - 60.0).max(0.0) / 40.0 * 1000.0).max(0.0);
        let warranty_kwh = asset.current_capacity_kwh * remaining_cycles;

        self.offers.push(MarketplaceOffer {
            asset_id,
            asking_price_usd,
            application_fit: fit,
            remaining_useful_life_years: rul_years,
            warranty_kwh,
        });

        Ok(())
    }

    /// Purchase a listed asset on behalf of `buyer_id`.
    ///
    /// Returns the final sale price \[USD\].
    /// Transfers ownership, removes the listing, and logs the transaction.
    pub fn buy_asset(&mut self, asset_id: u64, buyer_id: usize) -> Result<f64, MarketError> {
        // Find and remove the offer
        let offer_idx = self
            .offers
            .iter()
            .position(|o| o.asset_id == asset_id)
            .ok_or(MarketError::NotForSale(asset_id))?;
        let offer = self.offers.remove(offer_idx);

        // Find the asset and transfer ownership
        let asset = self
            .assets
            .iter_mut()
            .find(|a| a.id == asset_id)
            .ok_or(MarketError::AssetNotFound(asset_id))?;

        let soh_at_sale = asset.current_soh_pct;
        asset.current_owner = buyer_id;

        // Log a sale lifecycle event
        asset.history.push(BatteryLifecycleEvent {
            timestamp: current_civil_date(),
            event_type: LifecycleEventType::Sold,
            value_usd: offer.asking_price_usd,
        });

        // Record transaction
        self.transaction_history
            .push((asset_id, buyer_id, offer.asking_price_usd, soh_at_sale));

        Ok(offer.asking_price_usd)
    }

    /// Estimate the second-life market value of a battery asset \[USD\].
    ///
    /// ```text
    /// value = current_capacity_kwh × (soh_pct/100) × price_per_kwh × age_factor
    /// age_factor = max(0.1, 1.0 − calendar_age_years × 0.05)
    /// ```
    pub fn assess_second_life_value(&self, asset: &BatteryAsset) -> f64 {
        let price_per_kwh = asset.chemistry.second_life_price_per_kwh();
        let age_factor = (1.0 - asset.calendar_age_years * 0.05).max(0.1);
        asset.current_capacity_kwh * (asset.current_soh_pct / 100.0) * price_per_kwh * age_factor
    }

    /// Find listings matching an application requirement and minimum SoH.
    pub fn find_matching_offers(
        &self,
        requirement: &BatteryApplication,
        min_soh_pct: f64,
    ) -> Vec<&MarketplaceOffer> {
        self.offers
            .iter()
            .filter(|offer| {
                // Check application fit
                let fits_app = offer.application_fit.contains(requirement);
                // Check asset SoH
                let soh_ok = self
                    .assets
                    .iter()
                    .find(|a| a.id == offer.asset_id)
                    .map(|a| a.current_soh_pct >= min_soh_pct)
                    .unwrap_or(false);
                fits_app && soh_ok
            })
            .collect()
    }

    /// Total USD volume of all completed transactions.
    pub fn total_market_volume_usd(&self) -> f64 {
        self.transaction_history
            .iter()
            .map(|(_, _, price, _)| price)
            .sum()
    }

    /// Average SoH of assets sold in second-life transactions \[%\].
    ///
    /// Returns 0.0 if no transactions have occurred.
    pub fn average_second_life_soh(&self) -> f64 {
        if self.transaction_history.is_empty() {
            return 0.0;
        }
        let total_soh: f64 = self
            .transaction_history
            .iter()
            .map(|(_, _, _, soh)| soh)
            .sum();
        total_soh / self.transaction_history.len() as f64
    }

    /// Number of registered assets.
    pub fn n_assets(&self) -> usize {
        self.assets.len()
    }

    /// Number of active listings.
    pub fn n_listings(&self) -> usize {
        self.offers.len()
    }

    /// Number of completed transactions.
    pub fn n_transactions(&self) -> usize {
        self.transaction_history.len()
    }

    /// Retrieve an asset by ID (read-only).
    pub fn asset(&self, id: u64) -> Option<&BatteryAsset> {
        self.assets.iter().find(|a| a.id == id)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

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

    fn make_nmc_asset(id: u64, soh_pct: f64, age_years: f64, owner: usize) -> BatteryAsset {
        BatteryAsset::new(
            id,
            BatteryChemistry::NmcLithiumIon,
            100.0, // 100 kWh original
            soh_pct,
            500.0, // cycle_count
            age_years,
            BatteryApplication::ElectricVehicle,
            owner,
        )
    }

    // ── Test 1: Register and list ────────────────────────────────────────────

    #[test]
    fn test_register_and_list_asset() {
        let mut mp = BatteryMarketplace::new();
        let asset = make_nmc_asset(1, 82.0, 3.0, 0);
        let id = mp.register_asset(asset);
        assert_eq!(id, 1, "returned id should match asset id");
        assert_eq!(mp.n_assets(), 1);

        mp.list_for_sale(id, 5000.0)
            .expect("list_for_sale should succeed");
        assert_eq!(mp.n_listings(), 1, "one active listing after list_for_sale");
    }

    // ── Test 2: Buy asset — ownership transfer and transaction log ───────────

    #[test]
    fn test_buy_asset_transfers_ownership() {
        let mut mp = BatteryMarketplace::new();
        let asset = make_nmc_asset(42, 78.0, 4.0, 0); // owner = 0
        mp.register_asset(asset);
        mp.list_for_sale(42, 4200.0).expect("list ok");

        let price = mp.buy_asset(42, 7).expect("buy should succeed");
        assert!(
            (price - 4200.0).abs() < 1e-9,
            "price should match asking price"
        );

        // Ownership transferred
        let a = mp.asset(42).expect("asset must still exist");
        assert_eq!(a.current_owner, 7, "owner should be buyer 7");

        // Transaction logged
        assert_eq!(mp.n_transactions(), 1);
        let (aid, buyer, tx_price, _soh) = mp.transaction_history[0];
        assert_eq!(aid, 42);
        assert_eq!(buyer, 7);
        assert!((tx_price - 4200.0).abs() < 1e-9);

        // Listing removed
        assert_eq!(mp.n_listings(), 0);
    }

    // ── Test 3: Second-life value — higher SoH = higher value ───────────────

    #[test]
    fn test_second_life_value_higher_soh_higher_value() {
        let mp = BatteryMarketplace::new();
        let asset_high = make_nmc_asset(1, 90.0, 2.0, 0);
        let asset_low = make_nmc_asset(2, 70.0, 2.0, 0);

        let val_high = mp.assess_second_life_value(&asset_high);
        let val_low = mp.assess_second_life_value(&asset_low);

        assert!(
            val_high > val_low,
            "higher SoH asset ({:.2}) should have higher value than lower SoH ({:.2})",
            val_high,
            val_low
        );
    }

    // ── Test 4: Find matching offers ─────────────────────────────────────────

    #[test]
    fn test_find_matching_offers_filters_correctly() {
        let mut mp = BatteryMarketplace::new();
        // High SoH — fits EV, GridStorage, UPS
        let asset_good = make_nmc_asset(1, 85.0, 2.0, 0);
        // Low SoH — only fits SecondLife
        let asset_poor = make_nmc_asset(2, 55.0, 8.0, 0);

        mp.register_asset(asset_good);
        mp.register_asset(asset_poor);

        mp.list_for_sale(1, 6000.0).expect("list good");
        mp.list_for_sale(2, 1000.0).expect("list poor");

        // Looking for GridStorage with SoH >= 80%
        let matches = mp.find_matching_offers(&BatteryApplication::GridStorage, 80.0);
        assert_eq!(
            matches.len(),
            1,
            "only 1 asset meets GridStorage + SoH 80% requirement"
        );
        assert_eq!(matches[0].asset_id, 1);

        // Looking for SecondLife with SoH >= 50%
        let matches2 = mp.find_matching_offers(&BatteryApplication::SecondLife, 50.0);
        // asset 2 (soh=55%) fits SecondLife; asset 1 (soh=85%) does NOT have SecondLife in fit
        assert!(
            !matches2.is_empty(),
            "at least asset_poor should match SecondLife"
        );
    }

    // ── Test 5: Market volume = sum of transactions ──────────────────────────

    #[test]
    fn test_market_volume_equals_transaction_sum() {
        let mut mp = BatteryMarketplace::new();
        // Register and trade 3 assets
        for i in 1u64..=3 {
            let asset = make_nmc_asset(i, 75.0 + i as f64, 3.0, 0);
            mp.register_asset(asset);
            let price = 1000.0 * i as f64;
            mp.list_for_sale(i, price).expect("list ok");
            mp.buy_asset(i, i as usize + 10).expect("buy ok");
        }

        let expected_volume = 1000.0 + 2000.0 + 3000.0;
        let actual_volume = mp.total_market_volume_usd();
        assert!(
            (actual_volume - expected_volume).abs() < 1e-6,
            "market volume {actual_volume:.2} != expected {expected_volume:.2}"
        );
    }

    // ── Test 6: Already listed error ─────────────────────────────────────────

    #[test]
    fn test_double_listing_returns_error() {
        let mut mp = BatteryMarketplace::new();
        let asset = make_nmc_asset(1, 80.0, 2.0, 0);
        mp.register_asset(asset);
        mp.list_for_sale(1, 5000.0).expect("first listing ok");
        let result = mp.list_for_sale(1, 4500.0);
        assert!(
            matches!(result, Err(MarketError::AlreadyListed(1))),
            "double listing should return AlreadyListed"
        );
    }

    // ── Test 7: Buy unlisted asset returns error ──────────────────────────────

    #[test]
    fn test_buy_unlisted_returns_error() {
        let mut mp = BatteryMarketplace::new();
        let asset = make_nmc_asset(5, 80.0, 2.0, 0);
        mp.register_asset(asset);
        // Not listed for sale
        let result = mp.buy_asset(5, 99);
        assert!(
            matches!(result, Err(MarketError::NotForSale(5))),
            "buying unlisted asset should return NotForSale"
        );
    }

    // ── Test 8: Average second-life SoH ──────────────────────────────────────

    #[test]
    fn test_average_second_life_soh() {
        let mut mp = BatteryMarketplace::new();
        // Two transactions: SoH 80% and 70% → average 75%
        for (id, soh) in [(1u64, 80.0_f64), (2, 70.0)] {
            let asset = make_nmc_asset(id, soh, 3.0, 0);
            mp.register_asset(asset);
            mp.list_for_sale(id, 1000.0).expect("list ok");
            mp.buy_asset(id, 10).expect("buy ok");
        }
        let avg = mp.average_second_life_soh();
        assert!(
            (avg - 75.0).abs() < 1e-6,
            "average SoH should be 75%, got {avg:.4}"
        );
    }

    // ── Test 9: days_to_civil — Unix epoch (day 0 = 1970-01-01) ─────────────

    #[test]
    fn civil_from_days_epoch() {
        // Day 0 must map exactly to 1970-01-01.
        let (y, m, d) = days_to_civil(0);
        assert_eq!((y, m, d), (1970, 1, 1), "epoch day 0 should be 1970-01-01");
    }

    // ── Test 10: days_to_civil — known offset ────────────────────────────────

    #[test]
    fn civil_from_days_known_offset() {
        // 2024-01-01 is 19723 days after 1970-01-01.
        let (y, m, d) = days_to_civil(19723);
        assert_eq!((y, m, d), (2024, 1, 1), "day 19723 should be 2024-01-01");
    }

    // ── Test 11: current_civil_date — sanity bounds ───────────────────────────

    #[test]
    fn current_civil_date_sane() {
        let (y, m, d) = current_civil_date();
        assert!(y >= 1970, "year must be >= 1970, got {y}");
        assert!((1..=12).contains(&m), "month must be 1-12, got {m}");
        assert!((1..=31).contains(&d), "day must be 1-31, got {d}");
    }
}