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
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
//! Analysis commands: variance, sensitivity, `goal_seek`, `break_even`, compare

use crate::core::ArrayCalculator;
use crate::error::{ForgeError, ForgeResult};
use crate::parser;
use colored::Colorize;
use std::fmt::Write as _;
use std::fs;
use std::path::Path;

use super::{apply_scenario, format_number};

/// Variance result for a single variable
#[derive(Debug, Clone)]
pub struct VarianceResult {
    pub name: String,
    pub budget: f64,
    pub actual: f64,
    pub variance: f64,
    pub variance_pct: f64,
    pub is_favorable: bool,
    pub exceeds_threshold: bool,
}

/// Compare scenarios and return structured results (no printing).
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, a scenario does not exist,
/// or calculation fails.
pub fn compare_core(
    file: &Path,
    scenarios: &[String],
) -> ForgeResult<super::results::ComparisonResult> {
    use std::collections::HashMap;

    let base_model = parser::parse_model(file)?;

    for scenario_name in scenarios {
        if !base_model.scenarios.contains_key(scenario_name) {
            let available: Vec<_> = base_model.scenarios.keys().collect();
            return Err(ForgeError::Validation(format!(
                "Scenario '{scenario_name}' not found. Available: {available:?}"
            )));
        }
    }

    let mut results: Vec<(String, crate::types::ParsedModel)> = Vec::new();
    for scenario_name in scenarios {
        let mut model = base_model.clone();
        apply_scenario(&mut model, scenario_name)?;
        let calculator = ArrayCalculator::new(model);
        let calculated = calculator.calculate_all()?;
        results.push((scenario_name.clone(), calculated));
    }

    let mut all_scalars: Vec<String> = results
        .iter()
        .flat_map(|(_, m)| m.scalars.keys().cloned())
        .collect();
    all_scalars.sort();
    all_scalars.dedup();

    let mut values: HashMap<String, HashMap<String, Option<f64>>> = HashMap::new();
    for scalar_name in &all_scalars {
        let mut scenario_values = HashMap::new();
        for (scenario_name, result_model) in &results {
            let val = result_model.scalars.get(scalar_name).and_then(|v| v.value);
            scenario_values.insert(scenario_name.clone(), val);
        }
        values.insert(scalar_name.clone(), scenario_values);
    }

    Ok(super::results::ComparisonResult {
        scenarios: scenarios.to_vec(),
        variables: all_scalars,
        values,
    })
}

/// Execute the compare command - compare results across scenarios
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, a scenario does not exist,
/// or calculation fails.
pub fn compare(file: &Path, scenarios: &[String], verbose: bool) -> ForgeResult<()> {
    println!("{}", "🔥 Forge - Scenario Comparison".bold().green());
    println!("   File: {}", file.display());
    println!(
        "   Scenarios: {}\n",
        scenarios.join(", ").bright_yellow().bold()
    );

    // Parse model
    let base_model = parser::parse_model(file)?;

    // Validate scenarios exist
    for scenario_name in scenarios {
        if !base_model.scenarios.contains_key(scenario_name) {
            let available: Vec<_> = base_model.scenarios.keys().collect();
            return Err(ForgeError::Validation(format!(
                "Scenario '{scenario_name}' not found. Available: {available:?}"
            )));
        }
    }

    if verbose {
        println!(
            "   Found {} tables, {} scalars, {} scenarios",
            base_model.tables.len(),
            base_model.scalars.len(),
            base_model.scenarios.len()
        );
    }

    // Calculate results for each scenario
    let mut results: Vec<(String, crate::types::ParsedModel)> = Vec::new();

    for scenario_name in scenarios {
        let mut model = base_model.clone();
        apply_scenario(&mut model, scenario_name)?;

        let calculator = ArrayCalculator::new(model);
        let calculated = calculator.calculate_all()?;
        results.push((scenario_name.clone(), calculated));
    }

    // Collect all scalar names
    let mut all_scalars: Vec<String> = results
        .iter()
        .flat_map(|(_, m)| m.scalars.keys().cloned())
        .collect();
    all_scalars.sort();
    all_scalars.dedup();

    // Print comparison table
    println!("\n{}", "📊 Scenario Comparison:".bold().cyan());
    println!("{}", "".repeat(20 + scenarios.len() * 15));

    // Header row
    print!("{:<20}", "Variable".bold());
    for scenario_name in scenarios {
        print!("{:>15}", scenario_name.bright_yellow().bold());
    }
    println!();
    println!("{}", "".repeat(20 + scenarios.len() * 15));

    // Data rows
    for scalar_name in &all_scalars {
        print!("{:<20}", scalar_name.bright_blue());

        for (_, result_model) in &results {
            if let Some(var) = result_model.scalars.get(scalar_name) {
                if let Some(value) = var.value {
                    print!("{:>15}", format_number(value).green());
                } else {
                    print!("{:>15}", "-".dimmed());
                }
            } else {
                print!("{:>15}", "-".dimmed());
            }
        }
        println!();
    }

    println!("{}", "".repeat(20 + scenarios.len() * 15));
    println!("\n{}", "✅ Comparison complete".bold().green());

    Ok(())
}

