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
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
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use serde::{Deserialize, Serialize};

use crate::{CorpFinanceError, CorpFinanceResult};

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

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InvestorType {
    pub category: String,
    pub allocation_pct: Decimal,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UsFundInput {
    pub fund_name: String,
    /// "DelawareLP", "LLC", "REIT", "MLP", "BDC", "QOZ"
    pub structure_type: String,
    pub fund_size: Decimal,
    pub management_fee_rate: Decimal,
    pub carried_interest_rate: Decimal,
    pub preferred_return: Decimal,
    pub gp_commitment_pct: Decimal,
    pub fund_term_years: u32,
    /// "Delaware", "California", etc.
    pub state_of_formation: String,
    /// category in ["TaxExempt", "Taxable", "Foreign", "ERISA"]
    pub investor_types: Vec<InvestorType>,
    pub expected_annual_return: Decimal,
    /// "Quarterly", "Annual", "AtRealization"
    pub distribution_frequency: String,
    /// e.g. ["Section754", "QEF", "PFIC"]
    pub tax_elections: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FundEconomics {
    pub management_fees_annual: Decimal,
    pub carried_interest_potential: Decimal,
    pub gp_return: Decimal,
    pub net_return_to_lps: Decimal,
    pub total_fund_expenses: Decimal,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplianceTest {
    pub test_name: String,
    pub required_threshold: String,
    pub assumed_value: String,
    pub passes: bool,
    pub description: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxAnalysis {
    pub effective_tax_rate_taxable: Decimal,
    pub ubti_risk_score: Decimal,
    pub eci_risk_score: Decimal,
    pub pass_through_benefits: Vec<String>,
    pub structure_specific_tests: Vec<ComplianceTest>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErisaAnalysis {
    pub plan_asset_risk: String,
    pub vcoc_eligible: bool,
    pub reoc_eligible: bool,
    pub blocker_recommended: bool,
    pub benefit_plan_investor_pct: Decimal,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateAnalysis {
    pub formation_cost: Decimal,
    pub annual_cost: Decimal,
    pub franchise_tax: Decimal,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InvestorSuitability {
    pub category: String,
    pub suitable: bool,
    pub issues: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UsFundOutput {
    pub structure_type: String,
    pub fund_economics: FundEconomics,
    pub tax_analysis: TaxAnalysis,
    pub erisa_analysis: ErisaAnalysis,
    pub state_analysis: StateAnalysis,
    pub investor_suitability: Vec<InvestorSuitability>,
    pub recommendations: Vec<String>,
    pub warnings: Vec<String>,
}

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

const VALID_STRUCTURES: &[&str] = &["DelawareLP", "LLC", "REIT", "MLP", "BDC", "QOZ"];
const VALID_CATEGORIES: &[&str] = &["TaxExempt", "Taxable", "Foreign", "ERISA"];
const VALID_DIST_FREQ: &[&str] = &["Quarterly", "Annual", "AtRealization"];

fn validate_input(input: &UsFundInput) -> CorpFinanceResult<()> {
    if input.fund_size <= Decimal::ZERO {
        return Err(CorpFinanceError::InvalidInput {
            field: "fund_size".into(),
            reason: "must be positive".into(),
        });
    }
    if input.management_fee_rate < Decimal::ZERO || input.management_fee_rate > dec!(0.10) {
        return Err(CorpFinanceError::InvalidInput {
            field: "management_fee_rate".into(),
            reason: "must be in [0, 0.10]".into(),
        });
    }
    if input.carried_interest_rate < Decimal::ZERO || input.carried_interest_rate > Decimal::ONE {
        return Err(CorpFinanceError::InvalidInput {
            field: "carried_interest_rate".into(),
            reason: "must be in [0, 1]".into(),
        });
    }
    if input.preferred_return < Decimal::ZERO || input.preferred_return > Decimal::ONE {
        return Err(CorpFinanceError::InvalidInput {
            field: "preferred_return".into(),
            reason: "must be in [0, 1]".into(),
        });
    }
    if input.gp_commitment_pct < Decimal::ZERO || input.gp_commitment_pct > Decimal::ONE {
        return Err(CorpFinanceError::InvalidInput {
            field: "gp_commitment_pct".into(),
            reason: "must be in [0, 1]".into(),
        });
    }
    if input.fund_term_years == 0 || input.fund_term_years > 30 {
        return Err(CorpFinanceError::InvalidInput {
            field: "fund_term_years".into(),
            reason: "must be in [1, 30]".into(),
        });
    }
    if !VALID_STRUCTURES.contains(&input.structure_type.as_str()) {
        return Err(CorpFinanceError::InvalidInput {
            field: "structure_type".into(),
            reason: format!("must be one of: {}", VALID_STRUCTURES.join(", ")),
        });
    }
    if !VALID_DIST_FREQ.contains(&input.distribution_frequency.as_str()) {
        return Err(CorpFinanceError::InvalidInput {
            field: "distribution_frequency".into(),
            reason: format!("must be one of: {}", VALID_DIST_FREQ.join(", ")),
        });
    }
    if input.expected_annual_return < dec!(-1) || input.expected_annual_return > dec!(1) {
        return Err(CorpFinanceError::InvalidInput {
            field: "expected_annual_return".into(),
            reason: "must be in [-1, 1]".into(),
        });
    }
    if input.investor_types.is_empty() {
        return Err(CorpFinanceError::InvalidInput {
            field: "investor_types".into(),
            reason: "must have at least one investor type".into(),
        });
    }
    let mut alloc_sum = Decimal::ZERO;
    for inv in &input.investor_types {
        if !VALID_CATEGORIES.contains(&inv.category.as_str()) {
            return Err(CorpFinanceError::InvalidInput {
                field: "investor_types.category".into(),
                reason: format!(
                    "'{}' is not valid; must be one of: {}",
                    inv.category,
                    VALID_CATEGORIES.join(", ")
                ),
            });
        }
        if inv.allocation_pct < Decimal::ZERO || inv.allocation_pct > Decimal::ONE {
            return Err(CorpFinanceError::InvalidInput {
                field: "investor_types.allocation_pct".into(),
                reason: "must be in [0, 1]".into(),
            });
        }
        alloc_sum += inv.allocation_pct;
    }
    let alloc_diff = if alloc_sum > Decimal::ONE {
        alloc_sum - Decimal::ONE
    } else {
        Decimal::ONE - alloc_sum
    };
    if alloc_diff > dec!(0.01) {
        return Err(CorpFinanceError::InvalidInput {
            field: "investor_types.allocation_pct".into(),
            reason: format!("allocations sum to {} but must sum to ~1.0", alloc_sum),
        });
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Iterative compound: (1 + r)^n using multiplication to avoid powd drift.
fn compound(rate: Decimal, years: u32) -> Decimal {
    let mut result = Decimal::ONE;
    let factor = Decimal::ONE + rate;
    for _ in 0..years {
        result *= factor;
    }
    result
}

fn compute_fund_economics(input: &UsFundInput) -> FundEconomics {
    let mgmt_fee_annual = input.fund_size * input.management_fee_rate;
    let term = Decimal::from(input.fund_term_years);

    // Total fund value at end (simple compound)
    let total_value =
        input.fund_size * compound(input.expected_annual_return, input.fund_term_years);
    let total_profit = if total_value > input.fund_size {
        total_value - input.fund_size
    } else {
        Decimal::ZERO
    };

    // Preferred return hurdle over fund life
    let hurdle_value = input.fund_size * compound(input.preferred_return, input.fund_term_years);
    let excess_above_hurdle = if total_value > hurdle_value {
        total_value - hurdle_value
    } else {
        Decimal::ZERO
    };

    // Carried interest (European waterfall: carry only on excess above hurdle)
    let carried_interest = excess_above_hurdle * input.carried_interest_rate;

    // GP commitment return
    let gp_commitment = input.fund_size * input.gp_commitment_pct;
    let gp_return = gp_commitment * compound(input.expected_annual_return, input.fund_term_years)
        - gp_commitment;

    // Fund expenses (estimated: 0.5% of AUM annually for admin/legal/audit)
    let annual_expenses = input.fund_size * dec!(0.005);
    let total_expenses = annual_expenses * term + mgmt_fee_annual * term;

    // Net return to LPs
    let lp_capital = input.fund_size * (Decimal::ONE - input.gp_commitment_pct);
    let lp_share_of_profit = total_profit - carried_interest - gp_return;
    let net_return_to_lps = if lp_capital > Decimal::ZERO {
        lp_share_of_profit / lp_capital
    } else {
        Decimal::ZERO
    };

    FundEconomics {
        management_fees_annual: mgmt_fee_annual,
        carried_interest_potential: carried_interest,
        gp_return,
        net_return_to_lps,
        total_fund_expenses: total_expenses,
    }
}

fn compute_tax_analysis(input: &UsFundInput) -> TaxAnalysis {
    let st = input.structure_type.as_str();

    // Effective tax rate for taxable investors (federal estimates)
    let effective_tax_rate = match st {
        "DelawareLP" | "LLC" | "FCP" => dec!(0.238), // pass-through, top LTCG 23.8%
        "REIT" => dec!(0.37),                        // ordinary income rate on distributions
        "MLP" => dec!(0.238),                        // LTCG on unit sales
        "BDC" => dec!(0.37),                         // dividends taxed as ordinary income
        "QOZ" => dec!(0.0),                          // 10-year hold = step-up to FMV
        _ => dec!(0.37),
    };

    // UBTI risk (0=none, 1=high)
    let ubti_risk = match st {
        "DelawareLP" => dec!(0.3), // debt-financed income risk
        "LLC" => dec!(0.3),
        "REIT" => dec!(0.1), // generally no UBTI if properly structured
        "MLP" => dec!(0.9),  // MLPs generate UBTI for tax-exempt investors
        "BDC" => dec!(0.2),
        "QOZ" => dec!(0.2),
        _ => dec!(0.5),
    };

    // ECI risk for foreign investors
    let eci_risk = match st {
        "DelawareLP" => dec!(0.7), // trade or business income passes through
        "LLC" => dec!(0.7),
        "REIT" => dec!(0.2), // FIRPTA may apply to real estate
        "MLP" => dec!(0.9),  // ECI for all foreign investors
        "BDC" => dec!(0.3),
        "QOZ" => dec!(0.5),
        _ => dec!(0.5),
    };

    // Pass-through benefits
    let pass_through_benefits = match st {
        "DelawareLP" => vec![
            "Flow-through of capital gains".into(),
            "Section 199A deduction potential (20% QBI)".into(),
            "K-1 reporting to investors".into(),
            "No entity-level tax".into(),
        ],
        "LLC" => vec![
            "Check-the-box flexibility".into(),
            "Flow-through taxation".into(),
            "Limited liability protection".into(),
            "K-1 reporting to members".into(),
        ],
        "REIT" => vec![
            "Dividends-paid deduction eliminates corporate tax".into(),
            "Qualified REIT dividend (199A) — 20% deduction".into(),
        ],
        "MLP" => vec![
            "Tax-deferred distributions (return of capital)".into(),
            "Depreciation pass-through".into(),
            "Section 754 step-up available".into(),
        ],
        "BDC" => vec![
            "Pass-through via RIC structure".into(),
            "Dividends-paid deduction".into(),
        ],
        "QOZ" => vec![
            "Deferral of capital gains until 2026".into(),
            "10-year hold: step-up to FMV (no tax on appreciation)".into(),
            "Substantial improvement benefit".into(),
        ],
        _ => vec![],
    };

    // Structure-specific compliance tests
    let tests = compute_compliance_tests(input);

    TaxAnalysis {
        effective_tax_rate_taxable: effective_tax_rate,
        ubti_risk_score: ubti_risk,
        eci_risk_score: eci_risk,
        pass_through_benefits,
        structure_specific_tests: tests,
    }
}

fn compute_compliance_tests(input: &UsFundInput) -> Vec<ComplianceTest> {
    let st = input.structure_type.as_str();
    let mut tests = Vec::new();

    match st {
        "REIT" => {
            tests.push(ComplianceTest {
                test_name: "Distribution Requirement".into(),
                required_threshold: ">=90% of taxable income".into(),
                assumed_value: "90% assumed".into(),
                passes: true,
                description: "REIT must distribute at least 90% of taxable income".into(),
            });
            tests.push(ComplianceTest {
                test_name: "75% Asset Test".into(),
                required_threshold: ">=75% real estate assets".into(),
                assumed_value: "75% assumed".into(),
                passes: true,
                description:
                    "At least 75% of assets must be real estate, cash, or government securities"
                        .into(),
            });
            tests.push(ComplianceTest {
                test_name: "75% Income Test".into(),
                required_threshold: ">=75% from real estate".into(),
                assumed_value: "75% assumed".into(),
                passes: true,
                description:
                    "At least 75% of gross income from rents, mortgages, or real property sales"
                        .into(),
            });
            tests.push(ComplianceTest {
                test_name: "95% Income Test".into(),
                required_threshold: ">=95% passive income".into(),
                assumed_value: "95% assumed".into(),
                passes: true,
                description: "At least 95% of gross income from passive sources".into(),
            });
            tests.push(ComplianceTest {
                test_name: "TRS Limit".into(),
                required_threshold: "<=25% of assets in TRS".into(),
                assumed_value: "0% assumed".into(),
                passes: true,
                description: "Taxable REIT subsidiary cannot exceed 25% of total assets".into(),
            });
        }
        "MLP" => {
            tests.push(ComplianceTest {
                test_name: "Qualifying Income Test".into(),
                required_threshold: ">=90% qualifying income".into(),
                assumed_value: "90% assumed".into(),
                passes: true,
                description: "At least 90% of income must be qualifying (natural resources, real estate, etc.)".into(),
            });
            tests.push(ComplianceTest {
                test_name: "IDR Tier 1 (25/15/50 split)".into(),
                required_threshold: "IDR tiers properly structured".into(),
                assumed_value: "Standard tiers assumed".into(),
                passes: true,
                description: "Incentive distribution rights at 25%/15%/50% split levels".into(),
            });
            tests.push(ComplianceTest {
                test_name: "PTP Status".into(),
                required_threshold: "Publicly traded partnership rules".into(),
                assumed_value: "Compliant".into(),
                passes: true,
                description: "Must meet qualifying income test to avoid corporate taxation as PTP"
                    .into(),
            });
        }
        "BDC" => {
            tests.push(ComplianceTest {
                test_name: "Distribution Requirement".into(),
                required_threshold: ">=90% of investment income".into(),
                assumed_value: "90% assumed".into(),
                passes: true,
                description: "BDC must distribute at least 90% of net investment income".into(),
            });
            tests.push(ComplianceTest {
                test_name: "70% Qualifying Asset Test".into(),
                required_threshold: ">=70% qualifying assets".into(),
                assumed_value: "70% assumed".into(),
                passes: true,
                description:
                    "At least 70% of assets in qualifying investments (private/thinly traded)"
                        .into(),
            });
            tests.push(ComplianceTest {
                test_name: "Leverage Limit".into(),
                required_threshold: "<=2:1 debt-to-equity".into(),
                assumed_value: "1.5:1 assumed".into(),
                passes: true,
                description: "Debt-to-equity cannot exceed 2:1 (post-2018 SBCAA)".into(),
            });
        }
        "QOZ" => {
            tests.push(ComplianceTest {
                test_name: "90% QOZP Test".into(),
                required_threshold: ">=90% in qualified opportunity zone property".into(),
                assumed_value: "90% assumed".into(),
                passes: true,
                description: "At least 90% of assets must be qualified opportunity zone property"
                    .into(),
            });
            tests.push(ComplianceTest {
                test_name: "Substantial Improvement".into(),
                required_threshold: "Basis doubled within 30 months".into(),
                assumed_value: "Improvement planned".into(),
                passes: true,
                description:
                    "For existing buildings, basis must be doubled in improvements within 30 months"
                        .into(),
            });
            tests.push(ComplianceTest {
                test_name: "10-Year Hold Period".into(),
                required_threshold: ">=10 years for step-up to FMV".into(),
                assumed_value: format!("{} years", input.fund_term_years),
                passes: input.fund_term_years >= 10,
                description: "Must hold for at least 10 years to receive step-up to fair market value".into(),
            });
        }
        "DelawareLP" => {
            tests.push(ComplianceTest {
                test_name: "LP Agreement".into(),
                required_threshold: "Valid limited partnership agreement".into(),
                assumed_value: "In place".into(),
                passes: true,
                description: "Must have valid LP agreement filed with Delaware Secretary of State"
                    .into(),
            });
            if input.tax_elections.contains(&"Section754".to_string()) {
                tests.push(ComplianceTest {
                    test_name: "Section 754 Election".into(),
                    required_threshold: "Election filed with IRS".into(),
                    assumed_value: "Elected".into(),
                    passes: true,
                    description: "Section 754 election allows step-up in basis on transfer of partnership interests".into(),
                });
            }
        }
        "LLC" => {
            tests.push(ComplianceTest {
                test_name: "Check-the-Box Election".into(),
                required_threshold: "Form 8832 filed".into(),
                assumed_value: "Partnership classification".into(),
                passes: true,
                description: "LLC must elect partnership or disregarded entity classification for pass-through".into(),
            });
        }
        _ => {}
    }

    tests
}

fn compute_erisa_analysis(input: &UsFundInput) -> ErisaAnalysis {
    // Calculate benefit plan investor percentage
    let erisa_pct: Decimal = input
        .investor_types
        .iter()
        .filter(|i| i.category == "ERISA" || i.category == "TaxExempt")
        .map(|i| i.allocation_pct)
        .sum();

    // 25% threshold: if benefit plan investors >= 25%, fund assets = plan assets
    let plan_asset_risk = if erisa_pct >= dec!(0.25) {
        "High — exceeds 25% plan asset threshold".to_string()
    } else if erisa_pct >= dec!(0.15) {
        "Moderate — approaching 25% threshold".to_string()
    } else {
        "Low — below 25% threshold".to_string()
    };

    // VCOC: venture capital operating company exemption (>50% in operating companies + management rights)
    let vcoc_eligible = matches!(input.structure_type.as_str(), "DelawareLP" | "LLC");

    // REOC: real estate operating company (>50% in real estate with active management)
    let reoc_eligible = matches!(input.structure_type.as_str(), "REIT" | "QOZ");

    // Blocker recommended if ERISA investors and high UBTI risk structure
    let blocker_recommended =
        erisa_pct > Decimal::ZERO && matches!(input.structure_type.as_str(), "MLP");

    ErisaAnalysis {
        plan_asset_risk,
        vcoc_eligible,
        reoc_eligible,
        blocker_recommended,
        benefit_plan_investor_pct: erisa_pct,
    }
}

fn compute_state_analysis(input: &UsFundInput) -> StateAnalysis {
    let state = input.state_of_formation.as_str();

    let (formation_cost, annual_cost, franchise_tax) = match state {
        "Delaware" => (dec!(200), dec!(300), dec!(300)),
        "California" => (dec!(70), dec!(800), dec!(800)),
        "New York" => (dec!(200), dec!(4500), dec!(25)),
        "Texas" => (dec!(300), dec!(0), dec!(0)),
        "Nevada" => (dec!(75), dec!(350), dec!(0)),
        "Wyoming" => (dec!(100), dec!(60), dec!(0)),
        _ => (dec!(150), dec!(500), dec!(500)),
    };

    StateAnalysis {
        formation_cost,
        annual_cost,
        franchise_tax,
    }
}

fn compute_investor_suitability(input: &UsFundInput) -> Vec<InvestorSuitability> {
    let st = input.structure_type.as_str();

    input
        .investor_types
        .iter()
        .map(|inv| {
            let cat = inv.category.as_str();
            let mut issues = Vec::new();
            let mut suitable = true;

            match (cat, st) {
                ("TaxExempt", "MLP") => {
                    issues
                        .push("UBTI risk: MLP income is unrelated business taxable income".into());
                    issues.push("Consider blocker corporation to shield UBTI".into());
                    suitable = false;
                }
                ("TaxExempt", "DelawareLP") | ("TaxExempt", "LLC") => {
                    if input.tax_elections.iter().any(|e| e == "PFIC") {
                        issues.push("PFIC election may generate UBTI".into());
                    }
                    issues.push("Debt-financed income may generate UBTI".into());
                }
                ("TaxExempt", _) => {}
                ("Foreign", "MLP") => {
                    issues.push(
                        "ECI exposure: foreign investors subject to US tax on MLP income".into(),
                    );
                    issues.push("Withholding at 37% on ECI distributions".into());
                    issues.push("US tax return filing required".into());
                    suitable = false;
                }
                ("Foreign", "DelawareLP") | ("Foreign", "LLC") => {
                    issues.push("ECI risk: partnership trade or business income is ECI".into());
                    issues.push("FIRPTA may apply to real property dispositions".into());
                    issues.push("Consider blocker to convert ECI to portfolio income".into());
                }
                ("Foreign", "REIT") => {
                    issues.push(
                        "FIRPTA withholding on REIT distributions from US real property".into(),
                    );
                }
                ("Foreign", _) => {}
                ("ERISA", "MLP") => {
                    issues.push("UBTI risk makes MLP unsuitable for ERISA plans".into());
                    issues.push("Blocker entity required".into());
                    suitable = false;
                }
                ("ERISA", _) => {
                    let erisa_pct: Decimal = input
                        .investor_types
                        .iter()
                        .filter(|i| i.category == "ERISA" || i.category == "TaxExempt")
                        .map(|i| i.allocation_pct)
                        .sum();
                    if erisa_pct >= dec!(0.25) {
                        issues
                            .push("Plan asset risk: benefit plan investors >= 25% of fund".into());
                        issues
                            .push("VCOC or REOC exemption needed to avoid plan asset rules".into());
                    }
                }
                ("Taxable", _) => {
                    // Generally suitable
                }
                _ => {}
            }

            InvestorSuitability {
                category: inv.category.clone(),
                suitable,
                issues,
            }
        })
        .collect()
}

fn generate_recommendations(
    input: &UsFundInput,
    tax: &TaxAnalysis,
    erisa: &ErisaAnalysis,
) -> Vec<String> {
    let mut recs = Vec::new();
    let st = input.structure_type.as_str();

    match st {
        "DelawareLP" => {
            if !input.tax_elections.contains(&"Section754".to_string()) {
                recs.push(
                    "Consider Section 754 election for basis step-up on secondary transfers".into(),
                );
            }
            recs.push(
                "Ensure GP maintains at least 1% ownership for tax partnership validity".into(),
            );
        }
        "LLC" => {
            recs.push("File Form 8832 to elect partnership classification if multi-member".into());
            recs.push("Consider series LLC structure for asset isolation".into());
        }
        "REIT" => {
            recs.push("Monitor 75%/95% income tests and 75% asset test quarterly".into());
            recs.push(
                "Consider TRS for non-qualifying activities (capped at 25% of assets)".into(),
            );
        }
        "MLP" => {
            recs.push("Monitor qualifying income test (90%) quarterly".into());
            recs.push("Consider blocker entity for tax-exempt and foreign investors".into());
        }
        "BDC" => {
            recs.push("Monitor 2:1 leverage limit and 70% qualifying asset test".into());
            recs.push("Consider spillover dividend for excess undistributed income".into());
        }
        "QOZ" => {
            if input.fund_term_years < 10 {
                recs.push("Extend fund term to at least 10 years for full step-up benefit".into());
            }
            recs.push("Ensure 90% QOZP test compliance at semi-annual testing dates".into());
            recs.push("Plan substantial improvement within 30 months of acquisition".into());
        }
        _ => {}
    }

    if erisa.benefit_plan_investor_pct > dec!(0.15) && erisa.benefit_plan_investor_pct < dec!(0.25)
    {
        recs.push("Approaching 25% benefit plan investor threshold — monitor closely".into());
    }
    if erisa.benefit_plan_investor_pct >= dec!(0.25) && !erisa.vcoc_eligible && !erisa.reoc_eligible
    {
        recs.push("Obtain VCOC or REOC exemption to avoid plan asset rules".into());
    }

    if tax.ubti_risk_score > dec!(0.5) {
        recs.push("High UBTI risk — consider blocker corporation for tax-exempt investors".into());
    }
    if tax.eci_risk_score > dec!(0.5) {
        recs.push("High ECI risk — consider offshore blocker for foreign investors".into());
    }

    recs
}

fn generate_warnings(input: &UsFundInput, tax: &TaxAnalysis, erisa: &ErisaAnalysis) -> Vec<String> {
    let mut warns = Vec::new();

    if erisa.benefit_plan_investor_pct >= dec!(0.25) {
        warns.push("ERISA plan asset rules triggered — benefit plan investors >= 25%".into());
    }

    if input.structure_type == "QOZ" && input.fund_term_years < 10 {
        warns.push(
            "QOZ fund term < 10 years — investors will not receive full step-up benefit".into(),
        );
    }

    for test in &tax.structure_specific_tests {
        if !test.passes {
            warns.push(format!("FAILED: {}{}", test.test_name, test.description));
        }
    }

    let has_foreign = input.investor_types.iter().any(|i| i.category == "Foreign");
    if has_foreign && tax.eci_risk_score > dec!(0.5) {
        warns.push("Foreign investors face significant ECI exposure in this structure".into());
    }

    let has_tax_exempt = input
        .investor_types
        .iter()
        .any(|i| i.category == "TaxExempt");
    if has_tax_exempt && tax.ubti_risk_score > dec!(0.5) {
        warns.push("Tax-exempt investors face significant UBTI exposure".into());
    }

    warns
}

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

/// Analyze a US onshore fund structure, producing economics, tax, ERISA,
/// state, and investor suitability analysis.
pub fn analyze_us_fund_structure(input: &UsFundInput) -> CorpFinanceResult<UsFundOutput> {
    validate_input(input)?;

    let fund_economics = compute_fund_economics(input);
    let tax_analysis = compute_tax_analysis(input);
    let erisa_analysis = compute_erisa_analysis(input);
    let state_analysis = compute_state_analysis(input);
    let investor_suitability = compute_investor_suitability(input);
    let recommendations = generate_recommendations(input, &tax_analysis, &erisa_analysis);
    let warnings = generate_warnings(input, &tax_analysis, &erisa_analysis);

    Ok(UsFundOutput {
        structure_type: input.structure_type.clone(),
        fund_economics,
        tax_analysis,
        erisa_analysis,
        state_analysis,
        investor_suitability,
        recommendations,
        warnings,
    })
}

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

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

    fn approx_eq(a: Decimal, b: Decimal, tol: Decimal) -> bool {
        let diff = if a > b { a - b } else { b - a };
        diff < tol
    }

    fn default_input() -> UsFundInput {
        UsFundInput {
            fund_name: "Test Fund I".into(),
            structure_type: "DelawareLP".into(),
            fund_size: dec!(100_000_000),
            management_fee_rate: dec!(0.02),
            carried_interest_rate: dec!(0.20),
            preferred_return: dec!(0.08),
            gp_commitment_pct: dec!(0.02),
            fund_term_years: 10,
            state_of_formation: "Delaware".into(),
            investor_types: vec![
                InvestorType {
                    category: "Taxable".into(),
                    allocation_pct: dec!(0.60),
                },
                InvestorType {
                    category: "TaxExempt".into(),
                    allocation_pct: dec!(0.25),
                },
                InvestorType {
                    category: "Foreign".into(),
                    allocation_pct: dec!(0.15),
                },
            ],
            expected_annual_return: dec!(0.15),
            distribution_frequency: "Quarterly".into(),
            tax_elections: vec!["Section754".into()],
        }
    }

    fn reit_input() -> UsFundInput {
        UsFundInput {
            fund_name: "REIT Fund".into(),
            structure_type: "REIT".into(),
            fund_size: dec!(500_000_000),
            management_fee_rate: dec!(0.01),
            carried_interest_rate: dec!(0.15),
            preferred_return: dec!(0.06),
            gp_commitment_pct: dec!(0.01),
            fund_term_years: 7,
            state_of_formation: "Delaware".into(),
            investor_types: vec![
                InvestorType {
                    category: "Taxable".into(),
                    allocation_pct: dec!(0.70),
                },
                InvestorType {
                    category: "TaxExempt".into(),
                    allocation_pct: dec!(0.30),
                },
            ],
            expected_annual_return: dec!(0.10),
            distribution_frequency: "Quarterly".into(),
            tax_elections: vec![],
        }
    }

    fn mlp_input() -> UsFundInput {
        UsFundInput {
            fund_name: "Energy MLP".into(),
            structure_type: "MLP".into(),
            fund_size: dec!(200_000_000),
            management_fee_rate: dec!(0.02),
            carried_interest_rate: dec!(0.20),
            preferred_return: dec!(0.08),
            gp_commitment_pct: dec!(0.02),
            fund_term_years: 10,
            state_of_formation: "Delaware".into(),
            investor_types: vec![
                InvestorType {
                    category: "Taxable".into(),
                    allocation_pct: dec!(0.50),
                },
                InvestorType {
                    category: "TaxExempt".into(),
                    allocation_pct: dec!(0.20),
                },
                InvestorType {
                    category: "Foreign".into(),
                    allocation_pct: dec!(0.30),
                },
            ],
            expected_annual_return: dec!(0.12),
            distribution_frequency: "Quarterly".into(),
            tax_elections: vec![],
        }
    }

    fn bdc_input() -> UsFundInput {
        UsFundInput {
            fund_name: "BDC Fund".into(),
            structure_type: "BDC".into(),
            fund_size: dec!(300_000_000),
            management_fee_rate: dec!(0.015),
            carried_interest_rate: dec!(0.175),
            preferred_return: dec!(0.07),
            gp_commitment_pct: dec!(0.03),
            fund_term_years: 8,
            state_of_formation: "Delaware".into(),
            investor_types: vec![InvestorType {
                category: "Taxable".into(),
                allocation_pct: dec!(1.0),
            }],
            expected_annual_return: dec!(0.10),
            distribution_frequency: "Quarterly".into(),
            tax_elections: vec![],
        }
    }

    fn qoz_input() -> UsFundInput {
        UsFundInput {
            fund_name: "QOZ Fund".into(),
            structure_type: "QOZ".into(),
            fund_size: dec!(50_000_000),
            management_fee_rate: dec!(0.015),
            carried_interest_rate: dec!(0.20),
            preferred_return: dec!(0.08),
            gp_commitment_pct: dec!(0.05),
            fund_term_years: 12,
            state_of_formation: "Delaware".into(),
            investor_types: vec![InvestorType {
                category: "Taxable".into(),
                allocation_pct: dec!(1.0),
            }],
            expected_annual_return: dec!(0.12),
            distribution_frequency: "AtRealization".into(),
            tax_elections: vec![],
        }
    }

    fn llc_input() -> UsFundInput {
        UsFundInput {
            fund_name: "LLC Fund".into(),
            structure_type: "LLC".into(),
            fund_size: dec!(75_000_000),
            management_fee_rate: dec!(0.02),
            carried_interest_rate: dec!(0.20),
            preferred_return: dec!(0.08),
            gp_commitment_pct: dec!(0.02),
            fund_term_years: 10,
            state_of_formation: "California".into(),
            investor_types: vec![
                InvestorType {
                    category: "Taxable".into(),
                    allocation_pct: dec!(0.80),
                },
                InvestorType {
                    category: "ERISA".into(),
                    allocation_pct: dec!(0.20),
                },
            ],
            expected_annual_return: dec!(0.14),
            distribution_frequency: "Annual".into(),
            tax_elections: vec![],
        }
    }

    // -----------------------------------------------------------------------
    // Basic functionality tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_delaware_lp_basic() {
        let input = default_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        assert_eq!(result.structure_type, "DelawareLP");
    }

    #[test]
    fn test_management_fee_calculation() {
        let input = default_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        // 100M * 2% = 2M
        assert_eq!(
            result.fund_economics.management_fees_annual,
            dec!(2_000_000)
        );
    }

    #[test]
    fn test_fund_expenses_positive() {
        let input = default_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        assert!(result.fund_economics.total_fund_expenses > Decimal::ZERO);
    }

    #[test]
    fn test_carried_interest_positive_with_positive_return() {
        let input = default_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        // 15% return > 8% hurdle => carry should be positive
        assert!(
            result.fund_economics.carried_interest_potential > Decimal::ZERO,
            "Carried interest should be positive when return > hurdle"
        );
    }

    #[test]
    fn test_carried_interest_zero_when_below_hurdle() {
        let mut input = default_input();
        input.expected_annual_return = dec!(0.05); // below 8% hurdle
        let result = analyze_us_fund_structure(&input).unwrap();
        assert_eq!(
            result.fund_economics.carried_interest_potential,
            Decimal::ZERO,
            "Carry should be zero when return < hurdle"
        );
    }

    #[test]
    fn test_gp_return_positive() {
        let input = default_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        assert!(result.fund_economics.gp_return > Decimal::ZERO);
    }

    // -----------------------------------------------------------------------
    // Tax analysis tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_delaware_lp_pass_through() {
        let input = default_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        assert!(
            result
                .tax_analysis
                .pass_through_benefits
                .iter()
                .any(|b| b.contains("Flow-through")),
            "Delaware LP should have flow-through benefits"
        );
    }

    #[test]
    fn test_delaware_lp_effective_tax_rate() {
        let input = default_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        assert_eq!(result.tax_analysis.effective_tax_rate_taxable, dec!(0.238));
    }

    #[test]
    fn test_reit_distribution_test() {
        let input = reit_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        let has_dist_test = result
            .tax_analysis
            .structure_specific_tests
            .iter()
            .any(|t| t.test_name.contains("Distribution"));
        assert!(
            has_dist_test,
            "REIT should have distribution requirement test"
        );
    }

    #[test]
    fn test_reit_asset_tests() {
        let input = reit_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        let test_names: Vec<&str> = result
            .tax_analysis
            .structure_specific_tests
            .iter()
            .map(|t| t.test_name.as_str())
            .collect();
        assert!(test_names.contains(&"75% Asset Test"));
        assert!(test_names.contains(&"75% Income Test"));
        assert!(test_names.contains(&"95% Income Test"));
        assert!(test_names.contains(&"TRS Limit"));
    }

    #[test]
    fn test_mlp_qualifying_income_test() {
        let input = mlp_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        let has_qi = result
            .tax_analysis
            .structure_specific_tests
            .iter()
            .any(|t| t.test_name.contains("Qualifying Income"));
        assert!(has_qi, "MLP should have qualifying income test");
    }

    #[test]
    fn test_mlp_high_ubti_risk() {
        let input = mlp_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        assert!(
            result.tax_analysis.ubti_risk_score >= dec!(0.9),
            "MLP UBTI risk {} should be >= 0.9",
            result.tax_analysis.ubti_risk_score
        );
    }

    #[test]
    fn test_mlp_high_eci_risk() {
        let input = mlp_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        assert!(
            result.tax_analysis.eci_risk_score >= dec!(0.9),
            "MLP ECI risk {} should be >= 0.9",
            result.tax_analysis.eci_risk_score
        );
    }

    #[test]
    fn test_bdc_compliance_tests() {
        let input = bdc_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        let test_names: Vec<&str> = result
            .tax_analysis
            .structure_specific_tests
            .iter()
            .map(|t| t.test_name.as_str())
            .collect();
        assert!(test_names.contains(&"Distribution Requirement"));
        assert!(test_names.contains(&"70% Qualifying Asset Test"));
        assert!(test_names.contains(&"Leverage Limit"));
    }

    #[test]
    fn test_qoz_step_up_benefit() {
        let input = qoz_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        assert_eq!(
            result.tax_analysis.effective_tax_rate_taxable,
            dec!(0.0),
            "QOZ 10-year hold should have 0% effective tax"
        );
    }

    #[test]
    fn test_qoz_compliance_tests_pass_with_long_term() {
        let input = qoz_input(); // 12-year term
        let result = analyze_us_fund_structure(&input).unwrap();
        let hold_test = result
            .tax_analysis
            .structure_specific_tests
            .iter()
            .find(|t| t.test_name.contains("10-Year"));
        assert!(hold_test.is_some());
        assert!(
            hold_test.unwrap().passes,
            "12-year term should pass 10-year test"
        );
    }

    #[test]
    fn test_qoz_compliance_tests_fail_with_short_term() {
        let mut input = qoz_input();
        input.fund_term_years = 7;
        let result = analyze_us_fund_structure(&input).unwrap();
        let hold_test = result
            .tax_analysis
            .structure_specific_tests
            .iter()
            .find(|t| t.test_name.contains("10-Year"));
        assert!(hold_test.is_some());
        assert!(
            !hold_test.unwrap().passes,
            "7-year term should fail 10-year test"
        );
    }

    #[test]
    fn test_llc_check_the_box() {
        let input = llc_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        let has_ctb = result
            .tax_analysis
            .structure_specific_tests
            .iter()
            .any(|t| t.test_name.contains("Check-the-Box"));
        assert!(has_ctb, "LLC should have check-the-box test");
    }

    #[test]
    fn test_section_754_election_test() {
        let input = default_input(); // has Section754 in tax_elections
        let result = analyze_us_fund_structure(&input).unwrap();
        let has_754 = result
            .tax_analysis
            .structure_specific_tests
            .iter()
            .any(|t| t.test_name.contains("Section 754"));
        assert!(has_754, "Should have Section 754 test when elected");
    }

    // -----------------------------------------------------------------------
    // ERISA analysis tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_erisa_below_threshold() {
        let input = default_input(); // TaxExempt 25% (just at threshold)
        let result = analyze_us_fund_structure(&input).unwrap();
        // TaxExempt 25% >= 25%
        assert!(
            result.erisa_analysis.plan_asset_risk.contains("High"),
            "25% TaxExempt should trigger high plan asset risk"
        );
    }

    #[test]
    fn test_erisa_low_risk() {
        let mut input = default_input();
        input.investor_types = vec![
            InvestorType {
                category: "Taxable".into(),
                allocation_pct: dec!(0.90),
            },
            InvestorType {
                category: "TaxExempt".into(),
                allocation_pct: dec!(0.10),
            },
        ];
        let result = analyze_us_fund_structure(&input).unwrap();
        assert!(
            result.erisa_analysis.plan_asset_risk.contains("Low"),
            "10% TaxExempt should be low risk"
        );
    }

    #[test]
    fn test_erisa_moderate_risk() {
        let mut input = default_input();
        input.investor_types = vec![
            InvestorType {
                category: "Taxable".into(),
                allocation_pct: dec!(0.80),
            },
            InvestorType {
                category: "TaxExempt".into(),
                allocation_pct: dec!(0.20),
            },
        ];
        let result = analyze_us_fund_structure(&input).unwrap();
        assert!(
            result.erisa_analysis.plan_asset_risk.contains("Moderate"),
            "20% TaxExempt should be moderate risk"
        );
    }

    #[test]
    fn test_vcoc_eligible_for_lp() {
        let input = default_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        assert!(result.erisa_analysis.vcoc_eligible);
    }

    #[test]
    fn test_reoc_eligible_for_reit() {
        let input = reit_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        assert!(result.erisa_analysis.reoc_eligible);
    }

    #[test]
    fn test_blocker_recommended_for_mlp() {
        let mut input = mlp_input();
        input.investor_types = vec![
            InvestorType {
                category: "Taxable".into(),
                allocation_pct: dec!(0.50),
            },
            InvestorType {
                category: "ERISA".into(),
                allocation_pct: dec!(0.50),
            },
        ];
        let result = analyze_us_fund_structure(&input).unwrap();
        assert!(
            result.erisa_analysis.blocker_recommended,
            "MLP with ERISA investors should recommend blocker"
        );
    }

    // -----------------------------------------------------------------------
    // State analysis tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_delaware_formation_cost() {
        let input = default_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        assert_eq!(result.state_analysis.formation_cost, dec!(200));
    }

    #[test]
    fn test_california_higher_annual_cost() {
        let input = llc_input(); // California
        let result = analyze_us_fund_structure(&input).unwrap();
        assert_eq!(result.state_analysis.annual_cost, dec!(800));
    }

    #[test]
    fn test_texas_no_franchise_tax() {
        let mut input = default_input();
        input.state_of_formation = "Texas".into();
        let result = analyze_us_fund_structure(&input).unwrap();
        assert_eq!(result.state_analysis.franchise_tax, Decimal::ZERO);
    }

    // -----------------------------------------------------------------------
    // Investor suitability tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_taxable_always_suitable() {
        let input = default_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        let taxable = result
            .investor_suitability
            .iter()
            .find(|s| s.category == "Taxable");
        assert!(taxable.is_some());
        assert!(taxable.unwrap().suitable);
    }

    #[test]
    fn test_tax_exempt_mlp_unsuitable() {
        let input = mlp_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        let te = result
            .investor_suitability
            .iter()
            .find(|s| s.category == "TaxExempt");
        assert!(te.is_some());
        assert!(
            !te.unwrap().suitable,
            "TaxExempt investors in MLP should be unsuitable"
        );
    }

    #[test]
    fn test_foreign_mlp_unsuitable() {
        let input = mlp_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        let foreign = result
            .investor_suitability
            .iter()
            .find(|s| s.category == "Foreign");
        assert!(foreign.is_some());
        assert!(
            !foreign.unwrap().suitable,
            "Foreign investors in MLP should be unsuitable"
        );
    }

    #[test]
    fn test_foreign_has_eci_warning_in_lp() {
        let input = default_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        let foreign = result
            .investor_suitability
            .iter()
            .find(|s| s.category == "Foreign");
        assert!(foreign.is_some());
        assert!(
            foreign.unwrap().issues.iter().any(|i| i.contains("ECI")),
            "Foreign investors in LP should have ECI warning"
        );
    }

    // -----------------------------------------------------------------------
    // Recommendations and warnings tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_recommendations_not_empty() {
        let input = default_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        assert!(!result.recommendations.is_empty());
    }

    #[test]
    fn test_qoz_short_term_warning() {
        let mut input = qoz_input();
        input.fund_term_years = 7;
        let result = analyze_us_fund_structure(&input).unwrap();
        assert!(
            result.warnings.iter().any(|w| w.contains("10 years")),
            "Should warn about short QOZ term"
        );
    }

    #[test]
    fn test_mlp_eci_warning_for_foreign() {
        let input = mlp_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        assert!(
            result.warnings.iter().any(|w| w.contains("ECI")),
            "MLP with foreign investors should have ECI warning"
        );
    }

    #[test]
    fn test_mlp_ubti_warning_for_tax_exempt() {
        let input = mlp_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        assert!(
            result.warnings.iter().any(|w| w.contains("UBTI")),
            "MLP with tax-exempt investors should have UBTI warning"
        );
    }

    // -----------------------------------------------------------------------
    // Validation error tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_invalid_fund_size() {
        let mut input = default_input();
        input.fund_size = dec!(-100);
        let result = analyze_us_fund_structure(&input);
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_management_fee() {
        let mut input = default_input();
        input.management_fee_rate = dec!(0.15);
        let result = analyze_us_fund_structure(&input);
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_structure_type() {
        let mut input = default_input();
        input.structure_type = "InvalidType".into();
        let result = analyze_us_fund_structure(&input);
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_investor_category() {
        let mut input = default_input();
        input.investor_types = vec![InvestorType {
            category: "BadCategory".into(),
            allocation_pct: dec!(1.0),
        }];
        let result = analyze_us_fund_structure(&input);
        assert!(result.is_err());
    }

    #[test]
    fn test_allocation_pct_not_sum_to_one() {
        let mut input = default_input();
        input.investor_types = vec![
            InvestorType {
                category: "Taxable".into(),
                allocation_pct: dec!(0.30),
            },
            InvestorType {
                category: "TaxExempt".into(),
                allocation_pct: dec!(0.30),
            },
        ];
        let result = analyze_us_fund_structure(&input);
        assert!(result.is_err());
    }

    #[test]
    fn test_zero_fund_term() {
        let mut input = default_input();
        input.fund_term_years = 0;
        let result = analyze_us_fund_structure(&input);
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_distribution_frequency() {
        let mut input = default_input();
        input.distribution_frequency = "Monthly".into();
        let result = analyze_us_fund_structure(&input);
        assert!(result.is_err());
    }

    #[test]
    fn test_empty_investor_types() {
        let mut input = default_input();
        input.investor_types = vec![];
        let result = analyze_us_fund_structure(&input);
        assert!(result.is_err());
    }

    #[test]
    fn test_carried_interest_rate_out_of_range() {
        let mut input = default_input();
        input.carried_interest_rate = dec!(1.5);
        let result = analyze_us_fund_structure(&input);
        assert!(result.is_err());
    }

    #[test]
    fn test_preferred_return_out_of_range() {
        let mut input = default_input();
        input.preferred_return = dec!(-0.1);
        let result = analyze_us_fund_structure(&input);
        assert!(result.is_err());
    }

    // -----------------------------------------------------------------------
    // Compound helper
    // -----------------------------------------------------------------------

    #[test]
    fn test_compound_basic() {
        // (1.10)^3 = 1.331
        let result = compound(dec!(0.10), 3);
        assert!(
            approx_eq(result, dec!(1.331), dec!(0.001)),
            "compound(0.10, 3) = {} expected ~1.331",
            result
        );
    }

    #[test]
    fn test_compound_zero_rate() {
        let result = compound(Decimal::ZERO, 10);
        assert_eq!(result, Decimal::ONE);
    }

    // -----------------------------------------------------------------------
    // Multi-structure tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_all_structure_types_produce_output() {
        for st in VALID_STRUCTURES {
            let mut input = default_input();
            input.structure_type = st.to_string();
            if *st == "QOZ" {
                // QOZ needs single taxable investor for simplicity
                input.investor_types = vec![InvestorType {
                    category: "Taxable".into(),
                    allocation_pct: dec!(1.0),
                }];
            }
            let result = analyze_us_fund_structure(&input);
            assert!(
                result.is_ok(),
                "Structure '{}' should produce valid output, got: {:?}",
                st,
                result.err()
            );
            assert_eq!(result.unwrap().structure_type, *st);
        }
    }

    #[test]
    fn test_erisa_investor_plan_asset() {
        let mut input = default_input();
        input.investor_types = vec![
            InvestorType {
                category: "Taxable".into(),
                allocation_pct: dec!(0.50),
            },
            InvestorType {
                category: "ERISA".into(),
                allocation_pct: dec!(0.50),
            },
        ];
        let result = analyze_us_fund_structure(&input).unwrap();
        assert!(
            result.erisa_analysis.benefit_plan_investor_pct >= dec!(0.50),
            "Benefit plan investor pct should be at least 50%"
        );
        assert!(result.erisa_analysis.plan_asset_risk.contains("High"));
    }

    #[test]
    fn test_net_return_positive_when_fund_returns_well() {
        let input = default_input();
        let result = analyze_us_fund_structure(&input).unwrap();
        assert!(
            result.fund_economics.net_return_to_lps > Decimal::ZERO,
            "LP net return should be positive with 15% annual return"
        );
    }
}