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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

//==============================================================================
// Forge v1.0.0 Array Model Types
//==============================================================================

/// Column value types (homogeneous arrays)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ColumnValue {
    /// Array of numbers (f64)
    Number(Vec<f64>),
    /// Array of text strings
    Text(Vec<String>),
    /// Array of ISO date strings (YYYY-MM or YYYY-MM-DD)
    Date(Vec<String>),
    /// Array of booleans
    Boolean(Vec<bool>),
}

impl ColumnValue {
    /// Get the length of the array
    #[must_use]
    pub const fn len(&self) -> usize {
        match self {
            Self::Number(v) => v.len(),
            Self::Text(v) | Self::Date(v) => v.len(),
            Self::Boolean(v) => v.len(),
        }
    }

    /// Check if array is empty
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Get the type name as a string
    #[must_use]
    pub const fn type_name(&self) -> &'static str {
        match self {
            Self::Number(_) => "Number",
            Self::Text(_) => "Text",
            Self::Date(_) => "Date",
            Self::Boolean(_) => "Boolean",
        }
    }
}

/// A column in a table (v4.0 enhanced with metadata)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Column {
    pub name: String,
    pub values: ColumnValue,
    /// Rich metadata (v4.0) - unit, notes, source, `validation_status`
    #[serde(default)]
    pub metadata: Metadata,
}

impl Column {
    #[must_use]
    pub fn new(name: String, values: ColumnValue) -> Self {
        Self {
            name,
            values,
            metadata: Metadata::default(),
        }
    }

    #[must_use]
    pub const fn with_metadata(name: String, values: ColumnValue, metadata: Metadata) -> Self {
        Self {
            name,
            values,
            metadata,
        }
    }

    #[must_use]
    pub const fn len(&self) -> usize {
        self.values.len()
    }

    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.values.is_empty()
    }
}

/// A table with column arrays
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Table {
    pub name: String,
    pub columns: HashMap<String, Column>,
    /// Row-wise formulas (e.g., "profit: =revenue - expenses")
    pub row_formulas: HashMap<String, String>,
}

impl Table {
    #[must_use]
    pub fn new(name: String) -> Self {
        Self {
            name,
            columns: HashMap::new(),
            row_formulas: HashMap::new(),
        }
    }

    pub fn add_column(&mut self, column: Column) {
        self.columns.insert(column.name.clone(), column);
    }

    pub fn add_row_formula(&mut self, name: String, formula: String) {
        self.row_formulas.insert(name, formula);
    }

    /// Get the number of rows (length of first column, all should be same)
    pub fn row_count(&self) -> usize {
        self.columns.values().next().map_or(0, Column::len)
    }

    /// Validate all columns have the same length
    ///
    /// # Errors
    ///
    /// Returns an error if any column has a different length than the first column.
    pub fn validate_lengths(&self) -> Result<(), String> {
        let row_count = self.row_count();
        for (name, column) in &self.columns {
            if column.len() != row_count {
                return Err(format!(
                    "Column '{}' has {} rows, expected {} rows",
                    name,
                    column.len(),
                    row_count
                ));
            }
        }
        Ok(())
    }
}

//==============================================================================
// Scalar Variables (for aggregations and summary values)
//==============================================================================

/// Rich metadata for enterprise financial models (v4.0)
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Metadata {
    /// Unit of measurement (CAD, USD, %, count, days, ratio)
    pub unit: Option<String>,
    /// Human-readable explanation
    pub notes: Option<String>,
    /// Source reference (<file:field> or URL)
    pub source: Option<String>,
    /// Validation status (VALIDATED, PROJECTED, ESTIMATED)
    pub validation_status: Option<String>,
    /// Last updated timestamp
    pub last_updated: Option<String>,
}

impl Metadata {
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.unit.is_none()
            && self.notes.is_none()
            && self.source.is_none()
            && self.validation_status.is_none()
            && self.last_updated.is_none()
    }
}