/// Compute variance analysis and return structured results (no printing).
///
/// # Errors
///
/// Returns an error if the budget or actual files cannot be parsed or calculation fails.
pub fn variance_core(
    budget_path: &Path,
    actual_path: &Path,
    threshold: f64,
) -> ForgeResult<super::results::VarianceAnalysis> {
    let budget_model = parser::parse_model(budget_path)?;
    let actual_model = parser::parse_model(actual_path)?;

    let budget_calculator = ArrayCalculator::new(budget_model);
    let budget_result = budget_calculator.calculate_all()?;

    let actual_calculator = ArrayCalculator::new(actual_model);
    let actual_result = actual_calculator.calculate_all()?;

    let variances = collect_variances(&budget_result, &actual_result, threshold);

    let favorable_count = variances.iter().filter(|v| v.is_favorable).count();
    let unfavorable_count = variances.len() - favorable_count;
    let alert_count = variances.iter().filter(|v| v.exceeds_threshold).count();

    let entries = variances
        .into_iter()
        .map(|v| super::results::VarianceEntry {
            name: v.name,
            budget: v.budget,
            actual: v.actual,
            variance: v.variance,
            variance_pct: v.variance_pct,
            is_favorable: v.is_favorable,
            exceeds_threshold: v.exceeds_threshold,
        })
        .collect();

    Ok(super::results::VarianceAnalysis {
        results: entries,
        favorable_count,
        unfavorable_count,
        alert_count,
        threshold,
    })
}

/// Execute the variance command - budget vs actual analysis
///
/// # Errors
///
/// Returns an error if the budget or actual files cannot be parsed, calculation fails,
/// or the output file cannot be written.
pub fn variance(
    budget_path: &Path,
    actual_path: &Path,
    threshold: f64,
    output: Option<&Path>,
    verbose: bool,
) -> ForgeResult<()> {
    println!("{}", "🔥 Forge - Variance Analysis".bold().green());
    println!("   Budget: {}", budget_path.display());
    println!("   Actual: {}", actual_path.display());
    println!("   Threshold: {threshold}%\n");

    // Parse both files
    if verbose {
        println!("{}", "📖 Parsing YAML files...".cyan());
    }

    let budget_model = parser::parse_model(budget_path)?;
    let actual_model = parser::parse_model(actual_path)?;

    // Calculate both models
    if verbose {
        println!("{}", "🧮 Calculating formulas...".cyan());
    }

    let budget_calculator = ArrayCalculator::new(budget_model);
    let budget_result = budget_calculator.calculate_all()?;

    let actual_calculator = ArrayCalculator::new(actual_model);
    let actual_result = actual_calculator.calculate_all()?;

    let variances = collect_variances(&budget_result, &actual_result, threshold);

    // Handle output
    if let Some(output_path) = output {
        let extension = output_path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("");

        match extension {
            "xlsx" => {
                export_variance_to_excel(output_path, &variances, threshold)?;
                println!(
                    "{}",
                    format!("✅ Variance report exported to {}", output_path.display())
                        .bold()
                        .green()
                );
            },
            "yaml" | "yml" => {
                export_variance_to_yaml(output_path, &variances, threshold)?;
                println!(
                    "{}",
                    format!("✅ Variance report exported to {}", output_path.display())
                        .bold()
                        .green()
                );
            },
            _ => {
                return Err(ForgeError::Export(format!(
                    "Unsupported output format: {extension}. Use .xlsx or .yaml"
                )));
            },
        }
    } else {
        // Print to terminal
        print_variance_table(&variances, threshold);
    }

    // Summary
    let favorable_count = variances.iter().filter(|v| v.is_favorable).count();
    let unfavorable_count = variances.len() - favorable_count;
    let alert_count = variances.iter().filter(|v| v.exceeds_threshold).count();

    println!();
    println!(
        "   {} Favorable: {}  {} Unfavorable: {}  {} Alerts (>{:.0}%): {}",
        "".green(),
        favorable_count.to_string().green(),
        "".red(),
        unfavorable_count.to_string().red(),
        "⚠️".yellow(),
        threshold,
        alert_count.to_string().yellow()
    );

    Ok(())
}

