corp-finance-core 1.1.0

Institutional-grade corporate finance calculations with 128-bit decimal precision — DCF, WACC, comps, LBO, credit metrics, derivatives, fixed income, options, and 60+ specialty modules. No f64 in financials. WASM-compatible.
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
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
//! ABS/MBS cash flow modelling with prepayment and default models.
//!
//! Provides institutional-grade securitization analytics including PSA/CPR/SMM
//! prepayment models, CDR/SDA default models, loss severity, recovery lag,
//! servicing fees, and weighted average life (WAL) computation.

use crate::compat::Instant;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use serde::{Deserialize, Serialize};

use crate::error::CorpFinanceError;
use crate::types::{with_metadata, ComputationOutput, Money, Rate};
use crate::CorpFinanceResult;

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/// Prepayment model specification.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PrepaymentModel {
    /// Constant Prepayment Rate (annual). E.g., 0.06 = 6% CPR.
    Cpr(Rate),
    /// PSA speed. 100 = 100% PSA (ramps to 6% CPR at month 30, then flat).
    Psa(Decimal),
    /// Single Monthly Mortality (already monthly). E.g., 0.005 = 0.5% SMM.
    Smm(Rate),
}

/// Default model specification.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DefaultModel {
    /// Constant Default Rate (annual). E.g., 0.02 = 2% CDR.
    Cdr(Rate),
    /// Standard Default Assumption speed. 100 = 100% SDA.
    Sda(Decimal),
    /// No defaults.
    None,
}

/// Input parameters for ABS/MBS cash flow modelling.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AbsMbsInput {
    /// Initial pool balance (unpaid principal balance).
    pub pool_balance: Money,
    /// Weighted average coupon (e.g., 0.055 = 5.5%).
    pub weighted_avg_coupon: Rate,
    /// Weighted average maturity in months.
    pub weighted_avg_maturity_months: u32,
    /// Weighted average loan age in months (WALA).
    pub weighted_avg_age_months: u32,
    /// Number of loans in pool.
    pub num_loans: u32,
    /// Prepayment model.
    pub prepayment_model: PrepaymentModel,
    /// Default model.
    pub default_model: DefaultModel,
    /// Loss given default (e.g., 0.40 = 40%).
    pub loss_severity: Rate,
    /// Months to recover from defaulted loans.
    pub recovery_lag_months: u32,
    /// Annual servicing fee rate (e.g., 0.0025 = 25bps).
    pub servicing_fee_rate: Rate,
    /// Number of months to project.
    pub projection_months: u32,
}

/// A single period in the ABS/MBS cash flow projection.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AbsPeriod {
    pub month: u32,
    pub beginning_balance: Money,
    pub scheduled_principal: Money,
    pub scheduled_interest: Money,
    pub prepayment: Money,
    pub defaults: Money,
    pub loss: Money,
    pub recovery: Money,
    pub servicing_fee: Money,
    pub total_principal: Money,
    pub total_cashflow: Money,
    pub ending_balance: Money,
    pub smm: Rate,
    pub cpr: Rate,
    pub mdr: Rate,
}

/// Summary statistics for the ABS/MBS projection.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AbsSummary {
    pub total_principal_collected: Money,
    pub total_interest_collected: Money,
    pub total_prepayments: Money,
    pub total_defaults: Money,
    pub total_losses: Money,
    pub total_recoveries: Money,
    pub total_servicing_fees: Money,
    pub weighted_average_life_years: Decimal,
    pub pool_factor_at_end: Rate,
    pub cumulative_loss_rate: Rate,
    pub total_cashflows: Money,
}

/// Complete ABS/MBS cash flow output.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AbsMbsOutput {
    pub periods: Vec<AbsPeriod>,
    pub summary: AbsSummary,
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// PSA base CPR at month 30 (6% annual).
const PSA_BASE_CPR_30: Decimal = dec!(0.06);

/// SDA peak CDR at month 30 (0.6% annual).
const SDA_PEAK_CDR_30: Decimal = dec!(0.006);

/// SDA floor CDR from month 121 onward (0.03% annual).
const SDA_FLOOR_CDR: Decimal = dec!(0.0003);

