mollendorff-forge 10.0.0-beta.8

Battle-tested financial math for AI. 173 Excel-compatible functions validated against Gnumeric & R. MCP integration, Monte Carlo, Decision Trees, Real Options.
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
//! Prediction Methods CLI Commands (Enterprise Only)
//!
//! CLI handlers for advanced forecasting methods:
//! - scenarios: Run scenario analysis (Base/Bull/Bear)
//! - `decision_tree`: Analyze decision trees with backward induction
//! - `real_options`: Value managerial flexibility (defer/expand/abandon)
//! - tornado: Generate sensitivity tornado diagrams
//! - bootstrap: Non-parametric confidence intervals via resampling
//! - bayesian: Bayesian network inference and queries

use crate::bayesian::{BayesianConfig, BayesianEngine};
use crate::bootstrap::{BootstrapConfig, BootstrapEngine};
use crate::decision_trees::{DecisionTreeConfig, DecisionTreeEngine};
use crate::error::{ForgeError, ForgeResult};
use crate::parser;
use crate::real_options::{RealOptionsConfig, RealOptionsEngine};
use crate::scenarios::{ScenarioConfig, ScenarioEngine};
use crate::tornado::{TornadoConfig, TornadoEngine};
use colored::Colorize;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

/// Run scenario analysis and return structured results (no printing).
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, no scenarios section exists,
/// or the scenario engine fails.
pub fn scenarios_core(
    file: &Path,
    scenario_filter: Option<&str>,
) -> ForgeResult<crate::scenarios::ScenarioResults> {
    let yaml_content = fs::read_to_string(file).map_err(ForgeError::Io)?;
    let model = parser::parse_model(file)?;

    let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(&yaml_content)
        .map_err(|e| ForgeError::Validation(format!("YAML parse error: {e}")))?;

    let config: ScenarioConfig = if let Some(scenarios_value) = value.get("scenarios") {
        let scenarios_map: HashMap<String, serde_yaml_ng::Value> =
            serde_yaml_ng::from_value(scenarios_value.clone())
                .map_err(|e| ForgeError::Validation(format!("scenarios config error: {e}")))?;

        let mut config = ScenarioConfig::default();
        for (name, def) in scenarios_map {
            let scenario_def = serde_yaml_ng::from_value(def)
                .map_err(|e| ForgeError::Validation(format!("scenario '{name}' error: {e}")))?;
            config.scenarios.insert(name, scenario_def);
        }
        config
    } else {
        return Err(ForgeError::Validation(
            "No 'scenarios' section found in YAML".to_string(),
        ));
    };

    let engine = ScenarioEngine::new(config, model).map_err(ForgeError::Validation)?;
    let _ = scenario_filter; // filtering done in display, engine runs all
    engine.run().map_err(ForgeError::Eval)
}

/// Analyze a decision tree and return structured results (no printing).
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, no `decision_tree` section exists,
/// or the analysis fails.
pub fn decision_tree_core(file: &Path) -> ForgeResult<crate::decision_trees::TreeResult> {
    let yaml_content = fs::read_to_string(file).map_err(ForgeError::Io)?;

    let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(&yaml_content)
        .map_err(|e| ForgeError::Validation(format!("YAML parse error: {e}")))?;

    let config: DecisionTreeConfig = if let Some(dt_value) = value.get("decision_tree") {
        serde_yaml_ng::from_value(dt_value.clone())
            .map_err(|e| ForgeError::Validation(format!("decision_tree config error: {e}")))?
    } else {
        return Err(ForgeError::Validation(
            "No 'decision_tree' section found in YAML".to_string(),
        ));
    };

    let engine = DecisionTreeEngine::new(config).map_err(ForgeError::Validation)?;
    engine.analyze().map_err(ForgeError::Eval)
}