/// Collect scalar variances between budget and actual calculation results
fn collect_variances(
    budget_result: &crate::types::ParsedModel,
    actual_result: &crate::types::ParsedModel,
    threshold: f64,
) -> Vec<VarianceResult> {
    let mut all_scalars: Vec<String> = budget_result
        .scalars
        .keys()
        .chain(actual_result.scalars.keys())
        .cloned()
        .collect();
    all_scalars.sort();
    all_scalars.dedup();

    let mut variances = Vec::new();
    for name in &all_scalars {
        let budget_val = budget_result
            .scalars
            .get(name)
            .and_then(|v| v.value)
            .unwrap_or(0.0);
        let actual_val = actual_result
            .scalars
            .get(name)
            .and_then(|v| v.value)
            .unwrap_or(0.0);

        let variance_abs = actual_val - budget_val;
        let variance_pct = if budget_val.abs() > 0.0001 {
            (variance_abs / budget_val) * 100.0
        } else {
            0.0
        };

        // Determine favorability (heuristic based on name)
        let is_expense = name.to_lowercase().contains("expense")
            || name.to_lowercase().contains("cost")
            || name.to_lowercase().contains("cogs");
        let is_favorable = if is_expense {
            actual_val <= budget_val // Lower expenses = favorable
        } else {
            actual_val >= budget_val // Higher revenue/profit = favorable
        };

        let exceeds_threshold = variance_pct.abs() >= threshold;

        variances.push(VarianceResult {
            name: name.clone(),
            budget: budget_val,
            actual: actual_val,
            variance: variance_abs,
            variance_pct,
            is_favorable,
            exceeds_threshold,
        });
    }
    variances
}

/// Print variance results as a table
pub fn print_variance_table(variances: &[VarianceResult], threshold: f64) {
    println!("\n{}", "📊 Budget vs Actual Variance:".bold().cyan());
    println!("{}", "".repeat(85));

    // Header
    println!(
        "{:<20} {:>12} {:>12} {:>12} {:>10} {:>8}",
        "Variable".bold(),
        "Budget".bold(),
        "Actual".bold(),
        "Variance".bold(),
        "Var %".bold(),
        "Status".bold()
    );
    println!("{}", "".repeat(85));

    // Data rows
    for v in variances {
        let var_str = format_number(v.variance);
        let pct_str = format!("{:.1}%", v.variance_pct);

        let status = if v.exceeds_threshold && !v.is_favorable {
            "⚠️ ❌".to_string()
        } else if v.exceeds_threshold {
            "⚠️ ✅".to_string()
        } else if v.is_favorable {
            "".to_string()
        } else {
            "".to_string()
        };

        // Color the variance based on favorability
        let var_colored = if v.is_favorable {
            var_str.green()
        } else {
            var_str.red()
        };
        let pct_colored = if v.is_favorable {
            pct_str.green()
        } else {
            pct_str.red()
        };

        println!(
            "{:<20} {:>12} {:>12} {:>12} {:>10} {:>8}",
            v.name.bright_blue(),
            format_number(v.budget),
            format_number(v.actual),
            var_colored,
            pct_colored,
            status
        );
    }

    println!("{}", "".repeat(85));
    println!("   {} = exceeds {:.0}% threshold", "⚠️".yellow(), threshold);
}

