reasonkit-core 0.1.8

The Reasoning Engine — Auditable Reasoning for Production AI | Rust-Native | Turn Prompts into Protocols
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
//! BedRock Module - First Principles Decomposition
//!
//! Reduces problems to fundamental axioms through recursive analysis,
//! then rebuilds understanding using Tree-of-Thoughts exploration.
//!
//! ## Methodology
//!
//! BedRock applies Elon Musk-style first principles thinking:
//! 1. **Decompose**: Break the problem into fundamental components
//! 2. **Identify Axioms**: Find self-evident truths that don't require proof
//! 3. **Surface Assumptions**: Expose hidden assumptions that may be challenged
//! 4. **Rebuild**: Reconstruct understanding from verified foundations
//! 5. **Explore**: Use Tree-of-Thoughts to find optimal reasoning paths
//!
//! ## Usage
//!
//! ```ignore
//! use reasonkit::thinktool::modules::{BedRock, ThinkToolModule, ThinkToolContext};
//!
//! let bedrock = BedRock::new();
//! let context = ThinkToolContext {
//!     query: "Why are electric vehicles better than gas cars?".into(),
//!     previous_steps: vec![],
//! };
//!
//! let result = bedrock.execute(&context)?;
//! println!("Axioms found: {}", result.output["axioms"]);
//! println!("Hidden assumptions: {}", result.output["assumptions"]);
//! ```

use super::{ThinkToolContext, ThinkToolModule, ThinkToolModuleConfig, ThinkToolOutput};
use serde::{Deserialize, Serialize};

/// Configuration for BedRock analysis depth and behavior.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BedRockConfig {
    /// Maximum decomposition depth (how deep to recurse into sub-principles)
    pub max_depth: usize,
    /// Minimum fundamentality score to consider a principle as axiomatic (0.0-1.0)
    pub axiom_threshold: f64,
    /// Number of parallel thought branches to explore per principle
    pub branching_factor: usize,
    /// Minimum confidence threshold for including a principle
    pub min_confidence: f64,
    /// Whether to require all assumptions to be explicitly stated
    pub strict_assumptions: bool,
    /// Maximum number of principles to identify
    pub max_principles: usize,
}

impl Default for BedRockConfig {
    fn default() -> Self {
        Self {
            max_depth: 3,
            axiom_threshold: 0.85,
            branching_factor: 3,
            min_confidence: 0.5,
            strict_assumptions: true,
            max_principles: 20,
        }
    }
}

// ============================================================================
// TREE-OF-THOUGHTS (ToT) EXPLORATION
// Based on Yao et al. 2023: "Tree of Thoughts: Deliberate Problem Solving"
// ============================================================================

/// Search strategy for Tree-of-Thoughts exploration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ExplorationStrategy {
    /// Breadth-First Search: Explore all nodes at current depth before going deeper
    /// Best for: Problems where optimal solution depth is unknown
    #[default]
    BreadthFirst,

    /// Depth-First Search: Explore one branch fully before backtracking
    /// Best for: Problems with clear pruning conditions
    DepthFirst,

    /// Best-First Search: Always expand the most promising node (Greedy)
    /// Best for: Problems with reliable heuristic evaluation
    BestFirst,

    /// A* Search: Combines path cost with heuristic estimate
    /// Best for: Finding optimal solutions with admissible heuristics
    AStar,

    /// Beam Search: Keep only top-k nodes at each level
    /// Best for: Balancing exploration breadth with computational cost
    BeamSearch,
}

impl ExplorationStrategy {
    /// Returns description of when to use this strategy
    pub fn use_case(&self) -> &'static str {
        match self {
            Self::BreadthFirst => "Unknown solution depth, want all solutions at each level",
            Self::DepthFirst => "Deep solutions, good pruning heuristics available",
            Self::BestFirst => "Reliable value function, want fastest path to good solution",
            Self::AStar => "Need optimal solution, have admissible heuristic",
            Self::BeamSearch => "Limited compute budget, want diverse high-quality solutions",
        }
    }
}

/// Configuration for Tree-of-Thoughts exploration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToTConfig {
    /// Search strategy to use
    pub strategy: ExplorationStrategy,

    /// Maximum number of thought branches to explore per node
    pub branching_factor: usize,

    /// Beam width for BeamSearch strategy
    pub beam_width: usize,

    /// Maximum nodes to explore before stopping
    pub max_nodes: usize,

    /// Minimum value threshold for pruning (0.0-1.0)
    pub pruning_threshold: f64,

    /// Whether to enable backtracking on dead ends
    pub enable_backtracking: bool,

    /// Maximum search depth
    pub max_depth: usize,

    /// Whether to aggregate multiple paths for final answer
    pub aggregate_paths: bool,

    /// Number of evaluation samples for voting (0 = use value function)
    pub voting_samples: usize,
}

impl Default for ToTConfig {
    fn default() -> Self {
        Self {
            strategy: ExplorationStrategy::default(),
            branching_factor: 3,
            beam_width: 5,
            max_nodes: 100,
            pruning_threshold: 0.3,
            enable_backtracking: true,
            max_depth: 4,
            aggregate_paths: true,
            voting_samples: 0, // Use value function by default
        }
    }
}

impl ToTConfig {
    /// Configuration optimized for BFS exploration
    pub fn bfs() -> Self {
        Self {
            strategy: ExplorationStrategy::BreadthFirst,
            branching_factor: 4,
            beam_width: 10,
            max_nodes: 200,
            ..Self::default()
        }
    }

    /// Configuration optimized for DFS exploration with pruning
    pub fn dfs() -> Self {
        Self {
            strategy: ExplorationStrategy::DepthFirst,
            branching_factor: 2,
            max_depth: 6,
            pruning_threshold: 0.4, // More aggressive pruning
            ..Self::default()
        }
    }

    /// Configuration optimized for beam search (balanced)
    pub fn beam(width: usize) -> Self {
        Self {
            strategy: ExplorationStrategy::BeamSearch,
            beam_width: width,
            branching_factor: 3,
            aggregate_paths: true,
            ..Self::default()
        }
    }
}

/// A node in the Tree-of-Thoughts search tree
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThoughtNode {
    /// Unique identifier for this node
    pub id: usize,

    /// The thought/reasoning step content
    pub thought: String,

    /// Value estimate for this node (0.0-1.0)
    pub value: f64,

    /// Depth in the search tree
    pub depth: usize,

    /// Parent node ID (None for root)
    pub parent_id: Option<usize>,

    /// Child node IDs
    pub children: Vec<usize>,

    /// Whether this node is a terminal/solution state
    pub is_terminal: bool,

    /// Whether this node was pruned
    pub is_pruned: bool,

    /// Path from root to this node (for reconstruction)
    pub path: Vec<usize>,

    /// Metadata about how this thought was generated
    pub generation_method: ThoughtGenerationMethod,
}

/// Method used to generate a thought
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ThoughtGenerationMethod {
    /// Proposed by sampling from LLM
    #[default]
    Sampled,
    /// Proposed by explicit generation prompt
    Proposed,
    /// Generated via decomposition
    Decomposed,
    /// Derived from existing thoughts
    Derived,
}

impl ThoughtNode {
    /// Create a new root thought node
    pub fn root(thought: impl Into<String>) -> Self {
        Self {
            id: 0,
            thought: thought.into(),
            value: 1.0, // Root has maximum value
            depth: 0,
            parent_id: None,
            children: Vec::new(),
            is_terminal: false,
            is_pruned: false,
            path: vec![0],
            generation_method: ThoughtGenerationMethod::Decomposed,
        }
    }

    /// Create a child thought node
    pub fn child(id: usize, thought: impl Into<String>, value: f64, parent: &ThoughtNode) -> Self {
        let mut path = parent.path.clone();
        path.push(id);

        Self {
            id,
            thought: thought.into(),
            value,
            depth: parent.depth + 1,
            parent_id: Some(parent.id),
            children: Vec::new(),
            is_terminal: false,
            is_pruned: false,
            path,
            generation_method: ThoughtGenerationMethod::default(),
        }
    }