/// A scalar variable with optional formula and metadata (v4.0 enhanced)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Variable {
    pub path: String,
    pub value: Option<f64>,
    pub formula: Option<String>,
    /// Rich metadata (v4.0) - unit, notes, source, `validation_status`
    #[serde(default)]
    pub metadata: Metadata,
}

impl Variable {
    /// Create a new variable with default (empty) metadata
    #[must_use]
    pub fn new(path: String, value: Option<f64>, formula: Option<String>) -> Self {
        Self {
            path,
            value,
            formula,
            metadata: Metadata::default(),
        }
    }

    /// Create a new variable with metadata (v4.0)
    #[must_use]
    pub const fn with_metadata(
        path: String,
        value: Option<f64>,
        formula: Option<String>,
        metadata: Metadata,
    ) -> Self {
        Self {
            path,
            value,
            formula,
            metadata,
        }
    }
}

//==============================================================================
// Cross-File References (v4.0)
//==============================================================================

/// An include directive for cross-file references (v4.0)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Include {
    /// Path to the included file (relative to current file)
    pub file: String,
    /// Namespace alias for referencing (e.g., "sources" for @sources.field)
    pub namespace: String,
}

impl Include {
    #[must_use]
    pub const fn new(file: String, namespace: String) -> Self {
        Self { file, namespace }
    }
}

/// Resolved include with parsed model data
#[derive(Debug, Clone)]
pub struct ResolvedInclude {
    /// The include directive
    pub include: Include,
    /// Resolved absolute path
    pub resolved_path: std::path::PathBuf,
    /// Parsed model from the included file
    pub model: ParsedModel,
}

//==============================================================================
// Scenarios (for multi-scenario modeling)
//==============================================================================

/// A named scenario with variable overrides
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Scenario {
    /// Variable overrides for this scenario (`variable_name` -> value)
    pub overrides: HashMap<String, f64>,
}

impl Scenario {
    #[must_use]
    pub fn new() -> Self {
        Self {
            overrides: HashMap::new(),
        }
    }

    pub fn add_override(&mut self, name: String, value: f64) {
        self.overrides.insert(name, value);
    }
}

//==============================================================================
// Parsed Model
//==============================================================================

/// Parsed Forge model (v4.0 with cross-file references)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParsedModel {
    /// Tables with column arrays
    pub tables: HashMap<String, Table>,

    /// Scalar variables (for summary values and aggregations)
    pub scalars: HashMap<String, Variable>,

    /// Aggregation formulas (formulas that reduce columns to scalars)
    pub aggregations: HashMap<String, String>,

    /// Named scenarios with variable overrides
    pub scenarios: HashMap<String, Scenario>,

    /// Cross-file includes (v4.0) - parsed but not yet resolved
    #[serde(default)]
    pub includes: Vec<Include>,

    /// Resolved includes with loaded models (populated after resolution)
    #[serde(skip)]
    pub resolved_includes: HashMap<String, ResolvedInclude>,

    /// Document names from multi-document YAML files (v4.4.2)
    /// Empty for single-document files
    #[serde(default)]
    pub documents: Vec<String>,
}

impl ParsedModel {
    #[must_use]
    pub fn new() -> Self {
        Self {
            tables: HashMap::new(),
            scalars: HashMap::new(),
            aggregations: HashMap::new(),
            scenarios: HashMap::new(),
            includes: Vec::new(),
            resolved_includes: HashMap::new(),
            documents: Vec::new(),
        }
    }

    /// Add an include directive (v4.0)
    pub fn add_include(&mut self, include: Include) {
        self.includes.push(include);
    }

    /// Check if model has unresolved includes
    #[must_use]
    pub fn has_unresolved_includes(&self) -> bool {
        !self.includes.is_empty() && self.resolved_includes.is_empty()
    }