/// Value real options and return structured results (no printing).
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, no `real_options` section exists,
/// or the analysis fails.
pub fn real_options_core(file: &Path) -> ForgeResult<crate::real_options::OptionsResult> {
    let yaml_content = fs::read_to_string(file).map_err(ForgeError::Io)?;

    let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(&yaml_content)
        .map_err(|e| ForgeError::Validation(format!("YAML parse error: {e}")))?;

    let config: RealOptionsConfig = if let Some(ro_value) = value.get("real_options") {
        serde_yaml_ng::from_value(ro_value.clone())
            .map_err(|e| ForgeError::Validation(format!("real_options config error: {e}")))?
    } else {
        return Err(ForgeError::Validation(
            "No 'real_options' section found in YAML".to_string(),
        ));
    };

    let engine = RealOptionsEngine::new(config).map_err(ForgeError::Validation)?;
    engine.analyze().map_err(ForgeError::Eval)
}

/// Generate tornado sensitivity analysis and return structured results (no printing).
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, no tornado section exists,
/// or the analysis fails.
pub fn tornado_core(
    file: &Path,
    output_var: Option<&str>,
) -> ForgeResult<crate::tornado::TornadoResult> {
    let yaml_content = fs::read_to_string(file).map_err(ForgeError::Io)?;
    let model = parser::parse_model(file)?;

    let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(&yaml_content)
        .map_err(|e| ForgeError::Validation(format!("YAML parse error: {e}")))?;

    let mut config: TornadoConfig = if let Some(tornado_value) = value.get("tornado") {
        serde_yaml_ng::from_value(tornado_value.clone())
            .map_err(|e| ForgeError::Validation(format!("tornado config error: {e}")))?
    } else {
        return Err(ForgeError::Validation(
            "No 'tornado' section found in YAML".to_string(),
        ));
    };

    if let Some(out_var) = output_var {
        config.output = out_var.to_string();
    }

    let engine = TornadoEngine::new(config, model).map_err(ForgeError::Validation)?;
    engine.analyze().map_err(ForgeError::Eval)
}

/// Run bootstrap resampling and return structured results (no printing).
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, no bootstrap section exists,
/// or the analysis fails.
pub fn bootstrap_core(
    file: &Path,
    iterations_override: Option<usize>,
    seed_override: Option<u64>,
    confidence_override: Option<Vec<f64>>,
) -> ForgeResult<crate::bootstrap::BootstrapResult> {
    let yaml_content = fs::read_to_string(file).map_err(ForgeError::Io)?;

    let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(&yaml_content)
        .map_err(|e| ForgeError::Validation(format!("YAML parse error: {e}")))?;

    let mut config: BootstrapConfig = if let Some(bs_value) = value.get("bootstrap") {
        serde_yaml_ng::from_value(bs_value.clone())
            .map_err(|e| ForgeError::Validation(format!("bootstrap config error: {e}")))?
    } else {
        return Err(ForgeError::Validation(
            "No 'bootstrap' section found in YAML".to_string(),
        ));
    };

    if let Some(n) = iterations_override {
        config.iterations = n;
    }
    if let Some(s) = seed_override {
        config.seed = Some(s);
    }
    if let Some(levels) = confidence_override {
        config.confidence_levels = levels;
    }

    let mut engine = BootstrapEngine::new(config).map_err(ForgeError::Validation)?;
    engine.analyze().map_err(ForgeError::Eval)
}