    /// Check if this node should be pruned based on value threshold
    pub fn should_prune(&self, threshold: f64) -> bool {
        self.value < threshold
    }

    /// Calculate the path cost (sum of 1-value for each node in path)
    pub fn path_cost(&self, nodes: &[ThoughtNode]) -> f64 {
        self.path
            .iter()
            .filter_map(|&id| nodes.get(id))
            .map(|n| 1.0 - n.value)
            .sum()
    }
}

/// Result of Tree-of-Thoughts exploration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToTResult {
    /// All nodes explored
    pub nodes: Vec<ThoughtNode>,

    /// Best path found (node IDs from root to solution)
    pub best_path: Vec<usize>,

    /// Best solution value
    pub best_value: f64,

    /// All terminal nodes (potential solutions)
    pub terminal_nodes: Vec<usize>,

    /// Exploration statistics
    pub stats: ToTStats,
}

/// Statistics from ToT exploration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ToTStats {
    /// Total nodes created
    pub nodes_created: usize,

    /// Nodes expanded (had children generated)
    pub nodes_expanded: usize,

    /// Nodes pruned
    pub nodes_pruned: usize,

    /// Maximum depth reached
    pub max_depth_reached: usize,

    /// Number of terminal/solution nodes found
    pub solutions_found: usize,

    /// Search strategy used
    pub strategy: String,

    /// Effective branching factor
    pub effective_branching_factor: f64,
}

impl ToTResult {
    /// Get the best solution path as thought strings
    pub fn best_path_thoughts(&self) -> Vec<&str> {
        self.best_path
            .iter()
            .filter_map(|&id| self.nodes.get(id))
            .map(|n| n.thought.as_str())
            .collect()
    }

    /// Get all solution paths sorted by value
    pub fn all_solutions(&self) -> Vec<(&ThoughtNode, f64)> {
        let mut solutions: Vec<_> = self
            .terminal_nodes
            .iter()
            .filter_map(|&id| self.nodes.get(id))
            .map(|n| (n, n.value))
            .collect();

        solutions.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
        solutions
    }
}

/// Tree-of-Thoughts explorer for BedRock
pub struct ToTExplorer {
    config: ToTConfig,
    nodes: Vec<ThoughtNode>,
    next_id: usize,
    stats: ToTStats,
}

impl ToTExplorer {
    /// Create a new ToT explorer with the given configuration
    pub fn new(config: ToTConfig) -> Self {
        Self {
            stats: ToTStats {
                strategy: format!("{:?}", config.strategy),
                ..Default::default()
            },
            config,
            nodes: Vec::new(),
            next_id: 0,
        }
    }

    /// Create with default BFS configuration
    pub fn bfs() -> Self {
        Self::new(ToTConfig::bfs())
    }

    /// Create with default DFS configuration
    pub fn dfs() -> Self {
        Self::new(ToTConfig::dfs())
    }

    /// Create with beam search configuration
    pub fn beam(width: usize) -> Self {
        Self::new(ToTConfig::beam(width))
    }

    /// Initialize exploration with a root thought
    pub fn initialize(&mut self, root_thought: impl Into<String>) {
        self.nodes.clear();
        self.next_id = 0;
        self.stats = ToTStats {
            strategy: format!("{:?}", self.config.strategy),
            ..Default::default()
        };

        let root = ThoughtNode::root(root_thought);
        self.nodes.push(root);
        self.next_id = 1;
        self.stats.nodes_created = 1;
    }

    /// Add a child thought to a parent node
    pub fn add_child(&mut self, parent_id: usize, thought: impl Into<String>, value: f64) -> usize {
        let parent = self.nodes.get(parent_id).cloned();
        if let Some(parent) = parent {
            let child = ThoughtNode::child(self.next_id, thought, value, &parent);
            let child_id = child.id;

            // Check for pruning
            if child.should_prune(self.config.pruning_threshold) {
                let mut pruned = child;
                pruned.is_pruned = true;
                self.nodes.push(pruned);
                self.stats.nodes_pruned += 1;
            } else {
                self.nodes.push(child);
            }

            // Update parent's children list
            if let Some(parent_node) = self.nodes.get_mut(parent_id) {
                parent_node.children.push(child_id);
            }

            self.next_id += 1;
            self.stats.nodes_created += 1;
            self.stats.max_depth_reached =
                self.stats.max_depth_reached.max(self.nodes[child_id].depth);

            child_id
        } else {
            0
        }
    }

    /// Mark a node as terminal (solution found)
    pub fn mark_terminal(&mut self, node_id: usize) {
        if let Some(node) = self.nodes.get_mut(node_id) {
            node.is_terminal = true;
            self.stats.solutions_found += 1;
        }
    }

    /// Get the next node to expand based on search strategy
    pub fn next_to_expand(&self) -> Option<usize> {
        let candidates: Vec<_> = self
            .nodes
            .iter()
            .filter(|n| !n.is_terminal && !n.is_pruned && n.children.is_empty())
            .filter(|n| n.depth < self.config.max_depth)
            .collect();

        if candidates.is_empty() {
            return None;
        }

        match self.config.strategy {
            ExplorationStrategy::BreadthFirst => {
                // Return node with smallest depth (FIFO within depth)
                candidates.iter().min_by_key(|n| n.depth).map(|n| n.id)
            }
            ExplorationStrategy::DepthFirst => {
                // Return node with largest depth (LIFO)
                candidates.iter().max_by_key(|n| n.depth).map(|n| n.id)
            }
            ExplorationStrategy::BestFirst | ExplorationStrategy::AStar => {
                // Return node with highest value
                candidates
                    .iter()
                    .max_by(|a, b| {
                        a.value
                            .partial_cmp(&b.value)
                            .unwrap_or(std::cmp::Ordering::Equal)
                    })
                    .map(|n| n.id)
            }
            ExplorationStrategy::BeamSearch => {
                // Return highest value among top beam_width nodes at max depth
                let max_depth = candidates.iter().map(|n| n.depth).max().unwrap_or(0);
                candidates
                    .iter()
                    .filter(|n| n.depth == max_depth)
                    .max_by(|a, b| {
                        a.value
                            .partial_cmp(&b.value)
                            .unwrap_or(std::cmp::Ordering::Equal)
                    })
                    .map(|n| n.id)
            }
        }
    }

    /// Get the frontier nodes for beam search
    pub fn get_beam_frontier(&self) -> Vec<usize> {
        let max_depth = self.nodes.iter().map(|n| n.depth).max().unwrap_or(0);

        let mut frontier: Vec<_> = self
            .nodes
            .iter()
            .filter(|n| n.depth == max_depth && !n.is_pruned && !n.is_terminal)
            .map(|n| (n.id, n.value))
            .collect();

        // Sort by value descending and take top beam_width
        frontier.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
        frontier
            .into_iter()
            .take(self.config.beam_width)
            .map(|(id, _)| id)
            .collect()
    }