/// Export variance report to Excel
///
/// # Errors
///
/// Returns an error if the Excel workbook cannot be created or saved.
pub fn export_variance_to_excel(
    output: &Path,
    variances: &[VarianceResult],
    threshold: f64,
) -> ForgeResult<()> {
    use rust_xlsxwriter::{Format, Workbook};

    let mut workbook = Workbook::new();
    let worksheet = workbook.add_worksheet();

    // Set column widths
    worksheet.set_column_width(0, 20).ok();
    worksheet.set_column_width(1, 12).ok();
    worksheet.set_column_width(2, 12).ok();
    worksheet.set_column_width(3, 12).ok();
    worksheet.set_column_width(4, 10).ok();
    worksheet.set_column_width(5, 10).ok();

    // Header format
    let header_format = Format::new().set_bold();

    // Headers
    worksheet
        .write_string_with_format(0, 0, "Variable", &header_format)
        .ok();
    worksheet
        .write_string_with_format(0, 1, "Budget", &header_format)
        .ok();
    worksheet
        .write_string_with_format(0, 2, "Actual", &header_format)
        .ok();
    worksheet
        .write_string_with_format(0, 3, "Variance", &header_format)
        .ok();
    worksheet
        .write_string_with_format(0, 4, "Var %", &header_format)
        .ok();
    worksheet
        .write_string_with_format(0, 5, "Status", &header_format)
        .ok();

    // Data rows
    for (i, v) in variances.iter().enumerate() {
        // Truncation impossible: variance reports have far fewer than u32::MAX rows
        #[allow(clippy::cast_possible_truncation)]
        let row = (i + 1) as u32;

        worksheet.write_string(row, 0, &v.name).ok();
        worksheet.write_number(row, 1, v.budget).ok();
        worksheet.write_number(row, 2, v.actual).ok();
        worksheet.write_number(row, 3, v.variance).ok();
        worksheet.write_number(row, 4, v.variance_pct / 100.0).ok(); // As decimal for %

        let status = if v.exceeds_threshold && !v.is_favorable {
            "ALERT - Unfavorable"
        } else if v.exceeds_threshold {
            "ALERT - Favorable"
        } else if v.is_favorable {
            "Favorable"
        } else {
            "Unfavorable"
        };
        worksheet.write_string(row, 5, status).ok();
    }

    // Add metadata row
    // Truncation impossible: variance reports have far fewer than u32::MAX rows
    #[allow(clippy::cast_possible_truncation)]
    let meta_row = (variances.len() + 3) as u32;
    worksheet
        .write_string(meta_row, 0, format!("Threshold: {threshold}%"))
        .ok();
    worksheet
        .write_string(meta_row + 1, 0, "Generated by Forge v2.3.0")
        .ok();

    workbook
        .save(output)
        .map_err(|e| ForgeError::Export(e.to_string()))?;

    Ok(())
}

/// Export variance report to YAML
///
/// # Errors
///
/// Returns an error if the output file cannot be created or written.
pub fn export_variance_to_yaml(
    output: &Path,
    variances: &[VarianceResult],
    threshold: f64,
) -> ForgeResult<()> {
    use std::io::Write as IoWrite;

    let mut content = String::new();
    content.push_str("# Forge Variance Analysis Report\n");
    content.push_str("# Generated by Forge v2.3.0\n");
    let _ = writeln!(content, "# Threshold: {threshold}%\n");

    content.push_str("metadata:\n");
    let _ = writeln!(content, "  threshold_pct: {threshold}");
    let _ = writeln!(content, "  total_items: {}", variances.len());
    let _ = writeln!(
        content,
        "  favorable_count: {}",
        variances.iter().filter(|v| v.is_favorable).count()
    );
    let _ = writeln!(
        content,
        "  alert_count: {}\n",
        variances.iter().filter(|v| v.exceeds_threshold).count()
    );

    content.push_str("variances:\n");
    for v in variances {
        let _ = writeln!(content, "  {}:", v.name);
        let _ = writeln!(content, "    budget: {}", v.budget);
        let _ = writeln!(content, "    actual: {}", v.actual);
        let _ = writeln!(content, "    variance: {}", v.variance);
        let _ = writeln!(content, "    variance_pct: {:.2}", v.variance_pct);
        let _ = writeln!(content, "    is_favorable: {}", v.is_favorable);
        let _ = writeln!(content, "    exceeds_threshold: {}", v.exceeds_threshold);
    }

    let mut file = fs::File::create(output)
        .map_err(|e| ForgeError::Export(format!("Failed to create file: {e}")))?;
    file.write_all(content.as_bytes())
        .map_err(|e| ForgeError::Export(format!("Failed to write file: {e}")))?;

    Ok(())
}

/// Parse a range string "start,end,step" into a vector of values
///
/// # Errors
///
/// Returns an error if the range format is invalid, values cannot be parsed,
/// step is non-positive, or start exceeds end.
pub fn parse_range(range: &str) -> ForgeResult<Vec<f64>> {
    let parts: Vec<&str> = range.split(',').collect();
    if parts.len() != 3 {
        return Err(ForgeError::Validation(format!(
            "Invalid range format '{range}'. Expected: start,end,step (e.g., 0.01,0.15,0.02)"
        )));
    }

    let start: f64 = parts[0]
        .trim()
        .parse()
        .map_err(|_| ForgeError::Validation(format!("Invalid start value: '{}'", parts[0])))?;
    let end: f64 = parts[1]
        .trim()
        .parse()
        .map_err(|_| ForgeError::Validation(format!("Invalid end value: '{}'", parts[1])))?;
    let step: f64 = parts[2]
        .trim()
        .parse()
        .map_err(|_| ForgeError::Validation(format!("Invalid step value: '{}'", parts[2])))?;

    if step <= 0.0 {
        return Err(ForgeError::Validation("Step must be positive".to_string()));
    }
    if start > end {
        return Err(ForgeError::Validation(
            "Start must be less than or equal to end".to_string(),
        ));
    }

    // Use integer step count to avoid while-float comparison
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    // step count is always a small positive number
    let num_steps = ((end - start) / step + 1.001).floor() as usize;
    #[allow(clippy::cast_precision_loss)] // step index is always small enough for f64
    let values: Vec<f64> = (0..num_steps)
        .map(|i| step.mul_add(i as f64, start))
        .collect();

    Ok(values)
}