/// Run Bayesian network inference and return structured results (no printing).
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, no `bayesian_network` section exists,
/// or inference fails.
pub fn bayesian_core(
    file: &Path,
    query_var: Option<&str>,
    evidence: &[String],
) -> ForgeResult<crate::bayesian::BayesianResult> {
    let yaml_content = fs::read_to_string(file).map_err(ForgeError::Io)?;

    let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(&yaml_content)
        .map_err(|e| ForgeError::Validation(format!("YAML parse error: {e}")))?;

    let config: BayesianConfig = if let Some(bn_value) = value.get("bayesian_network") {
        serde_yaml_ng::from_value(bn_value.clone())
            .map_err(|e| ForgeError::Validation(format!("bayesian_network config error: {e}")))?
    } else {
        return Err(ForgeError::Validation(
            "No 'bayesian_network' section found in YAML".to_string(),
        ));
    };

    let mut evidence_map: HashMap<String, &str> = HashMap::new();
    for ev in evidence {
        let parts: Vec<&str> = ev.split('=').collect();
        if parts.len() == 2 {
            evidence_map.insert(parts[0].to_string(), parts[1]);
        }
    }

    let network_name = config.name.clone();
    let engine = BayesianEngine::new(config).map_err(ForgeError::Validation)?;

    if let Some(target) = query_var {
        let var_result = if evidence_map.is_empty() {
            engine.query(target).map_err(ForgeError::Eval)?
        } else {
            engine
                .query_with_evidence(target, &evidence_map)
                .map_err(ForgeError::Eval)?
        };
        Ok(crate::bayesian::BayesianResult {
            name: network_name,
            queries: std::iter::once((target.to_string(), var_result)).collect(),
            evidence: evidence_map
                .iter()
                .map(|(k, v)| (k.clone(), (*v).to_string()))
                .collect(),
        })
    } else {
        let all_results = if evidence_map.is_empty() {
            engine.query_all().map_err(ForgeError::Eval)?
        } else {
            engine
                .query_all_with_evidence(&evidence_map)
                .map_err(ForgeError::Eval)?
        };
        Ok(all_results)
    }
}

/// Execute the scenarios command - probability-weighted scenario analysis
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, no scenarios section exists,
/// or the scenario engine fails.
pub fn scenarios(
    file: &Path,
    scenario_filter: Option<&str>,
    output_file: Option<PathBuf>,
    verbose: bool,
) -> ForgeResult<()> {
    println!("{}", "📊 Forge - Scenario Analysis".bold().green());
    println!("   File: {}", file.display());
    println!();

    // Parse YAML
    let yaml_content = fs::read_to_string(file).map_err(ForgeError::Io)?;
    let model = parser::parse_model(file)?;

    // Parse scenarios config
    let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(&yaml_content)
        .map_err(|e| ForgeError::Validation(format!("YAML parse error: {e}")))?;

    let config: ScenarioConfig = if let Some(scenarios_value) = value.get("scenarios") {
        let scenarios_map: HashMap<String, serde_yaml_ng::Value> =
            serde_yaml_ng::from_value(scenarios_value.clone())
                .map_err(|e| ForgeError::Validation(format!("scenarios config error: {e}")))?;

        // Convert to ScenarioConfig
        let mut config = ScenarioConfig::default();
        for (name, def) in scenarios_map {
            let scenario_def = serde_yaml_ng::from_value(def)
                .map_err(|e| ForgeError::Validation(format!("scenario '{name}' error: {e}")))?;
            config.scenarios.insert(name, scenario_def);
        }
        config
    } else {
        return Err(ForgeError::Validation(
            "No 'scenarios' section found in YAML".to_string(),
        ));
    };

    // Display config
    println!("   {}", "Scenarios:".bold());
    for (name, def) in &config.scenarios {
        println!(
            "      {} (p={:.0}%): {}",
            name.bright_blue(),
            def.probability * 100.0,
            &def.description
        );
    }
    println!();

    // Create engine and run
    let engine = ScenarioEngine::new(config, model).map_err(ForgeError::Validation)?;

    if let Some(filter) = scenario_filter {
        if verbose {
            println!("{}", format!("🎯 Running scenario: {filter}").cyan());
        }
    } else if verbose {
        println!("{}", "🔄 Running all scenarios...".cyan());
    }
    let results = engine.run().map_err(ForgeError::Eval)?;

    // Display results
    println!("{}", "📈 Scenario Results:".bold().green());
    println!();

    for result in &results.scenarios {
        println!("   {}:", result.name.bright_blue().bold());
        println!("      Probability: {:.1}%", result.probability * 100.0);
        println!("      Key Scalars:");
        for (var, value) in result.scalars.iter().take(5) {
            println!("         {}: {:.2}", var.cyan(), value);
        }
        println!();
    }

    // Expected value
    println!("   {}", "Expected Values (probability-weighted):".bold());
    for (var, ev) in &results.expected_values {
        println!("      {}: {:.2}", var.bright_blue(), ev);
    }
    println!();

    // Write output if specified
    if let Some(output_path) = output_file {
        let output_str = format!("{results:#?}");
        fs::write(&output_path, output_str).map_err(ForgeError::Io)?;
        println!(
            "{}",
            format!("💾 Results written to {}", output_path.display())
                .bold()
                .green()
        );
    }

    println!("{}", "✅ Scenario analysis complete".bold().green());
    Ok(())
}