    /// Complete the exploration and return results
    pub fn finish(mut self) -> ToTResult {
        // Find best terminal node
        let (best_path, best_value) = self
            .nodes
            .iter()
            .filter(|n| n.is_terminal)
            .max_by(|a, b| {
                a.value
                    .partial_cmp(&b.value)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .map(|n| (n.path.clone(), n.value))
            .unwrap_or_else(|| (vec![0], 0.0));

        // Get all terminal node IDs
        let terminal_nodes: Vec<_> = self
            .nodes
            .iter()
            .filter(|n| n.is_terminal)
            .map(|n| n.id)
            .collect();

        // Calculate effective branching factor
        let nodes_with_children = self.nodes.iter().filter(|n| !n.children.is_empty()).count();
        let total_children: usize = self.nodes.iter().map(|n| n.children.len()).sum();
        self.stats.effective_branching_factor = if nodes_with_children > 0 {
            total_children as f64 / nodes_with_children as f64
        } else {
            0.0
        };
        self.stats.nodes_expanded = nodes_with_children;

        ToTResult {
            nodes: self.nodes,
            best_path,
            best_value,
            terminal_nodes,
            stats: self.stats,
        }
    }

    /// Get a reference to a node by ID
    pub fn get_node(&self, id: usize) -> Option<&ThoughtNode> {
        self.nodes.get(id)
    }

    /// Get number of nodes explored
    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    /// Check if exploration should continue
    pub fn should_continue(&self) -> bool {
        self.nodes.len() < self.config.max_nodes && self.next_to_expand().is_some()
    }
}

/// Classification of a principle's nature.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PrincipleType {
    /// Self-evident truth requiring no proof (e.g., "A = A", physical laws)
    Axiom,
    /// Logically derived from axioms
    Derived,
    /// Assumed for the sake of argument (may be challenged)
    Assumption,
    /// Based on empirical observation/data
    Empirical,
    /// Definitional statement clarifying terminology
    Definition,
    /// Contested claim requiring verification
    Contested,
}

impl PrincipleType {
    /// Returns the reliability weight for this principle type.
    pub fn reliability_weight(&self) -> f64 {
        match self {
            PrincipleType::Axiom => 1.0,
            PrincipleType::Definition => 0.95,
            PrincipleType::Empirical => 0.80,
            PrincipleType::Derived => 0.75,
            PrincipleType::Assumption => 0.50,
            PrincipleType::Contested => 0.30,
        }
    }
}

/// A fundamental principle identified during decomposition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Principle {
    /// Unique identifier within this analysis
    pub id: usize,
    /// The principle statement
    pub statement: String,
    /// Classification of the principle
    pub principle_type: PrincipleType,
    /// How fundamental is this (0.0-1.0, where 1.0 = pure axiom)
    pub fundamentality: f64,
    /// Confidence in this principle's validity
    pub confidence: f64,
    /// ID of parent principle if derived/decomposed
    pub parent_id: Option<usize>,
    /// IDs of child principles
    pub child_ids: Vec<usize>,
    /// Supporting evidence or reasoning
    pub evidence: Vec<String>,
    /// Potential challenges to this principle
    pub challenges: Vec<String>,
    /// Depth in the decomposition tree
    pub depth: usize,
}

impl Principle {
    /// Calculate the effective weight of this principle.
    pub fn effective_weight(&self) -> f64 {
        self.fundamentality * self.confidence * self.principle_type.reliability_weight()
    }

    /// Check if this principle qualifies as axiomatic.
    pub fn is_axiomatic(&self, threshold: f64) -> bool {
        self.principle_type == PrincipleType::Axiom && self.fundamentality >= threshold
    }
}

/// A reconstruction path from axioms to conclusions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReconstructionPath {
    /// Ordered list of principle IDs from axiom to conclusion
    pub principle_chain: Vec<usize>,
    /// Logical connectives between principles
    pub connectives: Vec<String>,
    /// Overall path confidence
    pub confidence: f64,
    /// Whether this path is complete (reaches conclusion)
    pub is_complete: bool,
    /// Gaps or missing links in the reasoning
    pub gaps: Vec<String>,
}

/// Analysis gap identified during reconstruction.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalysisGap {
    /// Description of the gap
    pub description: String,
    /// Severity (0.0-1.0, where 1.0 = critical)
    pub severity: f64,
    /// Suggested resolution
    pub suggestion: Option<String>,
    /// Principles affected by this gap
    pub affected_principles: Vec<usize>,
}

/// Complete result of BedRock first principles analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BedRockResult {
    /// Original query analyzed
    pub query: String,
    /// All identified principles
    pub principles: Vec<Principle>,
    /// Reconstruction paths from axioms to conclusions
    pub reconstructions: Vec<ReconstructionPath>,
    /// Identified gaps in reasoning
    pub gaps: Vec<AnalysisGap>,
    /// Key insights from the analysis
    pub insights: Vec<String>,
    /// Overall analysis confidence
    pub confidence: f64,
    /// Analysis metadata
    pub metadata: BedRockMetadata,
}

/// Metadata about the analysis process.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BedRockMetadata {
    /// Maximum depth reached
    pub max_depth_reached: usize,
    /// Total principles identified
    pub total_principles: usize,
    /// Number of axioms found
    pub axiom_count: usize,
    /// Number of assumptions identified
    pub assumption_count: usize,
    /// Number of contested claims
    pub contested_count: usize,
    /// Decomposition completeness (0.0-1.0)
    pub completeness: f64,
}

impl BedRockResult {
    /// Get all axiomatic principles.
    pub fn axioms(&self) -> Vec<&Principle> {
        self.principles
            .iter()
            .filter(|p| p.principle_type == PrincipleType::Axiom)
            .collect()
    }

    /// Get all assumptions that may be challenged.
    pub fn assumptions(&self) -> Vec<&Principle> {
        self.principles
            .iter()
            .filter(|p| p.principle_type == PrincipleType::Assumption)
            .collect()
    }

    /// Get contested claims requiring verification.
    pub fn contested(&self) -> Vec<&Principle> {
        self.principles
            .iter()
            .filter(|p| p.principle_type == PrincipleType::Contested)
            .collect()
    }

    /// Get principles at a specific depth.
    pub fn at_depth(&self, depth: usize) -> Vec<&Principle> {
        self.principles
            .iter()
            .filter(|p| p.depth == depth)
            .collect()
    }

    /// Check if analysis is sufficiently complete.
    pub fn is_complete(&self, threshold: f64) -> bool {
        self.metadata.completeness >= threshold && self.gaps.iter().all(|g| g.severity < 0.8)
    }

    /// Convert to JSON output format.
    pub fn to_json(&self) -> serde_json::Value {
        serde_json::json!({
            "query": self.query,
            "axioms": self.axioms().iter().map(|p| {
                serde_json::json!({
                    "id": p.id,
                    "statement": p.statement,
                    "fundamentality": p.fundamentality,
                    "confidence": p.confidence,
                    "evidence": p.evidence
                })
            }).collect::<Vec<_>>(),
            "assumptions": self.assumptions().iter().map(|p| {
                serde_json::json!({
                    "id": p.id,
                    "statement": p.statement,
                    "confidence": p.confidence,
                    "challenges": p.challenges
                })
            }).collect::<Vec<_>>(),
            "decomposition": self.principles.iter().map(|p| {
                serde_json::json!({
                    "id": p.id,
                    "statement": p.statement,
                    "type": format!("{:?}", p.principle_type),
                    "fundamentality": p.fundamentality,
                    "confidence": p.confidence,
                    "depth": p.depth,
                    "parent_id": p.parent_id
                })
            }).collect::<Vec<_>>(),
            "reconstruction": self.reconstructions.iter().map(|r| {
                serde_json::json!({
                    "path": r.principle_chain,
                    "confidence": r.confidence,
                    "complete": r.is_complete,
                    "gaps": r.gaps
                })
            }).collect::<Vec<_>>(),
            "gaps": self.gaps.iter().map(|g| {
                serde_json::json!({
                    "description": g.description,
                    "severity": g.severity,
                    "suggestion": g.suggestion
                })
            }).collect::<Vec<_>>(),
            "insights": self.insights,
            "confidence": self.confidence,
            "metadata": {
                "max_depth": self.metadata.max_depth_reached,
                "total_principles": self.metadata.total_principles,
                "axioms": self.metadata.axiom_count,
                "assumptions": self.metadata.assumption_count,
                "contested": self.metadata.contested_count,
                "completeness": self.metadata.completeness
            }
        })
    }
}