/// Minimum balance threshold below which the pool is considered fully paid.
const BALANCE_EPSILON: Decimal = dec!(0.01);

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Model ABS/MBS cash flows with prepayment and default projections.
///
/// Projects monthly cash flows for a mortgage or asset-backed securities pool,
/// applying the specified prepayment model (CPR/PSA/SMM), default model
/// (CDR/SDA/None), loss severity, recovery lag, and servicing fees.
pub fn model_abs_cashflows(
    input: &AbsMbsInput,
) -> CorpFinanceResult<ComputationOutput<AbsMbsOutput>> {
    let start = Instant::now();
    let mut warnings: Vec<String> = Vec::new();

    validate_input(input)?;

    let wac_monthly = input.weighted_avg_coupon / dec!(12);
    let mut balance = input.pool_balance;
    let mut remaining_months = input.weighted_avg_maturity_months;

    let mut periods: Vec<AbsPeriod> = Vec::with_capacity(input.projection_months as usize);
    // Track defaults per month for lagged recovery.
    let mut defaults_history: Vec<Money> = Vec::with_capacity(input.projection_months as usize);

    // Accumulators for summary.
    let mut total_principal_collected = Decimal::ZERO;
    let mut total_interest_collected = Decimal::ZERO;
    let mut total_prepayments = Decimal::ZERO;
    let mut total_defaults = Decimal::ZERO;
    let mut total_losses = Decimal::ZERO;
    let mut total_recoveries = Decimal::ZERO;
    let mut total_servicing_fees = Decimal::ZERO;
    let mut total_cashflows = Decimal::ZERO;

    // For WAL computation: sum(t * principal_t).
    let mut wal_numerator = Decimal::ZERO;

    for month_idx in 0..input.projection_months {
        let month = month_idx + 1;
        let age = input.weighted_avg_age_months + month;

        if balance < BALANCE_EPSILON || remaining_months == 0 {
            // Pool is exhausted; emit a zero period.
            let period = zero_period(month, balance);
            defaults_history.push(Decimal::ZERO);
            periods.push(period);
            continue;
        }

        let beginning_balance = balance;

        // --- Prepayment rates ---
        let cpr_annual = compute_cpr(age, &input.prepayment_model);
        let smm = cpr_to_smm(cpr_annual);

        // --- Default rates ---
        let cdr_annual = compute_cdr(age, &input.default_model);
        let mdr = cdr_to_mdr(cdr_annual);

        // --- Scheduled payment (standard level-pay amortisation) ---
        let scheduled_interest = beginning_balance * wac_monthly;

        let scheduled_payment = if wac_monthly > Decimal::ZERO {
            let denom =
                Decimal::ONE - iterative_pow_recip(Decimal::ONE + wac_monthly, remaining_months);
            if denom > Decimal::ZERO {
                beginning_balance * wac_monthly / denom
            } else {
                beginning_balance
            }
        } else {
            // Zero coupon: just return principal evenly.
            beginning_balance / Decimal::from(remaining_months)
        };

        let mut scheduled_principal = scheduled_payment - scheduled_interest;
        // Guard: scheduled principal cannot exceed balance.
        if scheduled_principal > beginning_balance {
            scheduled_principal = beginning_balance;
        }
        if scheduled_principal < Decimal::ZERO {
            scheduled_principal = Decimal::ZERO;
        }

        // --- Prepayment ---
        let prepay_base = beginning_balance - scheduled_principal;
        let prepayment = if prepay_base > Decimal::ZERO {
            prepay_base * smm
        } else {
            Decimal::ZERO
        };

        // --- Defaults ---
        let default_base = beginning_balance - scheduled_principal - prepayment;
        let defaults = if default_base > Decimal::ZERO {
            default_base * mdr
        } else {
            Decimal::ZERO
        };

        // --- Loss and recovery ---
        let loss = defaults * input.loss_severity;

        // Recovery comes from defaults that occurred recovery_lag_months ago.
        let recovery = if input.recovery_lag_months > 0 && month > input.recovery_lag_months {
            let lag_idx = (month - input.recovery_lag_months - 1) as usize;
            if lag_idx < defaults_history.len() {
                defaults_history[lag_idx] * (Decimal::ONE - input.loss_severity)
            } else {
                Decimal::ZERO
            }
        } else if input.recovery_lag_months == 0 {
            defaults * (Decimal::ONE - input.loss_severity)
        } else {
            Decimal::ZERO
        };

        defaults_history.push(defaults);

        // --- Servicing fee ---
        let servicing_fee = beginning_balance * input.servicing_fee_rate / dec!(12);

        // --- Total principal ---
        let total_principal = scheduled_principal + prepayment;

        // --- Total cashflow ---
        let total_cashflow = scheduled_interest + total_principal - servicing_fee + recovery;

        // --- Ending balance ---
        let mut ending_balance = beginning_balance - scheduled_principal - prepayment - defaults;
        if ending_balance < Decimal::ZERO {
            if ending_balance.abs() < BALANCE_EPSILON {
                ending_balance = Decimal::ZERO;
            } else {
                warnings.push(format!(
                    "Month {}: ending balance went negative ({}) — clamped to zero",
                    month, ending_balance
                ));
                ending_balance = Decimal::ZERO;
            }
        }

        // --- Accumulate summary ---
        total_principal_collected += total_principal;
        total_interest_collected += scheduled_interest;
        total_prepayments += prepayment;
        total_defaults += defaults;
        total_losses += loss;
        total_recoveries += recovery;
        total_servicing_fees += servicing_fee;
        total_cashflows += total_cashflow;

        // WAL: weight by month in years.
        wal_numerator += Decimal::from(month) * total_principal / dec!(12);

        periods.push(AbsPeriod {
            month,
            beginning_balance,
            scheduled_principal,
            scheduled_interest,
            prepayment,
            defaults,
            loss,
            recovery,
            servicing_fee,
            total_principal,
            total_cashflow,
            ending_balance,
            smm,
            cpr: cpr_annual,
            mdr,
        });

        balance = ending_balance;
        remaining_months = remaining_months.saturating_sub(1);
    }

    // --- WAL ---
    let weighted_average_life_years = if total_principal_collected > Decimal::ZERO {
        wal_numerator / total_principal_collected
    } else {
        Decimal::ZERO
    };

    // --- Pool factor ---
    let pool_factor_at_end = if input.pool_balance > Decimal::ZERO {
        balance / input.pool_balance
    } else {
        Decimal::ZERO
    };

    // --- Cumulative loss rate ---
    let cumulative_loss_rate = if input.pool_balance > Decimal::ZERO {
        total_losses / input.pool_balance
    } else {
        Decimal::ZERO
    };

    let summary = AbsSummary {
        total_principal_collected,
        total_interest_collected,
        total_prepayments,
        total_defaults,
        total_losses,
        total_recoveries,
        total_servicing_fees,
        weighted_average_life_years,
        pool_factor_at_end,
        cumulative_loss_rate,
        total_cashflows,
    };

    let output = AbsMbsOutput { periods, summary };

    let elapsed = start.elapsed().as_micros() as u64;

    Ok(with_metadata(
        "ABS/MBS Cash Flow Model — Amortisation with prepayment/default/recovery projections",
        input,
        warnings,
        elapsed,
        output,
    ))
}

// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------