/// Execute the decision-tree command - backward induction analysis
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, no `decision_tree` section exists,
/// or the analysis fails.
pub fn decision_tree(
    file: &Path,
    export_dot: bool,
    output_file: Option<PathBuf>,
    verbose: bool,
) -> ForgeResult<()> {
    println!("{}", "🌳 Forge - Decision Tree Analysis".bold().green());
    println!("   File: {}", file.display());
    println!();

    // Parse YAML
    let yaml_content = fs::read_to_string(file).map_err(ForgeError::Io)?;

    // Parse decision_tree config
    let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(&yaml_content)
        .map_err(|e| ForgeError::Validation(format!("YAML parse error: {e}")))?;

    let config: DecisionTreeConfig = if let Some(dt_value) = value.get("decision_tree") {
        serde_yaml_ng::from_value(dt_value.clone())
            .map_err(|e| ForgeError::Validation(format!("decision_tree config error: {e}")))?
    } else {
        return Err(ForgeError::Validation(
            "No 'decision_tree' section found in YAML".to_string(),
        ));
    };

    // Display config
    println!("   {}", format!("Tree: {}", config.name).bold());
    if verbose {
        println!("      Root: {:?}", config.root.as_ref().map(|r| &r.name));
        println!("      Nodes: {}", config.nodes.len());
    }
    println!();

    // Create engine and analyze
    let engine = DecisionTreeEngine::new(config).map_err(ForgeError::Validation)?;

    if verbose {
        println!("{}", "🔄 Running backward induction...".cyan());
    }

    let result = engine.analyze().map_err(ForgeError::Eval)?;

    // Display results
    println!("{}", "📊 Decision Tree Results:".bold().green());
    println!();

    // Optimal path
    println!("   {}", "Optimal Path:".bold());
    for step in &result.optimal_path {
        println!("{}", step.cyan());
    }
    println!();

    // Expected value at root
    println!(
        "   Expected Value: {}",
        format!("${:.2}", result.root_expected_value).bold().green()
    );

    // Decision policy
    println!();
    println!("   {}", "Decision Policy:".bold());
    for (node, choice) in &result.decision_policy {
        println!("      At \"{}\": choose \"{}\"", node.bright_blue(), choice);
    }

    // Risk profile
    println!();
    println!("   {}", "Risk Profile:".bold());
    println!("      Best case:  ${:.2}", result.risk_profile.best_case);
    println!("      Worst case: ${:.2}", result.risk_profile.worst_case);
    println!(
        "      P(value > 0): {:.1}%",
        result.risk_profile.probability_positive * 100.0
    );
    println!();

    // Export DOT if requested (feature not yet implemented, just note it)
    if export_dot {
        println!(
            "{}",
            "⚠️  DOT export not yet implemented. Use --output for YAML export.".yellow()
        );
    }

    if let Some(output_path) = output_file {
        let output_str = format!("{result:#?}");
        fs::write(&output_path, output_str).map_err(ForgeError::Io)?;
        println!(
            "{}",
            format!("💾 Results written to {}", output_path.display())
                .bold()
                .green()
        );
    }

    println!("{}", "✅ Decision tree analysis complete".bold().green());
    Ok(())
}