/// BedRock reasoning module for first principles analysis.
///
/// Decomposes statements to foundational axioms, identifies hidden
/// assumptions, and rebuilds understanding from verified foundations.
pub struct BedRock {
    /// Module configuration
    config: ThinkToolModuleConfig,
    /// Analysis configuration
    analysis_config: BedRockConfig,
}

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

impl BedRock {
    /// Create a new BedRock module instance with default configuration.
    pub fn new() -> Self {
        Self {
            config: ThinkToolModuleConfig {
                name: "BedRock".to_string(),
                version: "3.0.0".to_string(),
                description: "First principles decomposition with Tree-of-Thoughts reconstruction"
                    .to_string(),
                confidence_weight: 0.25,
            },
            analysis_config: BedRockConfig::default(),
        }
    }

    /// Create a new BedRock module with custom analysis configuration.
    pub fn with_config(analysis_config: BedRockConfig) -> Self {
        Self {
            config: ThinkToolModuleConfig {
                name: "BedRock".to_string(),
                version: "3.0.0".to_string(),
                description: "First principles decomposition with Tree-of-Thoughts reconstruction"
                    .to_string(),
                confidence_weight: 0.25,
            },
            analysis_config,
        }
    }

    /// Get the analysis configuration.
    pub fn analysis_config(&self) -> &BedRockConfig {
        &self.analysis_config
    }

    /// Perform first principles decomposition on the query.
    ///
    /// This is the core analysis method that:
    /// 1. Parses the query to identify claims
    /// 2. Recursively decomposes each claim
    /// 3. Classifies principles by type
    /// 4. Identifies gaps and assumptions
    pub fn decompose(&self, query: &str, previous_steps: &[String]) -> BedRockResult {
        let mut principles = Vec::new();
        let mut next_id = 0;

        // Step 1: Identify the root claim/question
        let root_principle = self.create_root_principle(query, &mut next_id);
        principles.push(root_principle);

        // Step 2: Recursive decomposition using heuristic analysis
        self.decompose_recursive(&mut principles, 0, 0, &mut next_id);

        // Step 3: Incorporate context from previous steps
        self.incorporate_context(&mut principles, previous_steps, &mut next_id);

        // Step 4: Classify and validate principles
        self.classify_principles(&mut principles);

        // Step 5: Build reconstruction paths
        let reconstructions = self.build_reconstructions(&principles);

        // Step 6: Identify gaps
        let gaps = self.identify_gaps(&principles, &reconstructions);

        // Step 7: Extract insights
        let insights = self.extract_insights(&principles, &gaps);

        // Step 8: Calculate overall confidence
        let confidence = self.calculate_confidence(&principles, &gaps);

        // Build metadata
        let metadata = BedRockMetadata {
            max_depth_reached: principles.iter().map(|p| p.depth).max().unwrap_or(0),
            total_principles: principles.len(),
            axiom_count: principles
                .iter()
                .filter(|p| p.principle_type == PrincipleType::Axiom)
                .count(),
            assumption_count: principles
                .iter()
                .filter(|p| p.principle_type == PrincipleType::Assumption)
                .count(),
            contested_count: principles
                .iter()
                .filter(|p| p.principle_type == PrincipleType::Contested)
                .count(),
            completeness: self.calculate_completeness(&principles, &gaps),
        };

        BedRockResult {
            query: query.to_string(),
            principles,
            reconstructions,
            gaps,
            insights,
            confidence,
            metadata,
        }
    }

    /// Create the root principle from the query.
    fn create_root_principle(&self, query: &str, next_id: &mut usize) -> Principle {
        let id = *next_id;
        *next_id += 1;

        // Analyze query to determine initial type
        let principle_type = self.classify_query(query);

        Principle {
            id,
            statement: query.to_string(),
            principle_type,
            fundamentality: 0.0, // Root is not fundamental - it's what we're decomposing
            confidence: 1.0,     // We're certain about what was asked
            parent_id: None,
            child_ids: Vec::new(),
            evidence: Vec::new(),
            challenges: Vec::new(),
            depth: 0,
        }
    }

    /// Classify a query/statement into a principle type.
    fn classify_query(&self, query: &str) -> PrincipleType {
        let lower = query.to_lowercase();

        // Check for definition markers
        if lower.contains("what is")
            || lower.contains("define")
            || lower.contains("meaning of")
            || lower.contains("definition")
        {
            return PrincipleType::Definition;
        }

        // Check for empirical markers
        if lower.contains("how many")
            || lower.contains("when did")
            || lower.contains("data shows")
            || lower.contains("research")
            || lower.contains("study")
            || lower.contains("evidence")
        {
            return PrincipleType::Empirical;
        }

        // Check for axiomatic/logical markers
        if lower.contains("always true")
            || lower.contains("by definition")
            || lower.contains("necessarily")
            || lower.contains("logically")
            || lower.contains("mathematically")
        {
            return PrincipleType::Axiom;
        }

        // Check for assumption markers
        if lower.contains("assume")
            || lower.contains("suppose")
            || lower.contains("if we")
            || lower.contains("given that")
        {
            return PrincipleType::Assumption;
        }

        // Check for contested/opinion markers
        if lower.contains("better")
            || lower.contains("worse")
            || lower.contains("should")
            || lower.contains("ought")
            || lower.contains("believe")
            || lower.contains("think")
        {
            return PrincipleType::Contested;
        }

        // Default to derived (needs further decomposition)
        PrincipleType::Derived
    }

    /// Recursively decompose a principle into sub-principles.
    fn decompose_recursive(
        &self,
        principles: &mut Vec<Principle>,
        parent_idx: usize,
        current_depth: usize,
        next_id: &mut usize,
    ) {
        if current_depth >= self.analysis_config.max_depth {
            return;
        }

        if principles.len() >= self.analysis_config.max_principles {
            return;
        }

        let parent_statement = principles[parent_idx].statement.clone();
        let sub_principles = self.extract_sub_principles(&parent_statement, current_depth);

        let mut child_ids = Vec::new();

        for (statement, principle_type, fundamentality) in sub_principles {
            if principles.len() >= self.analysis_config.max_principles {
                break;
            }

            let id = *next_id;
            *next_id += 1;
            child_ids.push(id);

            let confidence = self.estimate_confidence(&statement, principle_type);

            let principle = Principle {
                id,
                statement,
                principle_type,
                fundamentality,
                confidence,
                parent_id: Some(principles[parent_idx].id),
                child_ids: Vec::new(),
                evidence: Vec::new(),
                challenges: self.identify_challenges(principle_type),
                depth: current_depth + 1,
            };

            let new_idx = principles.len();
            principles.push(principle);

            // Only recurse for non-axiomatic principles
            if principle_type != PrincipleType::Axiom
                && fundamentality < self.analysis_config.axiom_threshold
            {
                self.decompose_recursive(principles, new_idx, current_depth + 1, next_id);
            }
        }

        principles[parent_idx].child_ids = child_ids;
    }