fn validate_input(input: &AbsMbsInput) -> CorpFinanceResult<()> {
    if input.pool_balance <= Decimal::ZERO {
        return Err(CorpFinanceError::InvalidInput {
            field: "pool_balance".into(),
            reason: "Pool balance must be positive".into(),
        });
    }
    if input.weighted_avg_coupon < Decimal::ZERO {
        return Err(CorpFinanceError::InvalidInput {
            field: "weighted_avg_coupon".into(),
            reason: "WAC cannot be negative".into(),
        });
    }
    if input.weighted_avg_maturity_months == 0 {
        return Err(CorpFinanceError::InvalidInput {
            field: "weighted_avg_maturity_months".into(),
            reason: "WAM must be greater than zero".into(),
        });
    }
    if input.loss_severity < Decimal::ZERO || input.loss_severity > Decimal::ONE {
        return Err(CorpFinanceError::InvalidInput {
            field: "loss_severity".into(),
            reason: "Loss severity must be between 0 and 1".into(),
        });
    }
    if input.servicing_fee_rate < Decimal::ZERO {
        return Err(CorpFinanceError::InvalidInput {
            field: "servicing_fee_rate".into(),
            reason: "Servicing fee rate cannot be negative".into(),
        });
    }
    if input.projection_months == 0 {
        return Err(CorpFinanceError::InvalidInput {
            field: "projection_months".into(),
            reason: "Projection months must be greater than zero".into(),
        });
    }

    // Validate prepayment model rates.
    match &input.prepayment_model {
        PrepaymentModel::Cpr(rate) => {
            if *rate < Decimal::ZERO || *rate > Decimal::ONE {
                return Err(CorpFinanceError::InvalidInput {
                    field: "prepayment_model.Cpr".into(),
                    reason: "CPR must be between 0 and 1".into(),
                });
            }
        }
        PrepaymentModel::Psa(speed) => {
            if *speed < Decimal::ZERO {
                return Err(CorpFinanceError::InvalidInput {
                    field: "prepayment_model.Psa".into(),
                    reason: "PSA speed must be non-negative".into(),
                });
            }
        }
        PrepaymentModel::Smm(rate) => {
            if *rate < Decimal::ZERO || *rate > Decimal::ONE {
                return Err(CorpFinanceError::InvalidInput {
                    field: "prepayment_model.Smm".into(),
                    reason: "SMM must be between 0 and 1".into(),
                });
            }
        }
    }

    // Validate default model rates.
    match &input.default_model {
        DefaultModel::Cdr(rate) => {
            if *rate < Decimal::ZERO || *rate > Decimal::ONE {
                return Err(CorpFinanceError::InvalidInput {
                    field: "default_model.Cdr".into(),
                    reason: "CDR must be between 0 and 1".into(),
                });
            }
        }
        DefaultModel::Sda(speed) => {
            if *speed < Decimal::ZERO {
                return Err(CorpFinanceError::InvalidInput {
                    field: "default_model.Sda".into(),
                    reason: "SDA speed must be non-negative".into(),
                });
            }
        }
        DefaultModel::None => {}
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Prepayment model helpers
// ---------------------------------------------------------------------------

/// Compute the annualised CPR for a given loan age and prepayment model.
fn compute_cpr(age: u32, model: &PrepaymentModel) -> Rate {
    match model {
        PrepaymentModel::Cpr(cpr) => *cpr,
        PrepaymentModel::Psa(speed) => {
            // PSA: CPR ramps linearly from 0 at month 0 to 6% at month 30, then flat.
            let base_cpr = if age <= 30 {
                PSA_BASE_CPR_30 * Decimal::from(age) / dec!(30)
            } else {
                PSA_BASE_CPR_30
            };
            base_cpr * *speed / dec!(100)
        }
        PrepaymentModel::Smm(smm) => {
            // Convert SMM back to CPR for reporting: CPR = 1 - (1 - SMM)^12.
            smm_to_cpr(*smm)
        }
    }
}

/// Convert annual CPR to single monthly mortality (SMM).
/// SMM = 1 - (1 - CPR)^(1/12)
fn cpr_to_smm(cpr: Rate) -> Rate {
    if cpr <= Decimal::ZERO {
        return Decimal::ZERO;
    }
    if cpr >= Decimal::ONE {
        return Decimal::ONE;
    }
    // SMM = 1 - twelfth_root(1 - CPR)
    let base = Decimal::ONE - cpr;
    Decimal::ONE - nth_root(base, 12)
}

/// Convert SMM back to annualised CPR.
/// CPR = 1 - (1 - SMM)^12
fn smm_to_cpr(smm: Rate) -> Rate {
    if smm <= Decimal::ZERO {
        return Decimal::ZERO;
    }
    if smm >= Decimal::ONE {
        return Decimal::ONE;
    }
    Decimal::ONE - iterative_pow(Decimal::ONE - smm, 12)
}

// ---------------------------------------------------------------------------
// Default model helpers
// ---------------------------------------------------------------------------

/// Compute the annualised CDR for a given loan age and default model.
fn compute_cdr(age: u32, model: &DefaultModel) -> Rate {
    match model {
        DefaultModel::Cdr(cdr) => *cdr,
        DefaultModel::Sda(speed) => {
            // SDA curve:
            //   Months 1-30:   CDR ramps from 0 to 0.6%
            //   Months 31-60:  flat at 0.6%
            //   Months 61-120: declines linearly to 0.03%
            //   Months 121+:   flat at 0.03%
            let base_cdr = if age <= 30 {
                SDA_PEAK_CDR_30 * Decimal::from(age) / dec!(30)
            } else if age <= 60 {
                SDA_PEAK_CDR_30
            } else if age <= 120 {
                // Linear decline from 0.006 at month 60 to 0.0003 at month 120.
                let months_into_decline = Decimal::from(age - 60);
                let decline_range = SDA_PEAK_CDR_30 - SDA_FLOOR_CDR;
                SDA_PEAK_CDR_30 - decline_range * months_into_decline / dec!(60)
            } else {
                SDA_FLOOR_CDR
            };
            base_cdr * *speed / dec!(100)
        }
        DefaultModel::None => Decimal::ZERO,
    }
}

/// Convert annual CDR to monthly default rate (MDR).
/// MDR = 1 - (1 - CDR)^(1/12)
fn cdr_to_mdr(cdr: Rate) -> Rate {
    if cdr <= Decimal::ZERO {
        return Decimal::ZERO;
    }
    if cdr >= Decimal::ONE {
        return Decimal::ONE;
    }
    let base = Decimal::ONE - cdr;
    Decimal::ONE - nth_root(base, 12)
}

// ---------------------------------------------------------------------------
// Decimal math helpers (no f64, no powd)
// ---------------------------------------------------------------------------

/// Compute base^n for a positive integer exponent via iterative multiplication.
fn iterative_pow(base: Decimal, n: u32) -> Decimal {
    let mut result = Decimal::ONE;
    for _ in 0..n {
        result *= base;
    }
    result
}

/// Compute 1 / base^n for a positive integer exponent via iterative multiplication.
/// Returns zero if base^n overflows or is zero.
fn iterative_pow_recip(base: Decimal, n: u32) -> Decimal {
    let pow = iterative_pow(base, n);
    if pow.is_zero() {
        Decimal::ZERO
    } else {
        Decimal::ONE / pow
    }
}

/// Compute the nth root of x using Newton's method.
/// x^(1/n) where n is a positive integer.
///
/// Newton iteration: g_{k+1} = g_k - (g_k^n - x) / (n * g_k^{n-1})
fn nth_root(x: Decimal, n: u32) -> Decimal {
    if x == Decimal::ONE {
        return Decimal::ONE;
    }
    if x == Decimal::ZERO {
        return Decimal::ZERO;
    }
    if n == 0 {
        return Decimal::ONE;
    }
    if n == 1 {
        return x;
    }

    let n_dec = Decimal::from(n);
    let n_minus_1 = n - 1;

    // Initial guess: start near 1 since our inputs are always close to 1
    // (they are of the form (1 - small_rate)).
    let mut guess = Decimal::ONE;

    for _ in 0..40 {
        let g_n_minus_1 = iterative_pow(guess, n_minus_1);
        let g_n = g_n_minus_1 * guess;

        if g_n_minus_1.is_zero() {
            break;
        }

        let delta = (g_n - x) / (n_dec * g_n_minus_1);
        guess -= delta;

        if delta.abs() < dec!(0.0000000000001) {
            break;
        }
    }

    guess
}

/// Create a zero-amount period for when the pool is exhausted.
fn zero_period(month: u32, balance: Money) -> AbsPeriod {
    AbsPeriod {
        month,
        beginning_balance: balance,
        scheduled_principal: Decimal::ZERO,
        scheduled_interest: Decimal::ZERO,
        prepayment: Decimal::ZERO,
        defaults: Decimal::ZERO,
        loss: Decimal::ZERO,
        recovery: Decimal::ZERO,
        servicing_fee: Decimal::ZERO,
        total_principal: Decimal::ZERO,
        total_cashflow: Decimal::ZERO,
        ending_balance: balance,
        smm: Decimal::ZERO,
        cpr: Decimal::ZERO,
        mdr: Decimal::ZERO,
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    /// Tolerance for financial comparisons.
    const TOL: Decimal = dec!(0.01);

    /// Helper: build a standard input for testing.
    fn standard_input() -> AbsMbsInput {
        AbsMbsInput {
            pool_balance: dec!(1_000_000),
            weighted_avg_coupon: dec!(0.06),
            weighted_avg_maturity_months: 360,
            weighted_avg_age_months: 0,
            num_loans: 1000,
            prepayment_model: PrepaymentModel::Cpr(dec!(0.0)),
            default_model: DefaultModel::None,
            loss_severity: dec!(0.40),
            recovery_lag_months: 6,
            servicing_fee_rate: dec!(0.0025),
            projection_months: 360,
        }
    }

    fn assert_close(actual: Decimal, expected: Decimal, tol: Decimal, msg: &str) {
        let diff = (actual - expected).abs();
        assert!(
            diff <= tol,
            "{}: expected ~{}, got {} (diff = {})",
            msg,
            expected,
            actual,
            diff
        );
    }

    // -----------------------------------------------------------------------
    // 1. Basic amortisation — no prepayments, no defaults
    // -----------------------------------------------------------------------
    #[test]
    fn test_basic_amortisation_no_prepay_no_defaults() {
        let input = standard_input();
        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // First period should have the full starting balance.
        assert_eq!(out.periods[0].beginning_balance, dec!(1_000_000));

        // Ending balance of last period should be near zero.
        let last = out.periods.last().unwrap();
        assert!(
            last.ending_balance < dec!(1.0),
            "Final balance should be near zero, got {}",
            last.ending_balance
        );

        // Total principal collected should equal pool balance (no defaults).
        assert_close(
            out.summary.total_principal_collected,
            dec!(1_000_000),
            dec!(1.0),
            "Total principal collected should equal pool balance",
        );

        // No prepayments.
        assert_eq!(out.summary.total_prepayments, Decimal::ZERO);
        // No defaults.
        assert_eq!(out.summary.total_defaults, Decimal::ZERO);
    }

    // -----------------------------------------------------------------------
    // 2. CPR prepayment model — basic
    // -----------------------------------------------------------------------
    #[test]
    fn test_cpr_prepayment_model() {
        let mut input = standard_input();
        input.prepayment_model = PrepaymentModel::Cpr(dec!(0.06));
        input.projection_months = 120;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // There should be prepayments in every period.
        assert!(out.summary.total_prepayments > Decimal::ZERO);

        // SMM should be constant across all periods with non-zero balance.
        let first_smm = out.periods[0].smm;
        for p in &out.periods {
            if p.beginning_balance > BALANCE_EPSILON {
                assert_close(
                    p.smm,
                    first_smm,
                    dec!(0.000001),
                    "SMM should be constant for CPR",
                );
            }
        }

        // CPR should be reported as 6%.
        assert_close(
            out.periods[0].cpr,
            dec!(0.06),
            dec!(0.0001),
            "CPR should be 6%",
        );
    }

    // -----------------------------------------------------------------------
    // 3. CPR at various speeds
    // -----------------------------------------------------------------------
    #[test]
    fn test_cpr_various_speeds() {
        for cpr_val in [dec!(0.02), dec!(0.10), dec!(0.20)] {
            let mut input = standard_input();
            input.prepayment_model = PrepaymentModel::Cpr(cpr_val);
            input.projection_months = 60;

            let result = model_abs_cashflows(&input).unwrap();
            let out = &result.result;

            assert!(
                out.summary.total_prepayments > Decimal::ZERO,
                "CPR {} should produce prepayments",
                cpr_val
            );
            assert_close(
                out.periods[0].cpr,
                cpr_val,
                dec!(0.0001),
                &format!("CPR should be {}", cpr_val),
            );
        }
    }

    // -----------------------------------------------------------------------
    // 4. PSA 100% model
    // -----------------------------------------------------------------------
    #[test]
    fn test_psa_100_model() {
        let mut input = standard_input();
        input.prepayment_model = PrepaymentModel::Psa(dec!(100));
        input.projection_months = 60;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // At month 1 (age=1), CPR = 0.06 * 1/30 = 0.002
        assert_close(
            out.periods[0].cpr,
            dec!(0.002),
            dec!(0.0001),
            "PSA 100 month 1 CPR",
        );

        // At month 30 (age=30), CPR = 0.06
        assert_close(
            out.periods[29].cpr,
            dec!(0.06),
            dec!(0.0001),
            "PSA 100 month 30 CPR",
        );

        // At month 40 (age=40), CPR still = 0.06 (flat after 30)
        assert_close(
            out.periods[39].cpr,
            dec!(0.06),
            dec!(0.0001),
            "PSA 100 month 40 CPR",
        );
    }

    // -----------------------------------------------------------------------
    // 5. PSA 200% model (faster prepayments)
    // -----------------------------------------------------------------------
    #[test]
    fn test_psa_200_model() {
        let mut input = standard_input();
        input.prepayment_model = PrepaymentModel::Psa(dec!(200));
        input.projection_months = 60;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // At month 30 (age=30), CPR = 0.06 * 200/100 = 0.12
        assert_close(
            out.periods[29].cpr,
            dec!(0.12),
            dec!(0.0001),
            "PSA 200 month 30 CPR",
        );

        // Higher PSA should produce more prepayments than PSA 100.
        let mut input_100 = standard_input();
        input_100.prepayment_model = PrepaymentModel::Psa(dec!(100));
        input_100.projection_months = 60;
        let result_100 = model_abs_cashflows(&input_100).unwrap();

        assert!(
            out.summary.total_prepayments > result_100.result.summary.total_prepayments,
            "PSA 200 should have more prepayments than PSA 100"
        );
    }

    // -----------------------------------------------------------------------
    // 6. PSA 50% model (slower prepayments)
    // -----------------------------------------------------------------------
    #[test]
    fn test_psa_50_model() {
        let mut input = standard_input();
        input.prepayment_model = PrepaymentModel::Psa(dec!(50));
        input.projection_months = 60;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // At month 30 (age=30), CPR = 0.06 * 50/100 = 0.03
        assert_close(
            out.periods[29].cpr,
            dec!(0.03),
            dec!(0.0001),
            "PSA 50 month 30 CPR",
        );
    }

    // -----------------------------------------------------------------------
    // 7. SDA default model with loss severity
    // -----------------------------------------------------------------------
    #[test]
    fn test_sda_default_model() {
        let mut input = standard_input();
        input.default_model = DefaultModel::Sda(dec!(100));
        input.projection_months = 120;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        assert!(
            out.summary.total_defaults > Decimal::ZERO,
            "SDA 100 should produce defaults"
        );
        assert!(
            out.summary.total_losses > Decimal::ZERO,
            "SDA 100 should produce losses"
        );

        // Losses = defaults * severity, accumulated.
        // Check that total_losses / total_defaults is close to loss severity.
        if out.summary.total_defaults > Decimal::ZERO {
            let avg_severity = out.summary.total_losses / out.summary.total_defaults;
            assert_close(
                avg_severity,
                dec!(0.40),
                dec!(0.01),
                "Average loss severity should equal input loss severity",
            );
        }
    }

    // -----------------------------------------------------------------------
    // 8. CDR constant default model
    // -----------------------------------------------------------------------
    #[test]
    fn test_cdr_constant_default_model() {
        let mut input = standard_input();
        input.default_model = DefaultModel::Cdr(dec!(0.02));
        input.projection_months = 60;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        assert!(
            out.summary.total_defaults > Decimal::ZERO,
            "CDR 2% should produce defaults"
        );

        // MDR should be constant.
        let first_mdr = out.periods[0].mdr;
        for p in &out.periods {
            if p.beginning_balance > BALANCE_EPSILON {
                assert_close(
                    p.mdr,
                    first_mdr,
                    dec!(0.000001),
                    "MDR should be constant for CDR",
                );
            }
        }
    }

    // -----------------------------------------------------------------------
    // 9. Combined prepayment + default models
    // -----------------------------------------------------------------------
    #[test]
    fn test_combined_prepayment_and_default() {
        let mut input = standard_input();
        input.prepayment_model = PrepaymentModel::Psa(dec!(150));
        input.default_model = DefaultModel::Cdr(dec!(0.03));
        input.projection_months = 120;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        assert!(out.summary.total_prepayments > Decimal::ZERO);
        assert!(out.summary.total_defaults > Decimal::ZERO);
        assert!(out.summary.total_losses > Decimal::ZERO);

        // Balance should decrease monotonically.
        for window in out.periods.windows(2) {
            assert!(
                window[1].beginning_balance <= window[0].beginning_balance + TOL,
                "Balance should decrease: month {} = {}, month {} = {}",
                window[0].month,
                window[0].beginning_balance,
                window[1].month,
                window[1].beginning_balance,
            );
        }
    }

    // -----------------------------------------------------------------------
    // 10. WAL calculation accuracy
    // -----------------------------------------------------------------------
    #[test]
    fn test_wal_calculation() {
        let input = standard_input();
        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // For a standard 30-year level-pay mortgage at 6%, WAL is around 14 years.
        // Without prepayments or defaults, WAL should be a reasonable value.
        assert!(
            out.summary.weighted_average_life_years > dec!(10),
            "WAL should be > 10 years, got {}",
            out.summary.weighted_average_life_years
        );
        assert!(
            out.summary.weighted_average_life_years < dec!(20),
            "WAL should be < 20 years, got {}",
            out.summary.weighted_average_life_years
        );

        // With higher prepayment, WAL should be shorter.
        let mut input_fast = standard_input();
        input_fast.prepayment_model = PrepaymentModel::Cpr(dec!(0.15));
        let result_fast = model_abs_cashflows(&input_fast).unwrap();
        assert!(
            result_fast.result.summary.weighted_average_life_years
                < out.summary.weighted_average_life_years,
            "Higher prepayment should produce shorter WAL"
        );
    }

    // -----------------------------------------------------------------------
    // 11. Pool factor calculation
    // -----------------------------------------------------------------------
    #[test]
    fn test_pool_factor() {
        let input = standard_input();
        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // After full amortisation, pool factor should be near zero.
        assert!(
            out.summary.pool_factor_at_end < dec!(0.001),
            "Pool factor at end should be near zero, got {}",
            out.summary.pool_factor_at_end
        );
    }

    // -----------------------------------------------------------------------
    // 12. Pool factor with early projection cutoff
    // -----------------------------------------------------------------------
    #[test]
    fn test_pool_factor_partial_projection() {
        let mut input = standard_input();
        input.projection_months = 60;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // After only 60 months of a 360-month pool, significant balance remains.
        assert!(
            out.summary.pool_factor_at_end > dec!(0.5),
            "Pool factor after 60 months should be > 50%, got {}",
            out.summary.pool_factor_at_end
        );
    }

    // -----------------------------------------------------------------------
    // 13. Recovery lag mechanics
    // -----------------------------------------------------------------------
    #[test]
    fn test_recovery_lag() {
        let mut input = standard_input();
        input.default_model = DefaultModel::Cdr(dec!(0.05));
        input.recovery_lag_months = 6;
        input.projection_months = 24;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // Recoveries should be zero for the first 6 months.
        for i in 0..6 {
            assert_eq!(
                out.periods[i].recovery,
                Decimal::ZERO,
                "Month {} should have zero recovery (lag = 6)",
                i + 1
            );
        }

        // After the lag, recoveries should appear.
        assert!(
            out.periods[6].recovery > Decimal::ZERO,
            "Month 7 should have non-zero recovery"
        );
    }

    // -----------------------------------------------------------------------
    // 14. Recovery lag of zero means immediate recovery
    // -----------------------------------------------------------------------
    #[test]
    fn test_recovery_lag_zero() {
        let mut input = standard_input();
        input.default_model = DefaultModel::Cdr(dec!(0.05));
        input.recovery_lag_months = 0;
        input.projection_months = 12;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // With zero lag, recoveries should appear in month 1.
        assert!(
            out.periods[0].recovery > Decimal::ZERO,
            "Month 1 should have immediate recovery with lag=0"
        );

        // Recovery should be defaults * (1 - loss_severity) for each period.
        for p in &out.periods {
            if p.defaults > Decimal::ZERO {
                let expected_recovery = p.defaults * (Decimal::ONE - dec!(0.40));
                assert_close(
                    p.recovery,
                    expected_recovery,
                    dec!(0.01),
                    &format!("Month {} recovery", p.month),
                );
            }
        }
    }

    // -----------------------------------------------------------------------
    // 15. Servicing fee deduction
    // -----------------------------------------------------------------------
    #[test]
    fn test_servicing_fee() {
        let input = standard_input();
        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // First month servicing fee = 1,000,000 * 0.0025 / 12 = ~208.33
        let expected_fee = dec!(1_000_000) * dec!(0.0025) / dec!(12);
        assert_close(
            out.periods[0].servicing_fee,
            expected_fee,
            dec!(0.01),
            "First month servicing fee",
        );

        // Total servicing fees should be positive.
        assert!(
            out.summary.total_servicing_fees > Decimal::ZERO,
            "Total servicing fees should be positive"
        );
    }

    // -----------------------------------------------------------------------
    // 16. Zero prepayment rate
    // -----------------------------------------------------------------------
    #[test]
    fn test_zero_prepayment() {
        let mut input = standard_input();
        input.prepayment_model = PrepaymentModel::Cpr(dec!(0.0));
        input.projection_months = 360;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        assert_eq!(out.summary.total_prepayments, Decimal::ZERO);
        for p in &out.periods {
            assert_eq!(p.prepayment, Decimal::ZERO);
            assert_eq!(p.smm, Decimal::ZERO);
        }
    }

    // -----------------------------------------------------------------------
    // 17. Very high prepayment (near 100% CPR)
    // -----------------------------------------------------------------------
    #[test]
    fn test_very_high_prepayment() {
        let mut input = standard_input();
        input.prepayment_model = PrepaymentModel::Cpr(dec!(0.95));
        input.projection_months = 60;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // Pool should be mostly paid off quickly.
        let last_period = out.periods.last().unwrap();
        assert!(
            last_period.ending_balance < dec!(100),
            "Very high CPR should exhaust pool quickly, got {}",
            last_period.ending_balance
        );

        // WAL should be very short.
        assert!(
            out.summary.weighted_average_life_years < dec!(2.0),
            "WAL with 95% CPR should be very short, got {}",
            out.summary.weighted_average_life_years
        );
    }

    // -----------------------------------------------------------------------
    // 18. High default rate
    // -----------------------------------------------------------------------
    #[test]
    fn test_high_default_rate() {
        let mut input = standard_input();
        input.default_model = DefaultModel::Cdr(dec!(0.20));
        input.projection_months = 60;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        assert!(
            out.summary.total_defaults > Decimal::ZERO,
            "20% CDR should produce significant defaults"
        );
        assert!(
            out.summary.cumulative_loss_rate > dec!(0.01),
            "Cumulative loss rate should be significant"
        );
    }

    // -----------------------------------------------------------------------
    // 19. Balance should never go negative
    // -----------------------------------------------------------------------
    #[test]
    fn test_balance_never_negative() {
        // Test with aggressive combined prepayment and defaults.
        let mut input = standard_input();
        input.prepayment_model = PrepaymentModel::Cpr(dec!(0.30));
        input.default_model = DefaultModel::Cdr(dec!(0.10));
        input.projection_months = 120;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        for p in &out.periods {
            assert!(
                p.ending_balance >= Decimal::ZERO,
                "Month {}: ending balance should not be negative, got {}",
                p.month,
                p.ending_balance
            );
            assert!(
                p.beginning_balance >= Decimal::ZERO,
                "Month {}: beginning balance should not be negative, got {}",
                p.month,
                p.beginning_balance
            );
        }
    }

    // -----------------------------------------------------------------------
    // 20. Sum of principal + defaults = starting balance
    // -----------------------------------------------------------------------
    #[test]
    fn test_principal_plus_defaults_equals_starting_balance() {
        let mut input = standard_input();
        input.prepayment_model = PrepaymentModel::Psa(dec!(150));
        input.default_model = DefaultModel::Cdr(dec!(0.03));
        input.projection_months = 360;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // Total principal collected + total defaults + remaining balance = pool balance.
        let total_reduction = out.summary.total_principal_collected
            + out.summary.total_defaults
            + out.periods.last().unwrap().ending_balance;

        assert_close(
            total_reduction,
            dec!(1_000_000),
            dec!(1.0),
            "Principal + defaults + remaining balance should equal pool balance",
        );
    }

    // -----------------------------------------------------------------------
    // 21. SMM model — direct monthly mortality
    // -----------------------------------------------------------------------
    #[test]
    fn test_smm_prepayment_model() {
        let mut input = standard_input();
        input.prepayment_model = PrepaymentModel::Smm(dec!(0.005));
        input.projection_months = 24;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // SMM should be the direct value.
        assert_close(
            out.periods[0].smm,
            dec!(0.005),
            dec!(0.0001),
            "SMM should be 0.005",
        );

        assert!(out.summary.total_prepayments > Decimal::ZERO);
    }

    // -----------------------------------------------------------------------
    // 22. Cumulative loss rate
    // -----------------------------------------------------------------------
    #[test]
    fn test_cumulative_loss_rate() {
        let mut input = standard_input();
        input.default_model = DefaultModel::Cdr(dec!(0.04));
        input.projection_months = 120;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // cumulative_loss_rate = total_losses / pool_balance.
        let expected = out.summary.total_losses / dec!(1_000_000);
        assert_close(
            out.summary.cumulative_loss_rate,
            expected,
            dec!(0.0001),
            "Cumulative loss rate",
        );
    }

    // -----------------------------------------------------------------------
    // 23. Interest calculation in first month
    // -----------------------------------------------------------------------
    #[test]
    fn test_interest_first_month() {
        let input = standard_input();
        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // First month interest = 1,000,000 * 0.06 / 12 = 5,000
        let expected_interest = dec!(1_000_000) * dec!(0.06) / dec!(12);
        assert_close(
            out.periods[0].scheduled_interest,
            expected_interest,
            dec!(0.01),
            "First month scheduled interest",
        );
    }

    // -----------------------------------------------------------------------
    // 24. Total cashflow includes all components
    // -----------------------------------------------------------------------
    #[test]
    fn test_total_cashflow_composition() {
        let mut input = standard_input();
        input.default_model = DefaultModel::Cdr(dec!(0.02));
        input.recovery_lag_months = 0;
        input.prepayment_model = PrepaymentModel::Cpr(dec!(0.05));
        input.projection_months = 24;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        for p in &out.periods {
            let expected_cf =
                p.scheduled_interest + p.total_principal - p.servicing_fee + p.recovery;
            assert_close(
                p.total_cashflow,
                expected_cf,
                dec!(0.01),
                &format!("Month {} total cashflow composition", p.month),
            );
        }
    }

    // -----------------------------------------------------------------------
    // 25. Validation: negative pool balance
    // -----------------------------------------------------------------------
    #[test]
    fn test_validation_negative_pool_balance() {
        let mut input = standard_input();
        input.pool_balance = dec!(-100);

        let result = model_abs_cashflows(&input);
        assert!(result.is_err());
        match result.unwrap_err() {
            CorpFinanceError::InvalidInput { field, .. } => {
                assert_eq!(field, "pool_balance");
            }
            other => panic!("Expected InvalidInput, got {:?}", other),
        }
    }

    // -----------------------------------------------------------------------
    // 26. Validation: invalid loss severity
    // -----------------------------------------------------------------------
    #[test]
    fn test_validation_loss_severity_out_of_range() {
        let mut input = standard_input();
        input.loss_severity = dec!(1.5);

        let result = model_abs_cashflows(&input);
        assert!(result.is_err());
        match result.unwrap_err() {
            CorpFinanceError::InvalidInput { field, .. } => {
                assert_eq!(field, "loss_severity");
            }
            other => panic!("Expected InvalidInput, got {:?}", other),
        }
    }

    // -----------------------------------------------------------------------
    // 27. Metadata is populated
    // -----------------------------------------------------------------------
    #[test]
    fn test_metadata_populated() {
        let input = standard_input();
        let result = model_abs_cashflows(&input).unwrap();

        assert!(!result.methodology.is_empty());
        assert!(result.methodology.contains("ABS/MBS"));
        assert_eq!(result.metadata.precision, "rust_decimal_128bit");
    }

    // -----------------------------------------------------------------------
    // 28. Correct number of periods
    // -----------------------------------------------------------------------
    #[test]
    fn test_correct_number_of_periods() {
        let mut input = standard_input();
        input.projection_months = 120;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        assert_eq!(out.periods.len(), 120);
        assert_eq!(out.periods[0].month, 1);
        assert_eq!(out.periods[119].month, 120);
    }

    // -----------------------------------------------------------------------
    // 29. SDA curve shape verification
    // -----------------------------------------------------------------------
    #[test]
    fn test_sda_curve_shape() {
        // Verify the SDA curve ramps, peaks, and declines correctly.
        // Age 1: CDR = 0.006 * 1/30 = 0.0002
        let cdr_1 = compute_cdr(1, &DefaultModel::Sda(dec!(100)));
        assert_close(cdr_1, dec!(0.0002), dec!(0.00001), "SDA age 1 CDR");

        // Age 30: CDR = 0.006
        let cdr_30 = compute_cdr(30, &DefaultModel::Sda(dec!(100)));
        assert_close(cdr_30, dec!(0.006), dec!(0.00001), "SDA age 30 CDR");

        // Age 45: CDR = 0.006 (flat 31-60)
        let cdr_45 = compute_cdr(45, &DefaultModel::Sda(dec!(100)));
        assert_close(cdr_45, dec!(0.006), dec!(0.00001), "SDA age 45 CDR");

        // Age 90: CDR = 0.006 - (0.006 - 0.0003) * 30/60 = 0.006 - 0.00285 = 0.00315
        let cdr_90 = compute_cdr(90, &DefaultModel::Sda(dec!(100)));
        assert_close(cdr_90, dec!(0.00315), dec!(0.0001), "SDA age 90 CDR");

        // Age 120: CDR = 0.0003
        let cdr_120 = compute_cdr(120, &DefaultModel::Sda(dec!(100)));
        assert_close(cdr_120, dec!(0.0003), dec!(0.00001), "SDA age 120 CDR");

        // Age 150: CDR = 0.0003 (floor)
        let cdr_150 = compute_cdr(150, &DefaultModel::Sda(dec!(100)));
        assert_close(cdr_150, dec!(0.0003), dec!(0.00001), "SDA age 150 CDR");
    }

    // -----------------------------------------------------------------------
    // 30. WALA offset works correctly
    // -----------------------------------------------------------------------
    #[test]
    fn test_wala_offset() {
        let mut input = standard_input();
        input.weighted_avg_age_months = 24;
        input.prepayment_model = PrepaymentModel::Psa(dec!(100));
        input.projection_months = 36;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // Month 1 of projection, age = 24 + 1 = 25.
        // CPR at age 25 = 0.06 * 25/30 = 0.05
        assert_close(
            out.periods[0].cpr,
            dec!(0.05),
            dec!(0.001),
            "PSA CPR at age 25",
        );

        // Month 6 of projection, age = 24 + 6 = 30 => CPR = 0.06
        assert_close(
            out.periods[5].cpr,
            dec!(0.06),
            dec!(0.001),
            "PSA CPR at age 30",
        );
    }

    // -----------------------------------------------------------------------
    // 31. Zero WAC pool (interest-free)
    // -----------------------------------------------------------------------
    #[test]
    fn test_zero_coupon_pool() {
        let mut input = standard_input();
        input.weighted_avg_coupon = dec!(0.0);
        input.projection_months = 360;

        let result = model_abs_cashflows(&input).unwrap();
        let out = &result.result;

        // All interest should be zero.
        assert_eq!(out.summary.total_interest_collected, Decimal::ZERO);
        for p in &out.periods {
            assert_eq!(p.scheduled_interest, Decimal::ZERO);
        }

        // But principal should still be amortised.
        assert_close(
            out.summary.total_principal_collected,
            dec!(1_000_000),
            dec!(1.0),
            "Zero coupon pool should still amortise",
        );
    }

    // -----------------------------------------------------------------------
    // 32. Validation: zero projection months
    // -----------------------------------------------------------------------
    #[test]
    fn test_validation_zero_projection_months() {
        let mut input = standard_input();
        input.projection_months = 0;

        let result = model_abs_cashflows(&input);
        assert!(result.is_err());
    }

    // -----------------------------------------------------------------------
    // 33. Nth root helper — 12th root of common values
    // -----------------------------------------------------------------------
    #[test]
    fn test_nth_root_precision() {
        // 12th root of 0.94 (i.e., (1-0.06)^(1/12))
        let root = nth_root(dec!(0.94), 12);
        // Expected: 0.94^(1/12) ~ 0.994845
        // Verify: root^12 should be close to 0.94
        let reconstructed = iterative_pow(root, 12);
        assert_close(
            reconstructed,
            dec!(0.94),
            dec!(0.000001),
            "12th root of 0.94 reconstruction",
        );

        // 12th root of 0.98
        let root2 = nth_root(dec!(0.98), 12);
        let reconstructed2 = iterative_pow(root2, 12);
        assert_close(
            reconstructed2,
            dec!(0.98),
            dec!(0.000001),
            "12th root of 0.98 reconstruction",
        );
    }

    // -----------------------------------------------------------------------
    // 34. CPR to SMM and back round-trip
    // -----------------------------------------------------------------------
    #[test]
    fn test_cpr_smm_round_trip() {
        for cpr in [dec!(0.02), dec!(0.06), dec!(0.10), dec!(0.20)] {
            let smm = cpr_to_smm(cpr);
            let cpr_back = smm_to_cpr(smm);
            assert_close(
                cpr_back,
                cpr,
                dec!(0.0001),
                &format!("CPR-SMM round trip for CPR={}", cpr),
            );
        }
    }
}