    /// Get a value from a resolved include by namespace reference
    /// e.g., "@`sources.pricing.unit_price`" -> lookup in sources namespace
    #[must_use]
    pub fn resolve_namespace_ref(&self, reference: &str) -> Option<f64> {
        // Parse @namespace.path format
        if !reference.starts_with('@') {
            return None;
        }

        let ref_path = &reference[1..]; // Remove @
        let parts: Vec<&str> = ref_path.splitn(2, '.').collect();
        if parts.len() != 2 {
            return None;
        }

        let namespace = parts[0];
        let field_path = parts[1];

        // Look up in resolved includes
        if let Some(resolved) = self.resolved_includes.get(namespace) {
            // Try to find the value in the included model's scalars
            if let Some(var) = resolved.model.scalars.get(field_path) {
                return var.value;
            }
            // Try nested path (e.g., "pricing.unit_price" -> scalars["pricing.unit_price"])
            for (key, var) in &resolved.model.scalars {
                if key == field_path || key.ends_with(&format!(".{field_path}")) {
                    return var.value;
                }
            }
        }

        None
    }

    pub fn add_scenario(&mut self, name: String, scenario: Scenario) {
        self.scenarios.insert(name, scenario);
    }

    /// Get available scenario names
    #[must_use]
    pub fn scenario_names(&self) -> Vec<&String> {
        self.scenarios.keys().collect()
    }

    pub fn add_table(&mut self, table: Table) {
        self.tables.insert(table.name.clone(), table);
    }

    pub fn add_scalar(&mut self, name: String, variable: Variable) {
        self.scalars.insert(name, variable);
    }

    pub fn add_aggregation(&mut self, name: String, formula: String) {
        self.aggregations.insert(name, formula);
    }

    /// Resolve a scenario override key to its full dotted scalar path.
    ///
    /// If the key matches an existing scalar exactly, returns it as-is.
    /// For simple (non-dotted) names with no exact match, searches for
    /// scalars ending with `.name`. Returns the full path if exactly one
    /// match; errors if ambiguous; returns the key as-is if no match (so a
    /// new top-level scalar can be created by the caller).
    ///
    /// # Errors
    ///
    /// Returns an error if multiple grouped scalars share the same suffix.
    pub fn resolve_scalar_name(&self, name: &str) -> Result<String, String> {
        if self.scalars.contains_key(name) {
            return Ok(name.to_string());
        }

        // Only try suffix matching for simple (non-dotted) names
        if !name.contains('.') {
            let suffix = format!(".{name}");
            let matches: Vec<&str> = self
                .scalars
                .keys()
                .filter(|k| k.ends_with(&suffix))
                .map(String::as_str)
                .collect();

            match matches.len() {
                1 => return Ok(matches[0].to_string()),
                n if n > 1 => {
                    let mut sorted = matches;
                    sorted.sort_unstable();
                    return Err(format!(
                        "Ambiguous scenario override '{name}': matches {}. Use the full dotted path.",
                        sorted.join(", ")
                    ));
                },
                _ => {},
            }
        }

        // No match — return as-is (caller creates a new top-level scalar)
        Ok(name.to_string())
    }
}