    /// Extract sub-principles from a statement using heuristic decomposition.
    fn extract_sub_principles(
        &self,
        statement: &str,
        depth: usize,
    ) -> Vec<(String, PrincipleType, f64)> {
        let mut sub_principles = Vec::new();
        let lower = statement.to_lowercase();

        // Extract comparative claims
        if lower.contains("better") || lower.contains("worse") || lower.contains("more") {
            sub_principles.push((
                "Comparison requires a defined metric or criterion".to_string(),
                PrincipleType::Definition,
                0.9,
            ));
            sub_principles.push((
                "Both alternatives must be well-understood".to_string(),
                PrincipleType::Assumption,
                0.7,
            ));
        }

        // Extract causal claims
        if lower.contains("because") || lower.contains("causes") || lower.contains("leads to") {
            sub_principles.push((
                "Causal relationships require evidence of mechanism".to_string(),
                PrincipleType::Empirical,
                0.6,
            ));
            sub_principles.push((
                "Correlation does not imply causation".to_string(),
                PrincipleType::Axiom,
                1.0,
            ));
        }

        // Extract quantitative claims
        if lower.contains("all")
            || lower.contains("every")
            || lower.contains("none")
            || lower.contains("never")
        {
            sub_principles.push((
                "Universal claims require exhaustive verification".to_string(),
                PrincipleType::Axiom,
                1.0,
            ));
            sub_principles.push((
                "A single counterexample disproves a universal claim".to_string(),
                PrincipleType::Axiom,
                1.0,
            ));
        }

        // Extract value judgments
        if lower.contains("good")
            || lower.contains("bad")
            || lower.contains("right")
            || lower.contains("wrong")
        {
            sub_principles.push((
                "Value judgments require a defined value framework".to_string(),
                PrincipleType::Definition,
                0.85,
            ));
            sub_principles.push((
                "Different stakeholders may have different values".to_string(),
                PrincipleType::Assumption,
                0.75,
            ));
        }

        // Extract temporal claims
        if lower.contains("will") || lower.contains("future") || lower.contains("predict") {
            sub_principles.push((
                "Future predictions carry inherent uncertainty".to_string(),
                PrincipleType::Axiom,
                1.0,
            ));
            sub_principles.push((
                "Past patterns may not continue".to_string(),
                PrincipleType::Assumption,
                0.6,
            ));
        }

        // Default decomposition if no specific patterns found
        if sub_principles.is_empty() && depth < self.analysis_config.max_depth {
            sub_principles.push((
                "The claim contains implicit assumptions".to_string(),
                PrincipleType::Assumption,
                0.5,
            ));
            sub_principles.push((
                "Terms used may have multiple interpretations".to_string(),
                PrincipleType::Definition,
                0.6,
            ));
        }

        sub_principles
    }

    /// Estimate confidence for a principle based on its type and content.
    fn estimate_confidence(&self, _statement: &str, principle_type: PrincipleType) -> f64 {
        match principle_type {
            PrincipleType::Axiom => 0.95,
            PrincipleType::Definition => 0.90,
            PrincipleType::Empirical => 0.75,
            PrincipleType::Derived => 0.70,
            PrincipleType::Assumption => 0.55,
            PrincipleType::Contested => 0.40,
        }
    }

    /// Identify potential challenges to a principle type.
    fn identify_challenges(&self, principle_type: PrincipleType) -> Vec<String> {
        match principle_type {
            PrincipleType::Axiom => vec![],
            PrincipleType::Definition => {
                vec!["Alternative definitions may exist".to_string()]
            }
            PrincipleType::Empirical => vec![
                "Data may be outdated".to_string(),
                "Sample may not be representative".to_string(),
            ],
            PrincipleType::Derived => vec![
                "Derivation logic may have flaws".to_string(),
                "Missing intermediate steps".to_string(),
            ],
            PrincipleType::Assumption => vec![
                "Assumption may not hold in all contexts".to_string(),
                "Implicit bias may be present".to_string(),
            ],
            PrincipleType::Contested => vec![
                "Subject to debate".to_string(),
                "Evidence may support opposing views".to_string(),
            ],
        }
    }

    /// Incorporate context from previous reasoning steps.
    fn incorporate_context(
        &self,
        principles: &mut Vec<Principle>,
        previous_steps: &[String],
        next_id: &mut usize,
    ) {
        for step in previous_steps {
            if principles.len() >= self.analysis_config.max_principles {
                break;
            }

            let principle_type = self.classify_query(step);
            let id = *next_id;
            *next_id += 1;

            let principle = Principle {
                id,
                statement: format!("Prior context: {}", step),
                principle_type,
                fundamentality: 0.3, // Context is not foundational
                confidence: 0.7,     // Moderate confidence in prior reasoning
                parent_id: None,
                child_ids: Vec::new(),
                evidence: vec!["From previous reasoning step".to_string()],
                challenges: vec!["May need re-evaluation in new context".to_string()],
                depth: 0, // Context is at root level
            };

            principles.push(principle);
        }
    }

    /// Classify all principles and refine their types.
    fn classify_principles(&self, principles: &mut [Principle]) {
        for principle in principles.iter_mut() {
            // Upgrade to axiom if fundamentality is high enough
            if principle.fundamentality >= self.analysis_config.axiom_threshold
                && principle.principle_type != PrincipleType::Axiom
                && principle.principle_type != PrincipleType::Contested
            {
                principle.principle_type = PrincipleType::Axiom;
                principle.challenges.clear();
            }

            // Downgrade contested claims with no support
            if principle.evidence.is_empty() && principle.principle_type == PrincipleType::Empirical
            {
                principle.principle_type = PrincipleType::Assumption;
                principle.confidence *= 0.8;
            }
        }
    }

    /// Build reconstruction paths from axioms to the root claim.
    fn build_reconstructions(&self, principles: &[Principle]) -> Vec<ReconstructionPath> {
        let mut reconstructions = Vec::new();

        // Find all axioms
        let axioms: Vec<_> = principles
            .iter()
            .filter(|p| p.principle_type == PrincipleType::Axiom)
            .collect();

        // For each axiom, try to build a path to the root
        for axiom in axioms {
            let mut path = vec![axiom.id];
            let mut connectives = Vec::new();
            let mut current_id = axiom.id;
            let mut gaps = Vec::new();

            // Traverse up to parents
            while let Some(principle) = principles.iter().find(|p| p.id == current_id) {
                if let Some(parent_idx) = principles.iter().position(|p| {
                    p.child_ids.contains(&current_id) || Some(p.id) == principle.parent_id
                }) {
                    let parent = &principles[parent_idx];
                    path.push(parent.id);
                    connectives.push("implies".to_string());
                    current_id = parent.id;
                } else {
                    break;
                }

                // Prevent infinite loops
                if path.len() > principles.len() {
                    gaps.push("Circular dependency detected".to_string());
                    break;
                }
            }

            // Check if we reached the root (depth 0)
            let is_complete = principles
                .iter()
                .any(|p| path.contains(&p.id) && p.depth == 0);

            if !is_complete {
                gaps.push("Path does not reach the original claim".to_string());
            }

            let confidence = if is_complete && gaps.is_empty() {
                axiom.confidence * 0.9
            } else {
                axiom.confidence * 0.5
            };

            reconstructions.push(ReconstructionPath {
                principle_chain: path,
                connectives,
                confidence,
                is_complete,
                gaps,
            });
        }

        reconstructions
    }