/// Calculate model with a specific variable override and return the output value
///
/// # Errors
///
/// Returns an error if calculation fails or the output variable is not found.
pub fn calculate_with_override(
    base_model: &crate::types::ParsedModel,
    var_name: &str,
    var_value: f64,
    output_name: &str,
) -> ForgeResult<f64> {
    let mut model = base_model.clone();

    // Override the variable
    if let Some(scalar) = model.scalars.get_mut(var_name) {
        scalar.value = Some(var_value);
        scalar.formula = None; // Clear formula since we're using override
    } else {
        // Create new scalar
        model.scalars.insert(
            var_name.to_string(),
            crate::types::Variable::new(var_name.to_string(), Some(var_value), None),
        );
    }

    // Calculate
    let calculator = ArrayCalculator::new(model);
    let result = calculator.calculate_all()?;

    // Get output value
    result.scalars.get(output_name).map_or_else(
        || {
            Err(ForgeError::Validation(format!(
                "Output variable '{output_name}' not found in model"
            )))
        },
        |scalar| {
            scalar.value.ok_or_else(|| {
                ForgeError::Validation(format!("Output variable '{output_name}' has no value"))
            })
        },
    )
}

/// Run sensitivity analysis and return structured results (no printing).
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, variables are not found,
/// ranges are invalid, or calculation fails.
pub fn sensitivity_core(
    file: &Path,
    vary: &str,
    range: &str,
    vary2: Option<&str>,
    range2: Option<&str>,
    output: &str,
) -> ForgeResult<super::results::SensitivityResult> {
    let base_model = parser::parse_model(file)?;

    if !base_model.scalars.contains_key(vary) {
        return Err(ForgeError::Validation(format!(
            "Variable '{}' not found. Available scalars: {:?}",
            vary,
            base_model.scalars.keys().collect::<Vec<_>>()
        )));
    }

    let values1 = parse_range(range)?;

    let data = if let (Some(v2), Some(r2)) = (vary2, range2) {
        if !base_model.scalars.contains_key(v2) {
            return Err(ForgeError::Validation(format!(
                "Variable '{}' not found. Available scalars: {:?}",
                v2,
                base_model.scalars.keys().collect::<Vec<_>>()
            )));
        }
        let values2 = parse_range(r2)?;
        let mut matrix = Vec::new();
        for val1 in &values1 {
            let mut row = Vec::new();
            for val2 in &values2 {
                let mut model = base_model.clone();
                if let Some(s) = model.scalars.get_mut(vary) {
                    s.value = Some(*val1);
                    s.formula = None;
                }
                if let Some(s) = model.scalars.get_mut(v2) {
                    s.value = Some(*val2);
                    s.formula = None;
                }
                let calculator = ArrayCalculator::new(model);
                let cell = match calculator.calculate_all() {
                    Ok(result) => result.scalars.get(output).and_then(|s| s.value),
                    Err(_) => None,
                };
                row.push(cell);
            }
            matrix.push(row);
        }
        super::results::SensitivityData::TwoVar {
            vary2: v2.to_string(),
            row_values: values1,
            col_values: values2,
            matrix,
        }
    } else {
        let mut entries = Vec::new();
        for val in &values1 {
            match calculate_with_override(&base_model, vary, *val, output) {
                Ok(result) => entries.push(super::results::SensitivityEntry {
                    input: *val,
                    output: Some(result),
                    error: None,
                }),
                Err(e) => entries.push(super::results::SensitivityEntry {
                    input: *val,
                    output: None,
                    error: Some(e.to_string()),
                }),
            }
        }
        super::results::SensitivityData::OneVar { entries }
    };

    Ok(super::results::SensitivityResult {
        vary: vary.to_string(),
        output: output.to_string(),
        data,
    })
}