/// Execute the real-options command - value managerial flexibility
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, no `real_options` section exists,
/// the option filter does not match, or the analysis fails.
pub fn real_options(
    file: &Path,
    option_filter: Option<&str>,
    compare_npv: bool,
    output_file: Option<PathBuf>,
    verbose: bool,
) -> ForgeResult<()> {
    println!("{}", "💎 Forge - Real Options Analysis".bold().green());
    println!("   File: {}", file.display());
    println!();

    // Parse YAML
    let yaml_content = fs::read_to_string(file).map_err(ForgeError::Io)?;

    // Parse real_options config
    let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(&yaml_content)
        .map_err(|e| ForgeError::Validation(format!("YAML parse error: {e}")))?;

    let config: RealOptionsConfig = if let Some(ro_value) = value.get("real_options") {
        serde_yaml_ng::from_value(ro_value.clone())
            .map_err(|e| ForgeError::Validation(format!("real_options config error: {e}")))?
    } else {
        return Err(ForgeError::Validation(
            "No 'real_options' section found in YAML".to_string(),
        ));
    };

    // Display config
    println!("   {}", format!("Analysis: {}", config.name).bold());
    println!(
        "      Method: {}",
        format!("{:?}", config.method).bright_blue()
    );
    println!(
        "      Underlying value: ${:.2}",
        config.underlying.current_value
    );
    println!(
        "      Volatility: {:.1}%",
        config.underlying.volatility * 100.0
    );
    println!(
        "      Risk-free rate: {:.1}%",
        config.underlying.risk_free_rate * 100.0
    );
    println!(
        "      Time horizon: {} years",
        config.underlying.time_horizon
    );
    println!();

    // Create engine and value options
    let engine = RealOptionsEngine::new(config).map_err(ForgeError::Validation)?;

    if verbose {
        println!("{}", "🔄 Valuing options...".cyan());
    }

    let result = engine.analyze().map_err(ForgeError::Eval)?;

    // Filter if specific option requested
    if let Some(filter) = option_filter {
        if !result.options.contains_key(filter) {
            return Err(ForgeError::Validation(format!(
                "Option '{}' not found. Available: {:?}",
                filter,
                result.options.keys().collect::<Vec<_>>()
            )));
        }
    }

    // Display results
    print_real_options_results(&result, option_filter, compare_npv);

    // Write output if specified
    if let Some(output_path) = output_file {
        let output_str = format!("{result:#?}");
        fs::write(&output_path, output_str).map_err(ForgeError::Io)?;
        println!(
            "{}",
            format!("💾 Results written to {}", output_path.display())
                .bold()
                .green()
        );
    }

    println!("{}", "✅ Real options analysis complete".bold().green());
    Ok(())
}

/// Execute the tornado command - sensitivity tornado diagram
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, no tornado section exists,
/// or the analysis fails.
pub fn tornado(
    file: &Path,
    output_var: Option<&str>,
    output_file: Option<PathBuf>,
    verbose: bool,
) -> ForgeResult<()> {
    println!("{}", "🌪️ Forge - Tornado Diagram".bold().green());
    println!("   File: {}", file.display());
    println!();

    // Parse YAML and model
    let yaml_content = fs::read_to_string(file).map_err(ForgeError::Io)?;
    let model = parser::parse_model(file)?;

    // Parse tornado config
    let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(&yaml_content)
        .map_err(|e| ForgeError::Validation(format!("YAML parse error: {e}")))?;

    let mut config: TornadoConfig = if let Some(tornado_value) = value.get("tornado") {
        serde_yaml_ng::from_value(tornado_value.clone())
            .map_err(|e| ForgeError::Validation(format!("tornado config error: {e}")))?
    } else {
        return Err(ForgeError::Validation(
            "No 'tornado' section found in YAML".to_string(),
        ));
    };

    // Override output variable if specified
    if let Some(out_var) = output_var {
        config.output = out_var.to_string();
    }

    // Display config
    println!("   Output variable: {}", config.output.bright_blue());
    println!("   Inputs to vary: {}", config.inputs.len());
    if verbose {
        for input in &config.inputs {
            println!(
                "      {} [{:.2} - {:.2}]",
                input.name.cyan(),
                input.low,
                input.high
            );
        }
    }
    println!();

    // Create engine and analyze
    let engine = TornadoEngine::new(config, model).map_err(ForgeError::Validation)?;

    if verbose {
        println!("{}", "🔄 Calculating sensitivities...".cyan());
    }

    let result = engine.analyze().map_err(ForgeError::Eval)?;

    // Display results
    println!("{}", "📊 Tornado Diagram:".bold().green());
    println!(
        "   Base value: {}",
        format!("{:.2}", result.base_value).bold()
    );
    println!();

    // Tornado bars (already sorted by impact)
    let max_impact = result
        .bars
        .iter()
        .map(|b| b.swing.abs())
        .fold(0.0f64, f64::max);

    for bar in &result.bars {
        // Truncation/sign-loss impossible: value is always in 0.0..=30.0
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let bar_width = if max_impact > 0.0 {
            ((bar.swing.abs() / max_impact) * 30.0) as usize
        } else {
            0
        };
        let bar_str = "".repeat(bar_width.max(1));

        println!(
            "   {:20} |{}| ±{:.2}",
            bar.input_name.bright_blue(),
            bar_str.cyan(),
            bar.swing.abs()
        );
        if verbose {
            println!(
                "                        Low: {:.2}  High: {:.2}",
                bar.output_at_low, bar.output_at_high
            );
        }
    }
    println!();

    // Write output if specified
    if let Some(output_path) = output_file {
        let output_str = format!("{result:#?}");
        fs::write(&output_path, output_str).map_err(ForgeError::Io)?;
        println!(
            "{}",
            format!("💾 Results written to {}", output_path.display())
                .bold()
                .green()
        );
    }

    println!("{}", "✅ Tornado diagram complete".bold().green());
    Ok(())
}