    /// Identify gaps in the analysis.
    fn identify_gaps(
        &self,
        principles: &[Principle],
        reconstructions: &[ReconstructionPath],
    ) -> Vec<AnalysisGap> {
        let mut gaps = Vec::new();

        // Check for missing axioms (no reconstruction paths)
        if reconstructions.is_empty() {
            gaps.push(AnalysisGap {
                description: "No axiomatic foundation identified".to_string(),
                severity: 0.9,
                suggestion: Some("Decompose further to find self-evident truths".to_string()),
                affected_principles: principles.iter().map(|p| p.id).collect(),
            });
        }

        // Check for incomplete paths
        let incomplete_paths: Vec<_> = reconstructions.iter().filter(|r| !r.is_complete).collect();

        if !incomplete_paths.is_empty() {
            gaps.push(AnalysisGap {
                description: format!(
                    "{} reconstruction path(s) do not reach the root claim",
                    incomplete_paths.len()
                ),
                severity: 0.7,
                suggestion: Some("Add intermediate principles to complete the chain".to_string()),
                affected_principles: incomplete_paths
                    .iter()
                    .flat_map(|r| r.principle_chain.clone())
                    .collect(),
            });
        }

        // Check for unsupported assumptions
        let unsupported_assumptions: Vec<_> = principles
            .iter()
            .filter(|p| p.principle_type == PrincipleType::Assumption && p.evidence.is_empty())
            .collect();

        if !unsupported_assumptions.is_empty() {
            gaps.push(AnalysisGap {
                description: format!(
                    "{} assumption(s) lack supporting evidence",
                    unsupported_assumptions.len()
                ),
                severity: 0.6,
                suggestion: Some("Provide evidence or acknowledge as unverified".to_string()),
                affected_principles: unsupported_assumptions.iter().map(|p| p.id).collect(),
            });
        }

        // Check for low-confidence principles
        let low_confidence: Vec<_> = principles
            .iter()
            .filter(|p| p.confidence < self.analysis_config.min_confidence)
            .collect();

        if !low_confidence.is_empty() {
            gaps.push(AnalysisGap {
                description: format!(
                    "{} principle(s) have confidence below threshold",
                    low_confidence.len()
                ),
                severity: 0.5,
                suggestion: Some("Verify or remove low-confidence principles".to_string()),
                affected_principles: low_confidence.iter().map(|p| p.id).collect(),
            });
        }

        // Check for contested claims without resolution
        let unresolved_contested: Vec<_> = principles
            .iter()
            .filter(|p| p.principle_type == PrincipleType::Contested && !p.challenges.is_empty())
            .collect();

        if !unresolved_contested.is_empty() {
            gaps.push(AnalysisGap {
                description: format!(
                    "{} contested claim(s) require resolution",
                    unresolved_contested.len()
                ),
                severity: 0.8,
                suggestion: Some("Provide evidence to resolve contested claims".to_string()),
                affected_principles: unresolved_contested.iter().map(|p| p.id).collect(),
            });
        }

        gaps
    }

    /// Extract key insights from the analysis.
    fn extract_insights(&self, principles: &[Principle], gaps: &[AnalysisGap]) -> Vec<String> {
        let mut insights = Vec::new();

        // Insight: Number of axiomatic foundations
        let axiom_count = principles
            .iter()
            .filter(|p| p.principle_type == PrincipleType::Axiom)
            .count();

        if axiom_count > 0 {
            insights.push(format!(
                "Analysis rests on {} axiomatic foundation(s)",
                axiom_count
            ));
        } else {
            insights.push(
                "No self-evident axioms identified - claim relies on assumptions".to_string(),
            );
        }

        // Insight: Assumption count
        let assumption_count = principles
            .iter()
            .filter(|p| p.principle_type == PrincipleType::Assumption)
            .count();

        if assumption_count > 0 {
            insights.push(format!(
                "{} hidden assumption(s) identified that could be challenged",
                assumption_count
            ));
        }

        // Insight: Gap severity
        let critical_gaps: Vec<_> = gaps.iter().filter(|g| g.severity >= 0.8).collect();

        if !critical_gaps.is_empty() {
            insights.push(format!(
                "{} critical gap(s) in reasoning require attention",
                critical_gaps.len()
            ));
        }

        // Insight: Depth analysis
        let max_depth = principles.iter().map(|p| p.depth).max().unwrap_or(0);
        if max_depth > 0 {
            insights.push(format!(
                "Decomposition reached {} level(s) of depth",
                max_depth
            ));
        }

        // Insight: Contested claims
        let contested_count = principles
            .iter()
            .filter(|p| p.principle_type == PrincipleType::Contested)
            .count();

        if contested_count > 0 {
            insights.push(format!(
                "{} contested claim(s) identified - these are debatable",
                contested_count
            ));
        }

        insights
    }

    /// Calculate overall confidence in the analysis.
    fn calculate_confidence(&self, principles: &[Principle], gaps: &[AnalysisGap]) -> f64 {
        if principles.is_empty() {
            return 0.0;
        }

        // Base confidence from principles
        let principle_confidence: f64 =
            principles.iter().map(|p| p.effective_weight()).sum::<f64>() / principles.len() as f64;

        // Penalty for gaps
        let gap_penalty: f64 = gaps.iter().map(|g| g.severity * 0.1).sum();

        // Bonus for axioms
        let axiom_count = principles
            .iter()
            .filter(|p| p.principle_type == PrincipleType::Axiom)
            .count();
        let axiom_bonus = (axiom_count as f64 * 0.05).min(0.2);

        (principle_confidence + axiom_bonus - gap_penalty).clamp(0.0, 1.0)
    }

    /// Calculate completeness of the analysis.
    fn calculate_completeness(&self, principles: &[Principle], gaps: &[AnalysisGap]) -> f64 {
        if principles.is_empty() {
            return 0.0;
        }

        // Check for presence of required components
        let has_axiom = principles
            .iter()
            .any(|p| p.principle_type == PrincipleType::Axiom);
        let has_definitions = principles
            .iter()
            .any(|p| p.principle_type == PrincipleType::Definition);
        let assumptions_identified = principles
            .iter()
            .any(|p| p.principle_type == PrincipleType::Assumption);

        let mut completeness = 0.0;

        if has_axiom {
            completeness += 0.3;
        }
        if has_definitions {
            completeness += 0.2;
        }
        if assumptions_identified {
            completeness += 0.2;
        }

        // Depth bonus
        let max_depth = principles.iter().map(|p| p.depth).max().unwrap_or(0);
        completeness += (max_depth as f64 * 0.1).min(0.2);

        // Gap penalty
        let critical_gaps = gaps.iter().filter(|g| g.severity >= 0.8).count();
        completeness -= critical_gaps as f64 * 0.1;

        completeness.clamp(0.0, 1.0)
    }
}

impl ThinkToolModule for BedRock {
    fn config(&self) -> &ThinkToolModuleConfig {
        &self.config
    }