/// Execute the sensitivity command
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, variables are not found,
/// ranges are invalid, or calculation fails.
pub fn sensitivity(
    file: &Path,
    vary: &str,
    range: &str,
    vary2: Option<&str>,
    range2: Option<&str>,
    output: &str,
    verbose: bool,
) -> ForgeResult<()> {
    println!("{}", "🔥 Forge - Sensitivity Analysis".bold().green());
    println!("   File: {}", file.display());
    println!("   Vary: {} ({})", vary.bright_yellow(), range);
    if let Some(v2) = vary2 {
        println!(
            "   Vary2: {} ({})",
            v2.bright_yellow(),
            range2.unwrap_or("?")
        );
    }
    println!("   Output: {}\n", output.bright_blue());

    // Parse model
    let base_model = parser::parse_model(file)?;

    // Validate that vary variable exists
    if !base_model.scalars.contains_key(vary) {
        return Err(ForgeError::Validation(format!(
            "Variable '{}' not found. Available scalars: {:?}",
            vary,
            base_model.scalars.keys().collect::<Vec<_>>()
        )));
    }

    // Parse range
    let values1 = parse_range(range)?;

    if verbose {
        println!(
            "   Range 1: {} values from {} to {}",
            values1.len(),
            values1.first().unwrap_or(&0.0),
            values1.last().unwrap_or(&0.0)
        );
    }

    // Two-variable analysis
    if let (Some(v2), Some(r2)) = (vary2, range2) {
        run_two_var_sensitivity(&base_model, vary, v2, r2, output, &values1, verbose)?;
    } else {
        // One-variable analysis
        println!(
            "\n{} {}{}",
            "📊 Sensitivity Table:".bold().cyan(),
            vary.yellow(),
            output.bright_blue()
        );
        println!("{}", "".repeat(30));
        println!("{:>12} {:>15}", vary.bold(), output.bold());
        println!("{}", "".repeat(30));

        for val in &values1 {
            match calculate_with_override(&base_model, vary, *val, output) {
                Ok(result) => {
                    println!(
                        "{:>12} {:>15}",
                        format!("{val:.4}").bright_yellow(),
                        format_number(result).green()
                    );
                },
                Err(e) => {
                    println!(
                        "{:>12} {:>15}",
                        format!("{val:.4}").bright_yellow(),
                        format!("ERR: {e}").red()
                    );
                },
            }
        }
        println!("{}", "".repeat(30));
    }

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

/// Run goal-seek and return structured results (no printing).
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, variables are not found,
/// or no solution exists in the search range.
pub fn goal_seek_core(
    file: &Path,
    target: &str,
    value: f64,
    vary: &str,
    bounds: (Option<f64>, Option<f64>),
    tolerance: f64,
) -> ForgeResult<super::results::GoalSeekResult> {
    let (min, max) = bounds;
    let base_model = parser::parse_model(file)?;

    if !base_model.scalars.contains_key(vary) {
        return Err(ForgeError::Validation(format!(
            "Variable '{}' not found. Available scalars: {:?}",
            vary,
            base_model.scalars.keys().collect::<Vec<_>>()
        )));
    }

    let current_value = base_model
        .scalars
        .get(vary)
        .and_then(|s| s.value)
        .unwrap_or(1.0);

    let lower = min.unwrap_or_else(|| {
        if current_value > 0.0 {
            current_value * 0.01
        } else if current_value < 0.0 {
            current_value * 100.0
        } else {
            -1000.0
        }
    });
    let upper = max.unwrap_or(if current_value > 0.0 {
        current_value * 100.0
    } else if current_value < 0.0 {
        current_value * 0.01
    } else {
        1000.0
    });

    let mut low = lower;
    let mut high = upper;

    let f_low = calculate_with_override(&base_model, vary, low, target)? - value;
    let f_high = calculate_with_override(&base_model, vary, high, target)? - value;

    if f_low * f_high > 0.0 {
        let expanded = expand_search_range_quiet(&base_model, vary, target, value, lower, upper)?;
        low = expanded.0;
        high = expanded.1;
    }

    let max_iterations = 100;
    let mut mid = f64::midpoint(low, high);
    let mut iteration = 0;

    while (high - low) > tolerance && iteration < max_iterations {
        mid = f64::midpoint(low, high);
        let f_mid = calculate_with_override(&base_model, vary, mid, target)? - value;
        let f_low_check = calculate_with_override(&base_model, vary, low, target)? - value;

        if f_mid.abs() < tolerance {
            break;
        }

        if f_low_check * f_mid < 0.0 {
            high = mid;
        } else {
            low = mid;
        }

        iteration += 1;
    }

    let final_value = calculate_with_override(&base_model, vary, mid, target)?;
    let error = (final_value - value).abs();

    Ok(super::results::GoalSeekResult {
        vary: vary.to_string(),
        target: target.to_string(),
        target_value: value,
        solution: mid,
        achieved: final_value,
        error,
        iterations: iteration,
        converged: error < tolerance,
    })
}

/// Expand search range without printing (for core function)
fn expand_search_range_quiet(
    base_model: &crate::types::ParsedModel,
    vary: &str,
    target: &str,
    value: f64,
    lower: f64,
    upper: f64,
) -> ForgeResult<(f64, f64)> {
    for factor in [10.0, 100.0, 1000.0] {
        let exp_low = if lower > 0.0 {
            lower / factor
        } else {
            lower * factor
        };
        let exp_high = if upper > 0.0 {
            upper * factor
        } else {
            upper / factor
        };

        let f_exp_low = calculate_with_override(base_model, vary, exp_low, target)? - value;
        let f_exp_high = calculate_with_override(base_model, vary, exp_high, target)? - value;

        if f_exp_low * f_exp_high <= 0.0 {
            return Ok((exp_low, exp_high));
        }
    }

    Err(ForgeError::Validation(format!(
        "No solution found in search range. The target value {value} may not be achievable by varying '{vary}'."
    )))
}

/// Execute the goal-seek command
///
/// # Errors
///
/// Returns an error if the file cannot be parsed, variables are not found,
/// or no solution exists in the search range.
pub fn goal_seek(
    file: &Path,
    target: &str,
    value: f64,
    vary: &str,
    bounds: (Option<f64>, Option<f64>),
    tolerance: f64,
    verbose: bool,
) -> ForgeResult<()> {
    let (min, max) = bounds;
    println!("{}", "🔥 Forge - Goal Seek".bold().green());
    println!("   File: {}", file.display());
    println!("   Target: {} = {}", target.bright_blue(), value);
    println!("   Vary: {}", vary.bright_yellow());
    println!("   Tolerance: {tolerance}\n");

    // Parse model
    let base_model = parser::parse_model(file)?;

    // Validate variables
    if !base_model.scalars.contains_key(vary) {
        return Err(ForgeError::Validation(format!(
            "Variable '{}' not found. Available scalars: {:?}",
            vary,
            base_model.scalars.keys().collect::<Vec<_>>()
        )));
    }

    // Get current value of vary to set default bounds
    let current_value = base_model
        .scalars
        .get(vary)
        .and_then(|s| s.value)
        .unwrap_or(1.0);

    // Set bounds (default: 0.01x to 100x current value)
    let lower = min.unwrap_or_else(|| {
        if current_value > 0.0 {
            current_value * 0.01
        } else if current_value < 0.0 {
            current_value * 100.0
        } else {
            -1000.0
        }
    });
    let upper = max.unwrap_or(if current_value > 0.0 {
        current_value * 100.0
    } else if current_value < 0.0 {
        current_value * 0.01
    } else {
        1000.0
    });

    if verbose {
        println!("   Current value of {vary}: {current_value}");
        println!("   Search bounds: [{lower}, {upper}]");
    }

    // Bisection method
    let max_iterations = 100;
    let mut low = lower;
    let mut high = upper;

    // Check bounds first
    let f_low = calculate_with_override(&base_model, vary, low, target)? - value;
    let f_high = calculate_with_override(&base_model, vary, high, target)? - value;

    if verbose {
        println!("   f({}) = {} (target diff: {})", low, f_low + value, f_low);
        println!(
            "   f({}) = {} (target diff: {})",
            high,
            f_high + value,
            f_high
        );
    }

    // Check if solution exists in range (signs should differ)
    if f_low * f_high > 0.0 {
        let expanded =
            expand_search_range(&base_model, vary, target, value, lower, upper, verbose)?;
        low = expanded.0;
        high = expanded.1;
    }

    // Bisection iteration
    let mut mid = f64::midpoint(low, high);
    let mut iteration = 0;

    while (high - low) > tolerance && iteration < max_iterations {
        mid = f64::midpoint(low, high);
        let f_mid = calculate_with_override(&base_model, vary, mid, target)? - value;

        if verbose && iteration % 10 == 0 {
            println!(
                "   Iteration {}: {} = {} (diff: {:.6})",
                iteration,
                vary,
                mid,
                f_mid.abs()
            );
        }

        let f_low_check = calculate_with_override(&base_model, vary, low, target)? - value;

        if f_mid.abs() < tolerance {
            break;
        }

        if f_low_check * f_mid < 0.0 {
            high = mid;
        } else {
            low = mid;
        }

        iteration += 1;
    }

    // Final result
    let final_value = calculate_with_override(&base_model, vary, mid, target)?;
    print_goal_seek_result(vary, target, mid, final_value, value, tolerance, iteration);
    Ok(())
}

/// Run two-variable sensitivity analysis matrix
fn run_two_var_sensitivity(
    base_model: &crate::types::ParsedModel,
    vary: &str,
    v2: &str,
    r2: &str,
    output: &str,
    values1: &[f64],
    verbose: bool,
) -> ForgeResult<()> {
    if !base_model.scalars.contains_key(v2) {
        return Err(ForgeError::Validation(format!(
            "Variable '{}' not found. Available scalars: {:?}",
            v2,
            base_model.scalars.keys().collect::<Vec<_>>()
        )));
    }

    let values2 = parse_range(r2)?;

    if verbose {
        println!(
            "   Range 2: {} values from {} to {}",
            values2.len(),
            values2.first().unwrap_or(&0.0),
            values2.last().unwrap_or(&0.0)
        );
    }

    // Calculate matrix
    println!(
        "\n{} {}{}",
        "📊 Sensitivity Matrix:".bold().cyan(),
        format!("({vary}, {v2})").yellow(),
        output.bright_blue()
    );

    // Header row
    print!("{:>12}", vary.bright_yellow());
    for val2 in &values2 {
        print!("{:>12}", format!("{val2:.4}").dimmed());
    }
    println!();
    println!("{}", "".repeat(12 + values2.len() * 12));

    // Data rows
    for val1 in values1 {
        print!("{:>12}", format!("{val1:.4}").bright_yellow());

        for val2 in &values2 {
            let mut model = base_model.clone();

            if let Some(s) = model.scalars.get_mut(vary) {
                s.value = Some(*val1);
                s.formula = None;
            }
            if let Some(s) = model.scalars.get_mut(v2) {
                s.value = Some(*val2);
                s.formula = None;
            }

            let calculator = ArrayCalculator::new(model);
            match calculator.calculate_all() {
                Ok(result) => {
                    if let Some(scalar) = result.scalars.get(output) {
                        if let Some(v) = scalar.value {
                            print!("{:>12}", format_number(v).green());
                        } else {
                            print!("{:>12}", "-".dimmed());
                        }
                    } else {
                        print!("{:>12}", "?".red());
                    }
                },
                Err(_) => {
                    print!("{:>12}", "ERR".red());
                },
            }
        }
        println!();
    }
    Ok(())
}

/// Expand the search range when initial bounds have the same sign
fn expand_search_range(
    base_model: &crate::types::ParsedModel,
    vary: &str,
    target: &str,
    value: f64,
    lower: f64,
    upper: f64,
    verbose: bool,
) -> ForgeResult<(f64, f64)> {
    println!(
        "{}",
        "⚠️  No sign change in initial range - expanding search...".yellow()
    );

    for factor in [10.0, 100.0, 1000.0] {
        let exp_low = if lower > 0.0 {
            lower / factor
        } else {
            lower * factor
        };
        let exp_high = if upper > 0.0 {
            upper * factor
        } else {
            upper / factor
        };

        let f_exp_low = calculate_with_override(base_model, vary, exp_low, target)? - value;
        let f_exp_high = calculate_with_override(base_model, vary, exp_high, target)? - value;

        if f_exp_low * f_exp_high <= 0.0 {
            if verbose {
                println!("   Found valid range: [{exp_low}, {exp_high}]");
            }
            return Ok((exp_low, exp_high));
        }
    }

    Err(ForgeError::Validation(format!(
        "No solution found in search range. The target value {value} may not be achievable by varying '{vary}'."
    )))
}

/// Print goal-seek result summary
fn print_goal_seek_result(
    vary: &str,
    target: &str,
    mid: f64,
    final_value: f64,
    value: f64,
    tolerance: f64,
    iteration: i32,
) {
    println!("{}", "".repeat(50));
    println!(
        "{}",
        format!("🎯 Solution found in {iteration} iterations:")
            .bold()
            .green()
    );
    println!(
        "   {} = {}{} = {}",
        vary.bright_yellow().bold(),
        format_number(mid).bold().green(),
        target.bright_blue(),
        format_number(final_value).green()
    );

    let error = (final_value - value).abs();
    if error < tolerance {
        println!("   {} Within tolerance", "".green());
    } else {
        println!(
            "   {} Error: {} (tolerance: {})",
            "⚠️".yellow(),
            error,
            tolerance
        );
    }
    println!("{}", "".repeat(50));
}

/// Execute the break-even command
///
/// # Errors
///
/// Returns an error if goal-seek fails to find a zero-crossing point.
pub fn break_even(
    file: &Path,
    output: &str,
    vary: &str,
    min: Option<f64>,
    max: Option<f64>,
    verbose: bool,
) -> ForgeResult<()> {
    println!("{}", "🔥 Forge - Break-Even Analysis".bold().green());
    println!("   Finding where {} = 0\n", output.bright_blue());

    // Break-even is just goal-seek with value = 0
    goal_seek(file, output, 0.0, vary, (min, max), 0.0001, verbose)
}