/// Execute the bootstrap command - resampling confidence intervals
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, no bootstrap section exists,
/// or the analysis fails.
pub fn bootstrap(
    file: &Path,
    iterations_override: Option<usize>,
    seed_override: Option<u64>,
    confidence_override: Option<Vec<f64>>,
    output_file: Option<PathBuf>,
    verbose: bool,
) -> ForgeResult<()> {
    println!("{}", "🔄 Forge - Bootstrap Resampling".bold().green());
    println!("   File: {}", file.display());
    println!();

    // Parse YAML
    let yaml_content = fs::read_to_string(file).map_err(ForgeError::Io)?;

    // Parse bootstrap config
    let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(&yaml_content)
        .map_err(|e| ForgeError::Validation(format!("YAML parse error: {e}")))?;

    let mut config: BootstrapConfig = if let Some(bs_value) = value.get("bootstrap") {
        serde_yaml_ng::from_value(bs_value.clone())
            .map_err(|e| ForgeError::Validation(format!("bootstrap config error: {e}")))?
    } else {
        return Err(ForgeError::Validation(
            "No 'bootstrap' section found in YAML".to_string(),
        ));
    };

    // Apply overrides
    if let Some(n) = iterations_override {
        config.iterations = n;
    }
    if let Some(s) = seed_override {
        config.seed = Some(s);
    }
    if let Some(levels) = confidence_override {
        config.confidence_levels = levels;
    }

    // Display config
    println!("   {}", "Configuration:".bold());
    println!(
        "      Iterations: {}",
        config.iterations.to_string().bright_blue()
    );
    println!(
        "      Statistic: {}",
        format!("{:?}", config.statistic).bright_blue()
    );
    println!("      Data points: {}", config.data.len());
    println!("      Confidence levels: {:?}", config.confidence_levels);
    if let Some(seed) = config.seed {
        println!("      Seed: {seed}");
    }
    println!();

    // Create engine and analyze
    let mut engine = BootstrapEngine::new(config).map_err(ForgeError::Validation)?;

    if verbose {
        println!("{}", "🔄 Resampling...".cyan());
    }

    let result = engine.analyze().map_err(ForgeError::Eval)?;

    // Display results
    println!("{}", "📊 Bootstrap Results:".bold().green());
    println!();

    println!(
        "   Original statistic: {}",
        format!("{:.4}", result.original_estimate).bold()
    );
    println!("   Bootstrap mean: {:.4}", result.bootstrap_mean);
    println!("   Bootstrap std error: {:.4}", result.bootstrap_std_error);
    println!("   Bias: {:.4}", result.bias);
    println!();

    // Confidence intervals
    println!("   {}", "Confidence Intervals:".bold());
    for ci in &result.confidence_intervals {
        println!(
            "      {:.0}% CI: [{:.4}, {:.4}]",
            ci.level * 100.0,
            ci.lower,
            ci.upper
        );
    }
    println!();

    // Write output if specified
    if let Some(output_path) = output_file {
        let output_str = format!("{result:#?}");
        fs::write(&output_path, output_str).map_err(ForgeError::Io)?;
        println!(
            "{}",
            format!("💾 Results written to {}", output_path.display())
                .bold()
                .green()
        );
    }

    println!("{}", "✅ Bootstrap analysis complete".bold().green());
    Ok(())
}