    fn execute(&self, context: &ThinkToolContext) -> Result<ThinkToolOutput, crate::error::Error> {
        // Perform first principles decomposition
        let result = self.decompose(&context.query, &context.previous_steps);

        Ok(ThinkToolOutput {
            module: self.config.name.clone(),
            confidence: result.confidence,
            output: result.to_json(),
        })
    }
}

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

    #[test]
    fn test_bedrock_new() {
        let bedrock = BedRock::new();
        assert_eq!(bedrock.config().name, "BedRock");
        assert_eq!(bedrock.config().version, "3.0.0");
    }

    #[test]
    fn test_bedrock_with_config() {
        let config = BedRockConfig {
            max_depth: 5,
            axiom_threshold: 0.9,
            ..Default::default()
        };
        let bedrock = BedRock::with_config(config);
        assert_eq!(bedrock.analysis_config().max_depth, 5);
        assert_eq!(bedrock.analysis_config().axiom_threshold, 0.9);
    }

    #[test]
    fn test_principle_type_reliability() {
        assert_eq!(PrincipleType::Axiom.reliability_weight(), 1.0);
        assert_eq!(PrincipleType::Contested.reliability_weight(), 0.30);
        assert!(
            PrincipleType::Assumption.reliability_weight()
                < PrincipleType::Derived.reliability_weight()
        );
    }

    #[test]
    fn test_decompose_simple_query() {
        let bedrock = BedRock::new();
        let result = bedrock.decompose("Electric vehicles are better than gas cars", &[]);

        assert!(!result.principles.is_empty());
        assert_eq!(result.query, "Electric vehicles are better than gas cars");
        assert!(result.confidence > 0.0);
        assert!(!result.insights.is_empty());
    }

    #[test]
    fn test_decompose_with_comparison() {
        let bedrock = BedRock::new();
        let result = bedrock.decompose("Python is better than JavaScript for data science", &[]);

        // Should identify that comparison requires metrics
        let has_definition = result
            .principles
            .iter()
            .any(|p| p.principle_type == PrincipleType::Definition);
        assert!(has_definition, "Should identify need for comparison metric");
    }

    #[test]
    fn test_decompose_with_causation() {
        let bedrock = BedRock::new();
        let result = bedrock.decompose("Smoking causes cancer", &[]);

        // Should identify causal analysis requirements
        let has_axiom = result
            .principles
            .iter()
            .any(|p| p.principle_type == PrincipleType::Axiom);
        assert!(
            has_axiom,
            "Should identify axiomatic principles about causation"
        );
    }

    #[test]
    fn test_execute_trait() {
        let bedrock = BedRock::new();
        let context = ThinkToolContext {
            query: "What is the best programming language?".into(),
            previous_steps: vec!["Prior analysis: Consider use case".into()],
        };

        let output = bedrock.execute(&context).expect("Execution should succeed");

        assert_eq!(output.module, "BedRock");
        assert!(output.confidence > 0.0);
        assert!(output.output.get("axioms").is_some());
        assert!(output.output.get("assumptions").is_some());
        assert!(output.output.get("decomposition").is_some());
        assert!(output.output.get("insights").is_some());
    }

    #[test]
    fn test_classify_query() {
        let bedrock = BedRock::new();

        // Definition query
        let def_type = bedrock.classify_query("What is machine learning?");
        assert_eq!(def_type, PrincipleType::Definition);

        // Empirical query
        let emp_type = bedrock.classify_query("Research shows that exercise improves health");
        assert_eq!(emp_type, PrincipleType::Empirical);

        // Contested/value query
        let contested_type = bedrock.classify_query("Rust is better than C++");
        assert_eq!(contested_type, PrincipleType::Contested);
    }

    #[test]
    fn test_result_accessors() {
        let bedrock = BedRock::new();
        let result = bedrock.decompose("All birds can fly", &[]);

        // Universal claims should generate axioms about universal statements
        let _axioms = result.axioms();
        let _assumptions = result.assumptions();

        // Check that we can access principles at different depths
        let root_principles = result.at_depth(0);
        assert!(!root_principles.is_empty());

        // Check completeness calculation
        assert!(result.metadata.completeness >= 0.0);
        assert!(result.metadata.completeness <= 1.0);
    }

    #[test]
    fn test_principle_effective_weight() {
        let principle = Principle {
            id: 0,
            statement: "Test axiom".into(),
            principle_type: PrincipleType::Axiom,
            fundamentality: 1.0,
            confidence: 0.95,
            parent_id: None,
            child_ids: vec![],
            evidence: vec![],
            challenges: vec![],
            depth: 0,
        };

        let weight = principle.effective_weight();
        assert_eq!(weight, 0.95); // 1.0 * 0.95 * 1.0
        assert!(principle.is_axiomatic(0.85));
    }

    #[test]
    fn test_gap_identification() {
        let bedrock = BedRock::new();
        let result = bedrock.decompose("This is a vague statement", &[]);

        // Should identify gaps
        // Note: gaps may or may not be found depending on decomposition
        // Gap identification may or may not find gaps depending on decomposition.
        // The invariant here is simply that the `gaps` collection is usable.
        let _ = &result.gaps;
    }

    #[test]
    fn test_max_principles_limit() {
        let config = BedRockConfig {
            max_principles: 5,
            ..Default::default()
        };
        let bedrock = BedRock::with_config(config);
        let result = bedrock.decompose("Complex multi-part query about many things", &[]);

        assert!(result.principles.len() <= 5);
    }

    #[test]
    fn test_json_output_structure() {
        let bedrock = BedRock::new();
        let result = bedrock.decompose("Test query for JSON", &[]);
        let json = result.to_json();

        assert!(json.get("query").is_some());
        assert!(json.get("axioms").is_some());
        assert!(json.get("assumptions").is_some());
        assert!(json.get("decomposition").is_some());
        assert!(json.get("reconstruction").is_some());
        assert!(json.get("gaps").is_some());
        assert!(json.get("insights").is_some());
        assert!(json.get("confidence").is_some());
        assert!(json.get("metadata").is_some());
    }

    // ========================================================================
    // Tree-of-Thoughts (ToT) Tests
    // Based on Yao et al. 2023: "Tree of Thoughts: Deliberate Problem Solving"
    // ========================================================================

    #[test]
    fn test_exploration_strategy_use_cases() {
        assert_eq!(
            ExplorationStrategy::BreadthFirst.use_case(),
            "Unknown solution depth, want all solutions at each level"
        );
        assert_eq!(
            ExplorationStrategy::DepthFirst.use_case(),
            "Deep solutions, good pruning heuristics available"
        );
        assert_eq!(
            ExplorationStrategy::BestFirst.use_case(),
            "Reliable value function, want fastest path to good solution"
        );
        assert_eq!(
            ExplorationStrategy::AStar.use_case(),
            "Need optimal solution, have admissible heuristic"
        );
        assert_eq!(
            ExplorationStrategy::BeamSearch.use_case(),
            "Limited compute budget, want diverse high-quality solutions"
        );
    }

    #[test]
    fn test_tot_config_defaults() {
        let config = ToTConfig::default();
        assert_eq!(config.strategy, ExplorationStrategy::BreadthFirst);
        assert_eq!(config.branching_factor, 3);
        assert_eq!(config.beam_width, 5);
        assert_eq!(config.max_nodes, 100);
        assert!((config.pruning_threshold - 0.3).abs() < f64::EPSILON);
        assert!(config.enable_backtracking);
        assert_eq!(config.max_depth, 4);
        assert!(config.aggregate_paths);
        assert_eq!(config.voting_samples, 0);
    }

    #[test]
    fn test_tot_config_presets() {
        // BFS preset
        let bfs = ToTConfig::bfs();
        assert_eq!(bfs.strategy, ExplorationStrategy::BreadthFirst);
        assert_eq!(bfs.branching_factor, 4);
        assert_eq!(bfs.beam_width, 10);
        assert_eq!(bfs.max_nodes, 200);

        // DFS preset
        let dfs = ToTConfig::dfs();
        assert_eq!(dfs.strategy, ExplorationStrategy::DepthFirst);
        assert_eq!(dfs.branching_factor, 2);
        assert_eq!(dfs.max_depth, 6);
        assert!((dfs.pruning_threshold - 0.4).abs() < f64::EPSILON);

        // Beam search preset
        let beam = ToTConfig::beam(8);
        assert_eq!(beam.strategy, ExplorationStrategy::BeamSearch);
        assert_eq!(beam.beam_width, 8);
        assert!(beam.aggregate_paths);
    }

    #[test]
    fn test_thought_node_root() {
        let root = ThoughtNode::root("What is the optimal solution?");
        assert_eq!(root.id, 0);
        assert_eq!(root.thought, "What is the optimal solution?");
        assert!((root.value - 1.0).abs() < f64::EPSILON);
        assert_eq!(root.depth, 0);
        assert!(root.parent_id.is_none());
        assert!(root.children.is_empty());
        assert!(!root.is_terminal);
        assert!(!root.is_pruned);
        assert_eq!(root.path, vec![0]);
        assert_eq!(root.generation_method, ThoughtGenerationMethod::Decomposed);
    }

    #[test]
    fn test_thought_node_child() {
        let root = ThoughtNode::root("Root thought");
        let child = ThoughtNode::child(1, "Child thought", 0.8, &root);

        assert_eq!(child.id, 1);
        assert_eq!(child.thought, "Child thought");
        assert!((child.value - 0.8).abs() < f64::EPSILON);
        assert_eq!(child.depth, 1);
        assert_eq!(child.parent_id, Some(0));
        assert!(child.children.is_empty());
        assert_eq!(child.path, vec![0, 1]);
    }

    #[test]
    fn test_thought_node_pruning_threshold() {
        let root = ThoughtNode::root("Root");
        let high_value = ThoughtNode::child(1, "High value", 0.9, &root);
        let low_value = ThoughtNode::child(2, "Low value", 0.2, &root);

        assert!(!high_value.should_prune(0.3));
        assert!(low_value.should_prune(0.3));
    }

    #[test]
    fn test_tot_explorer_bfs_initialization() {
        let mut explorer = ToTExplorer::bfs();
        explorer.initialize("Problem: Find optimal path");

        assert_eq!(explorer.node_count(), 1);
        assert!(explorer.should_continue());

        let root = explorer.get_node(0).unwrap();
        assert_eq!(root.thought, "Problem: Find optimal path");
    }

    #[test]
    fn test_tot_explorer_add_children() {
        let mut explorer = ToTExplorer::bfs();
        explorer.initialize("Root problem");

        // Add children to root
        let child1 = explorer.add_child(0, "Approach A", 0.8);
        let child2 = explorer.add_child(0, "Approach B", 0.7);
        let child3 = explorer.add_child(0, "Approach C", 0.6);

        assert_eq!(explorer.node_count(), 4);

        let root = explorer.get_node(0).unwrap();
        assert_eq!(root.children.len(), 3);
        assert!(root.children.contains(&child1));
        assert!(root.children.contains(&child2));
        assert!(root.children.contains(&child3));
    }

    #[test]
    fn test_tot_explorer_pruning() {
        let config = ToTConfig {
            pruning_threshold: 0.5,
            ..ToTConfig::default()
        };
        let mut explorer = ToTExplorer::new(config);
        explorer.initialize("Root");

        // Add a low-value child that should be pruned
        let pruned_id = explorer.add_child(0, "Low value thought", 0.2);

        let pruned_node = explorer.get_node(pruned_id).unwrap();
        assert!(pruned_node.is_pruned);
    }

    #[test]
    fn test_tot_explorer_terminal_marking() {
        let mut explorer = ToTExplorer::bfs();
        explorer.initialize("Root");

        let child1 = explorer.add_child(0, "Solution candidate", 0.9);
        explorer.mark_terminal(child1);

        let terminal = explorer.get_node(child1).unwrap();
        assert!(terminal.is_terminal);
    }

    #[test]
    fn test_tot_explorer_bfs_order() {
        let mut explorer = ToTExplorer::bfs();
        explorer.initialize("Root");

        // BFS should expand nodes level by level
        let child1 = explorer.add_child(0, "Level 1 - A", 0.8);
        let child2 = explorer.add_child(0, "Level 1 - B", 0.7);

        // BFS should return a level-1 node first (shallowest)
        let next = explorer.next_to_expand();
        assert!(next == Some(child1) || next == Some(child2));
    }

    #[test]
    fn test_tot_explorer_dfs_order() {
        let mut explorer = ToTExplorer::dfs();
        explorer.initialize("Root");

        let child1 = explorer.add_child(0, "Level 1 - A", 0.8);
        let _child2 = explorer.add_child(0, "Level 1 - B", 0.7);

        // Add deeper node
        let grandchild = explorer.add_child(child1, "Level 2 - A", 0.75);

        // DFS should return deepest unexpanded node
        let next = explorer.next_to_expand();
        assert_eq!(next, Some(grandchild));
    }

    #[test]
    fn test_tot_explorer_beam_frontier() {
        let mut explorer = ToTExplorer::beam(2);
        explorer.initialize("Root");

        // Add 4 children at level 1
        explorer.add_child(0, "A", 0.9);
        explorer.add_child(0, "B", 0.6);
        explorer.add_child(0, "C", 0.8);
        explorer.add_child(0, "D", 0.5);

        // Beam width 2 should keep only top 2
        let frontier = explorer.get_beam_frontier();
        assert_eq!(frontier.len(), 2);
    }

    #[test]
    fn test_tot_explorer_finish_results() {
        let mut explorer = ToTExplorer::bfs();
        explorer.initialize("Problem: 2+2");

        let child1 = explorer.add_child(0, "Try addition", 0.8);
        let solution = explorer.add_child(child1, "Answer: 4", 0.95);
        explorer.mark_terminal(solution);

        let result = explorer.finish();

        assert_eq!(result.terminal_nodes.len(), 1);
        assert!(result.terminal_nodes.contains(&solution));
        assert_eq!(result.best_path, vec![0, child1, solution]);
        assert!((result.best_value - 0.95).abs() < f64::EPSILON);
        assert!(result.stats.nodes_created >= 3);
        assert_eq!(result.stats.solutions_found, 1);
    }

    #[test]
    fn test_tot_result_best_path_thoughts() {
        let mut explorer = ToTExplorer::bfs();
        explorer.initialize("Root thought");

        let child = explorer.add_child(0, "Middle thought", 0.8);
        let solution = explorer.add_child(child, "Final thought", 0.9);
        explorer.mark_terminal(solution);

        let result = explorer.finish();
        let thoughts = result.best_path_thoughts();

        assert_eq!(thoughts.len(), 3);
        assert_eq!(thoughts[0], "Root thought");
        assert_eq!(thoughts[1], "Middle thought");
        assert_eq!(thoughts[2], "Final thought");
    }

    #[test]
    fn test_tot_result_all_solutions() {
        let mut explorer = ToTExplorer::bfs();
        explorer.initialize("Root");

        let path1 = explorer.add_child(0, "Path 1", 0.7);
        let sol1 = explorer.add_child(path1, "Solution 1", 0.8);
        explorer.mark_terminal(sol1);

        let path2 = explorer.add_child(0, "Path 2", 0.8);
        let sol2 = explorer.add_child(path2, "Solution 2", 0.95);
        explorer.mark_terminal(sol2);

        let result = explorer.finish();
        let solutions = result.all_solutions();

        assert_eq!(solutions.len(), 2);
        // Should be sorted by value descending
        assert!((solutions[0].1 - 0.95).abs() < f64::EPSILON);
        assert!((solutions[1].1 - 0.8).abs() < f64::EPSILON);
    }

    #[test]
    fn test_tot_stats_effective_branching_factor() {
        let mut explorer = ToTExplorer::bfs();
        explorer.initialize("Root");

        // Root has 3 children
        explorer.add_child(0, "A", 0.8);
        explorer.add_child(0, "B", 0.7);
        explorer.add_child(0, "C", 0.6);

        let result = explorer.finish();

        // One node (root) has 3 children -> EBF = 3.0
        assert!((result.stats.effective_branching_factor - 3.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_tot_max_depth_limit() {
        let config = ToTConfig {
            max_depth: 2,
            ..ToTConfig::default()
        };
        let mut explorer = ToTExplorer::new(config);
        explorer.initialize("Root");

        let child1 = explorer.add_child(0, "Depth 1", 0.8);
        let child2 = explorer.add_child(child1, "Depth 2", 0.8);

        // At max depth, should not be able to expand further
        // next_to_expand filters by depth < max_depth
        // child2 is at depth 2, equal to max_depth, so should not be expandable
        let _ = explorer.add_child(child2, "Depth 3", 0.8);
        let next = explorer.next_to_expand();

        // Should not return any node at depth 2 (which equals max_depth)
        if let Some(id) = next {
            let node = explorer.get_node(id).unwrap();
            assert!(node.depth < 2);
        }
    }

    #[test]
    fn test_tot_serialization() {
        let config = ToTConfig::beam(3);
        let json = serde_json::to_string(&config).unwrap();
        let deserialized: ToTConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.beam_width, 3);
        assert_eq!(deserialized.strategy, ExplorationStrategy::BeamSearch);
    }

    #[test]
    fn test_thought_generation_method_default() {
        assert_eq!(
            ThoughtGenerationMethod::default(),
            ThoughtGenerationMethod::Sampled
        );
    }

    #[test]
    fn test_tot_explorer_should_continue_max_nodes() {
        let config = ToTConfig {
            max_nodes: 3,
            ..ToTConfig::default()
        };
        let mut explorer = ToTExplorer::new(config);
        explorer.initialize("Root");

        explorer.add_child(0, "A", 0.8);
        explorer.add_child(0, "B", 0.7);

        // Now we have 3 nodes, should stop
        assert!(!explorer.should_continue());
    }
}