impl Default for ParsedModel {
    fn default() -> Self {
        Self::new()
    }
}

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

    // =========================================================================
    // Metadata Tests (v4.0)
    // =========================================================================

    #[test]
    fn test_metadata_default_is_empty() {
        let metadata = Metadata::default();
        assert!(metadata.is_empty());
        assert!(metadata.unit.is_none());
        assert!(metadata.notes.is_none());
        assert!(metadata.source.is_none());
        assert!(metadata.validation_status.is_none());
        assert!(metadata.last_updated.is_none());
    }

    #[test]
    fn test_metadata_with_unit_not_empty() {
        let metadata = Metadata {
            unit: Some("CAD".to_string()),
            ..Default::default()
        };
        assert!(!metadata.is_empty());
    }

    #[test]
    fn test_metadata_with_notes_not_empty() {
        let metadata = Metadata {
            notes: Some("Test notes".to_string()),
            ..Default::default()
        };
        assert!(!metadata.is_empty());
    }

    #[test]
    fn test_metadata_with_source_not_empty() {
        let metadata = Metadata {
            source: Some("data.yaml".to_string()),
            ..Default::default()
        };
        assert!(!metadata.is_empty());
    }

    #[test]
    fn test_metadata_with_validation_status_not_empty() {
        let metadata = Metadata {
            validation_status: Some("VALIDATED".to_string()),
            ..Default::default()
        };
        assert!(!metadata.is_empty());
    }

    #[test]
    fn test_metadata_with_last_updated_not_empty() {
        let metadata = Metadata {
            last_updated: Some("2025-11-26".to_string()),
            ..Default::default()
        };
        assert!(!metadata.is_empty());
    }

    #[test]
    fn test_metadata_full() {
        let metadata = Metadata {
            unit: Some("CAD".to_string()),
            notes: Some("Revenue projection".to_string()),
            source: Some("market_research.yaml".to_string()),
            validation_status: Some("PROJECTED".to_string()),
            last_updated: Some("2025-11-26".to_string()),
        };
        assert!(!metadata.is_empty());
        assert_eq!(metadata.unit, Some("CAD".to_string()));
        assert_eq!(metadata.notes, Some("Revenue projection".to_string()));
        assert_eq!(metadata.source, Some("market_research.yaml".to_string()));
        assert_eq!(metadata.validation_status, Some("PROJECTED".to_string()));
        assert_eq!(metadata.last_updated, Some("2025-11-26".to_string()));
    }

    // =========================================================================
    // Variable Tests (v4.0)
    // =========================================================================

    #[test]
    fn test_variable_new_with_value() {
        let var = Variable::new("price".to_string(), Some(100.0), None);
        assert_eq!(var.path, "price");
        assert_eq!(var.value, Some(100.0));
        assert!(var.formula.is_none());
        assert!(var.metadata.is_empty());
    }

    #[test]
    fn test_variable_new_with_formula() {
        let var = Variable::new(
            "profit".to_string(),
            None,
            Some("=revenue - costs".to_string()),
        );
        assert_eq!(var.path, "profit");
        assert!(var.value.is_none());
        assert_eq!(var.formula, Some("=revenue - costs".to_string()));
        assert!(var.metadata.is_empty());
    }

    #[test]
    fn test_variable_with_metadata() {
        let metadata = Metadata {
            unit: Some("CAD".to_string()),
            notes: Some("Total revenue".to_string()),
            ..Default::default()
        };
        let var = Variable::with_metadata("total".to_string(), Some(1000.0), None, metadata);
        assert_eq!(var.path, "total");
        assert_eq!(var.value, Some(1000.0));
        assert!(!var.metadata.is_empty());
        assert_eq!(var.metadata.unit, Some("CAD".to_string()));
    }

    // =========================================================================
    // Column Tests (v4.0)
    // =========================================================================

    #[test]
    fn test_column_new_no_metadata() {
        let col = Column::new(
            "revenue".to_string(),
            ColumnValue::Number(vec![100.0, 200.0]),
        );
        assert_eq!(col.name, "revenue");
        assert_eq!(col.len(), 2);
        assert!(col.metadata.is_empty());
    }

    #[test]
    fn test_column_with_metadata() {
        let metadata = Metadata {
            unit: Some("CAD".to_string()),
            validation_status: Some("VALIDATED".to_string()),
            ..Default::default()
        };
        let col = Column::with_metadata(
            "revenue".to_string(),
            ColumnValue::Number(vec![100.0, 200.0, 300.0]),
            metadata,
        );
        assert_eq!(col.name, "revenue");
        assert_eq!(col.len(), 3);
        assert!(!col.metadata.is_empty());
        assert_eq!(col.metadata.unit, Some("CAD".to_string()));
        assert_eq!(
            col.metadata.validation_status,
            Some("VALIDATED".to_string())
        );
    }

    #[test]
    fn test_column_value_types_with_metadata() {
        // Number column
        let num_col = Column::with_metadata(
            "amounts".to_string(),
            ColumnValue::Number(vec![1.0, 2.0]),
            Metadata {
                unit: Some("%".to_string()),
                ..Default::default()
            },
        );
        assert_eq!(num_col.values.type_name(), "Number");

        // Text column
        let text_col = Column::with_metadata(
            "labels".to_string(),
            ColumnValue::Text(vec!["A".to_string(), "B".to_string()]),
            Metadata {
                notes: Some("Labels".to_string()),
                ..Default::default()
            },
        );
        assert_eq!(text_col.values.type_name(), "Text");

        // Date column
        let date_col = Column::with_metadata(
            "months".to_string(),
            ColumnValue::Date(vec!["2025-01".to_string()]),
            Metadata {
                unit: Some("month".to_string()),
                ..Default::default()
            },
        );
        assert_eq!(date_col.values.type_name(), "Date");

        // Boolean column
        let bool_col = Column::with_metadata(
            "flags".to_string(),
            ColumnValue::Boolean(vec![true, false]),
            Metadata::default(),
        );
        assert_eq!(bool_col.values.type_name(), "Boolean");
    }

    // =========================================================================
    // Table Tests
    // =========================================================================

    #[test]
    fn test_table_new() {
        let table = Table::new("sales".to_string());
        assert_eq!(table.name, "sales");
        assert!(table.columns.is_empty());
        assert!(table.row_formulas.is_empty());
    }

    #[test]
    fn test_table_add_column() {
        let mut table = Table::new("sales".to_string());
        let col = Column::new(
            "revenue".to_string(),
            ColumnValue::Number(vec![100.0, 200.0]),
        );
        table.add_column(col);
        assert_eq!(table.columns.len(), 1);
        assert!(table.columns.contains_key("revenue"));
    }

    #[test]
    fn test_table_add_row_formula() {
        let mut table = Table::new("sales".to_string());
        table.add_row_formula("profit".to_string(), "=revenue - costs".to_string());
        assert_eq!(table.row_formulas.len(), 1);
        assert_eq!(
            table.row_formulas.get("profit"),
            Some(&"=revenue - costs".to_string())
        );
    }

    #[test]
    fn test_table_row_count_empty() {
        let table = Table::new("empty".to_string());
        assert_eq!(table.row_count(), 0);
    }

    #[test]
    fn test_table_row_count_with_data() {
        let mut table = Table::new("sales".to_string());
        table.add_column(Column::new(
            "revenue".to_string(),
            ColumnValue::Number(vec![100.0, 200.0, 300.0]),
        ));
        assert_eq!(table.row_count(), 3);
    }

    #[test]
    fn test_column_is_empty() {
        let empty_col = Column::new("empty".to_string(), ColumnValue::Number(vec![]));
        assert!(empty_col.is_empty());

        let non_empty_col = Column::new("nums".to_string(), ColumnValue::Number(vec![1.0]));
        assert!(!non_empty_col.is_empty());
    }

    // =========================================================================
    // Include Tests
    // =========================================================================

    #[test]
    fn test_include_new() {
        let include = Include::new("data.yaml".to_string(), "data".to_string());
        assert_eq!(include.file, "data.yaml");
        assert_eq!(include.namespace, "data");
    }

    // =========================================================================
    // Scenario Tests
    // =========================================================================

    #[test]
    fn test_scenario_new() {
        let scenario = Scenario::new();
        assert!(scenario.overrides.is_empty());
    }

    #[test]
    fn test_scenario_default() {
        let scenario = Scenario::default();
        assert!(scenario.overrides.is_empty());
    }

    #[test]
    fn test_scenario_add_override() {
        let mut scenario = Scenario::new();
        scenario.add_override("growth_rate".to_string(), 0.15);
        assert_eq!(scenario.overrides.get("growth_rate"), Some(&0.15));
    }

    // =========================================================================
    // ParsedModel Tests
    // =========================================================================

    #[test]
    fn test_parsed_model_new() {
        let model = ParsedModel::new();
        assert!(model.tables.is_empty());
        assert!(model.scalars.is_empty());
        assert!(model.aggregations.is_empty());
        assert!(model.scenarios.is_empty());
        assert!(model.includes.is_empty());
        assert!(model.resolved_includes.is_empty());
        assert!(model.documents.is_empty());
    }

    #[test]
    fn test_parsed_model_default() {
        let model = ParsedModel::default();
        assert!(model.tables.is_empty());
    }

    #[test]
    fn test_parsed_model_add_table() {
        let mut model = ParsedModel::new();
        let table = Table::new("sales".to_string());
        model.add_table(table);
        assert!(model.tables.contains_key("sales"));
    }

    #[test]
    fn test_parsed_model_add_scalar() {
        let mut model = ParsedModel::new();
        let var = Variable::new("profit".to_string(), Some(100.0), None);
        model.add_scalar("profit".to_string(), var);
        assert!(model.scalars.contains_key("profit"));
    }

    #[test]
    fn test_parsed_model_add_aggregation() {
        let mut model = ParsedModel::new();
        model.add_aggregation("total".to_string(), "=SUM(sales.revenue)".to_string());
        assert_eq!(
            model.aggregations.get("total"),
            Some(&"=SUM(sales.revenue)".to_string())
        );
    }

    #[test]
    fn test_parsed_model_add_scenario() {
        let mut model = ParsedModel::new();
        let mut scenario = Scenario::new();
        scenario.add_override("rate".to_string(), 0.10);
        model.add_scenario("optimistic".to_string(), scenario);
        assert!(model.scenarios.contains_key("optimistic"));
    }

    #[test]
    fn test_parsed_model_scenario_names() {
        let mut model = ParsedModel::new();
        model.add_scenario("base".to_string(), Scenario::new());
        model.add_scenario("optimistic".to_string(), Scenario::new());
        let names = model.scenario_names();
        assert_eq!(names.len(), 2);
    }

    #[test]
    fn test_parsed_model_add_include() {
        let mut model = ParsedModel::new();
        let include = Include::new("external.yaml".to_string(), "ext".to_string());
        model.add_include(include);
        assert_eq!(model.includes.len(), 1);
    }

    #[test]
    fn test_parsed_model_has_unresolved_includes_empty() {
        let model = ParsedModel::new();
        assert!(!model.has_unresolved_includes());
    }

    #[test]
    fn test_parsed_model_has_unresolved_includes_true() {
        let mut model = ParsedModel::new();
        model.add_include(Include::new("external.yaml".to_string(), "ext".to_string()));
        assert!(model.has_unresolved_includes());
    }

    #[test]
    fn test_parsed_model_has_unresolved_includes_resolved() {
        let mut model = ParsedModel::new();
        model.add_include(Include::new("external.yaml".to_string(), "ext".to_string()));

        // Add a resolved include
        let resolved = ResolvedInclude {
            include: Include::new("external.yaml".to_string(), "ext".to_string()),
            resolved_path: std::path::PathBuf::from("/tmp/external.yaml"),
            model: ParsedModel::new(),
        };
        model.resolved_includes.insert("ext".to_string(), resolved);

        assert!(!model.has_unresolved_includes());
    }

    #[test]
    fn test_parsed_model_resolve_namespace_ref_invalid_format() {
        let model = ParsedModel::new();

        // Missing @ prefix
        assert_eq!(model.resolve_namespace_ref("ext.value"), None);

        // No dot in path
        assert_eq!(model.resolve_namespace_ref("@ext"), None);
    }

    #[test]
    fn test_parsed_model_resolve_namespace_ref_not_found() {
        let model = ParsedModel::new();
        assert_eq!(model.resolve_namespace_ref("@ext.value"), None);
    }

    #[test]
    fn test_parsed_model_resolve_namespace_ref_found() {
        let mut model = ParsedModel::new();

        // Create an included model with a scalar
        let mut included_model = ParsedModel::new();
        let var = Variable::new("price".to_string(), Some(99.99), None);
        included_model.add_scalar("price".to_string(), var);

        let resolved = ResolvedInclude {
            include: Include::new("pricing.yaml".to_string(), "pricing".to_string()),
            resolved_path: std::path::PathBuf::from("/tmp/pricing.yaml"),
            model: included_model,
        };
        model
            .resolved_includes
            .insert("pricing".to_string(), resolved);

        assert_eq!(model.resolve_namespace_ref("@pricing.price"), Some(99.99));
    }

    #[test]
    fn test_parsed_model_resolve_namespace_ref_nested_path() {
        let mut model = ParsedModel::new();

        // Create an included model with a nested scalar path
        let mut included_model = ParsedModel::new();
        let var = Variable::new("products.item_price".to_string(), Some(50.0), None);
        included_model.add_scalar("products.item_price".to_string(), var);

        let resolved = ResolvedInclude {
            include: Include::new("data.yaml".to_string(), "data".to_string()),
            resolved_path: std::path::PathBuf::from("/tmp/data.yaml"),
            model: included_model,
        };
        model.resolved_includes.insert("data".to_string(), resolved);

        // Should find via ends_with match
        assert_eq!(model.resolve_namespace_ref("@data.item_price"), Some(50.0));
    }

    // =========================================================================
    // ColumnValue Tests
    // =========================================================================

    #[test]
    fn test_column_value_equality() {
        let a = ColumnValue::Number(vec![1.0, 2.0]);
        let b = ColumnValue::Number(vec![1.0, 2.0]);
        let c = ColumnValue::Number(vec![1.0, 3.0]);

        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn test_column_value_text_equality() {
        let a = ColumnValue::Text(vec!["a".to_string(), "b".to_string()]);
        let b = ColumnValue::Text(vec!["a".to_string(), "b".to_string()]);
        assert_eq!(a, b);
    }

    #[test]
    fn test_column_value_date_equality() {
        let a = ColumnValue::Date(vec!["2025-01".to_string()]);
        let b = ColumnValue::Date(vec!["2025-01".to_string()]);
        assert_eq!(a, b);
    }

    #[test]
    fn test_column_value_boolean_equality() {
        let a = ColumnValue::Boolean(vec![true, false]);
        let b = ColumnValue::Boolean(vec![true, false]);
        assert_eq!(a, b);
    }

    // =========================================================================
    // resolve_scalar_name Tests
    // =========================================================================

    #[test]
    fn test_resolve_scalar_name_exact_match() {
        let mut model = ParsedModel::new();
        model.add_scalar("rate".into(), Variable::new("rate".into(), Some(0.1), None));
        assert_eq!(model.resolve_scalar_name("rate").unwrap(), "rate");
    }

    #[test]
    fn test_resolve_scalar_name_grouped_suffix() {
        let mut model = ParsedModel::new();
        model.add_scalar(
            "assumptions.rate".into(),
            Variable::new("assumptions.rate".into(), Some(0.1), None),
        );
        // Short name resolves to the grouped scalar
        assert_eq!(
            model.resolve_scalar_name("rate").unwrap(),
            "assumptions.rate"
        );
    }

    #[test]
    fn test_resolve_scalar_name_ambiguous() {
        let mut model = ParsedModel::new();
        model.add_scalar(
            "assumptions.rate".into(),
            Variable::new("assumptions.rate".into(), Some(0.1), None),
        );
        model.add_scalar(
            "inputs.rate".into(),
            Variable::new("inputs.rate".into(), Some(0.2), None),
        );
        let err = model.resolve_scalar_name("rate").unwrap_err();
        assert!(err.contains("Ambiguous"), "{err}");
        assert!(err.contains("assumptions.rate"), "{err}");
        assert!(err.contains("inputs.rate"), "{err}");
    }

    #[test]
    fn test_resolve_scalar_name_dotted_exact() {
        let mut model = ParsedModel::new();
        model.add_scalar(
            "assumptions.rate".into(),
            Variable::new("assumptions.rate".into(), Some(0.1), None),
        );
        // Explicit dotted path resolves exactly
        assert_eq!(
            model.resolve_scalar_name("assumptions.rate").unwrap(),
            "assumptions.rate"
        );
    }

    #[test]
    fn test_resolve_scalar_name_no_match() {
        let model = ParsedModel::new();
        // Unknown name passes through (caller creates new scalar)
        assert_eq!(model.resolve_scalar_name("unknown").unwrap(), "unknown");
    }
}