/// Execute the bayesian command - Bayesian network inference
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, no `bayesian_network` section exists,
/// or inference fails.
pub fn bayesian(
    file: &Path,
    query_var: Option<&str>,
    evidence: &[String],
    output_file: Option<PathBuf>,
    verbose: bool,
) -> ForgeResult<()> {
    println!("{}", "🔮 Forge - Bayesian Network Inference".bold().green());
    println!("   File: {}", file.display());
    println!();

    // Parse YAML
    let yaml_content = fs::read_to_string(file).map_err(ForgeError::Io)?;

    // Parse bayesian_network config
    let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(&yaml_content)
        .map_err(|e| ForgeError::Validation(format!("YAML parse error: {e}")))?;

    let config: BayesianConfig = if let Some(bn_value) = value.get("bayesian_network") {
        serde_yaml_ng::from_value(bn_value.clone())
            .map_err(|e| ForgeError::Validation(format!("bayesian_network config error: {e}")))?
    } else {
        return Err(ForgeError::Validation(
            "No 'bayesian_network' section found in YAML".to_string(),
        ));
    };

    // Display config
    println!("   {}", format!("Network: {}", config.name).bold());
    println!("   Nodes: {}", config.nodes.len());
    if verbose {
        for (name, node) in &config.nodes {
            let parents = if node.parents.is_empty() {
                "root".to_string()
            } else {
                node.parents.join(", ")
            };
            println!(
                "      {} ({} states, parents: {})",
                name.bright_blue(),
                node.states.len(),
                parents
            );
        }
    }
    println!();

    // Parse evidence
    let mut evidence_map: HashMap<String, &str> = HashMap::new();
    for ev in evidence {
        let parts: Vec<&str> = ev.split('=').collect();
        if parts.len() == 2 {
            evidence_map.insert(parts[0].to_string(), parts[1]);
        }
    }

    if !evidence_map.is_empty() {
        println!("   {}", "Evidence:".bold());
        for (var, val) in &evidence_map {
            println!("      {} = {}", var.bright_blue(), val.cyan());
        }
        println!();
    }

    // Create engine
    let engine = BayesianEngine::new(config).map_err(ForgeError::Validation)?;

    if verbose {
        println!("{}", "🔄 Running inference...".cyan());
    }

    // Run query
    if let Some(target) = query_var {
        let var_result = if evidence_map.is_empty() {
            println!("{}", "📊 Query Result:".bold().green());
            engine.query(target).map_err(ForgeError::Eval)?
        } else {
            println!("{}", "📊 Query Result (with evidence):".bold().green());
            engine
                .query_with_evidence(target, &evidence_map)
                .map_err(ForgeError::Eval)?
        };
        print_bayesian_var_result(target, &var_result);
        if let Some(output_path) = output_file {
            let output_str = format!("{var_result:#?}");
            fs::write(&output_path, output_str).map_err(ForgeError::Io)?;
            println!(
                "{}",
                format!("💾 Results written to {}", output_path.display())
                    .bold()
                    .green()
            );
        }
    } else {
        // Query all nodes
        let all_results = if evidence_map.is_empty() {
            engine.query_all().map_err(ForgeError::Eval)?
        } else {
            engine
                .query_all_with_evidence(&evidence_map)
                .map_err(ForgeError::Eval)?
        };

        println!("{}", "📊 All Node Probabilities:".bold().green());
        println!();

        for (name, var_result) in &all_results.queries {
            print_bayesian_var_result(name, var_result);
        }

        if let Some(output_path) = output_file {
            let output_str = format!("{all_results:#?}");
            fs::write(&output_path, output_str).map_err(ForgeError::Io)?;
            println!(
                "{}",
                format!("💾 Results written to {}", output_path.display())
                    .bold()
                    .green()
            );
        }
    }

    println!("{}", "✅ Bayesian inference complete".bold().green());
    Ok(())
}

/// Print real options analysis results
fn print_real_options_results(
    result: &crate::real_options::OptionsResult,
    option_filter: Option<&str>,
    compare_npv: bool,
) {
    println!("{}", "📊 Real Options Results:".bold().green());
    println!();

    if compare_npv {
        println!(
            "   Traditional NPV: {}",
            format!("${:.2}", result.traditional_npv).yellow()
        );
    }

    println!("   {}", "Option Values:".bold());
    for (name, opt_result) in &result.options {
        if let Some(filter) = option_filter {
            if name != filter {
                continue;
            }
        }
        println!(
            "      {} ({}): {}",
            opt_result.name.bright_blue(),
            format!("{:?}", opt_result.option_type).dimmed(),
            format!("${:.2}", opt_result.value).bold().green()
        );
        if let Some(ref trigger) = opt_result.optimal_trigger {
            println!("         Trigger: {trigger}");
        }
        if let Some(prob) = opt_result.probability_exercise {
            println!("         P(exercise): {:.1}%", prob * 100.0);
        }
    }
    println!();

    println!(
        "   Total Option Value: {}",
        format!("${:.2}", result.total_option_value).bold().green()
    );
    println!(
        "   Project Value (with options): {}",
        format!("${:.2}", result.project_value_with_options)
            .bold()
            .green()
    );

    println!();
    println!(
        "   {}: {}",
        "Decision".bold(),
        result.decision.bright_yellow()
    );
    println!("   {}: {}", "Recommendation".bold(), result.recommendation);
    println!();
}

/// Print Bayesian variable result with probability bars
fn print_bayesian_var_result(name: &str, var_result: &crate::bayesian::VariableResult) {
    println!("   {}:", name.bright_blue().bold());
    for (state, prob) in var_result
        .states
        .iter()
        .zip(var_result.probabilities.iter())
    {
        // Truncation/sign-loss impossible: prob is in 0.0..=1.0, result in 0.0..=30.0
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let bar_width = (prob * 30.0) as usize;
        let bar = "".repeat(bar_width.max(1));
        println!("      {:15} |{}| {:.2}%", state, bar.cyan(), prob * 100.0);
    }
    println!();
    println!(
        "   Most likely: {} ({:.1}%)",
        var_result.most_likely.bold().green(),
        var_result.max_probability * 100.0
    );
    println!();
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_scenarios_config_parsing() {
        let yaml = r#"
_forge_version: "9.0.0"

scenarios:
  base_case:
    probability: 0.50
    description: "Base case"
    scalars:
      revenue_growth: 0.05
  bull_case:
    probability: 0.50
    scalars:
      revenue_growth: 0.15

scalars:
  revenue_growth:
    value: 0.05
"#;
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "{yaml}").unwrap();

        // Test config parsing
        let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(value.get("scenarios").is_some());
    }

    #[test]
    fn test_decision_tree_config_parsing() {
        let yaml = r#"
_forge_version: "9.0.0"

decision_tree:
  name: "Test Tree"
  root:
    type: decision
    name: "Start"
    branches:
      yes:
        value: 100
      no:
        value: 0
"#;
        let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(value.get("decision_tree").is_some());
    }

    #[test]
    fn test_bootstrap_config_parsing() {
        let yaml = r#"
_forge_version: "9.0.0"

bootstrap:
  iterations: 1000
  confidence_levels: [0.90, 0.95]
  data: [1.0, 2.0, 3.0, 4.0, 5.0]
  statistic: mean
"#;
        let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(yaml).unwrap();
        let bs_value = value.get("bootstrap").unwrap();
        let config: BootstrapConfig = serde_yaml_ng::from_value(bs_value.clone()).unwrap();
        assert_eq!(config.iterations, 1000);
        assert_eq!(config.data.len(), 5);
    }
}