thales 0.4.2

A comprehensive Computer Algebra System (CAS) library for symbolic mathematics, equation solving, calculus, and linear algebra
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
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
//! Resolution path tracking for equation solving.
//!
//! This module provides a comprehensive system for tracking and explaining the step-by-step
//! solution process when solving algebraic equations. It enables educational applications
//! to show students not just the answer, but the complete reasoning path.
//!
//! # Core Concepts
//!
//! The resolution path system consists of three main components:
//!
//! - **[`ResolutionPath`]**: The complete solution journey from initial equation to final answer,
//!   including all intermediate steps and transformations.
//! - **[`ResolutionStep`]**: A single operation in the solution process, consisting of the
//!   operation performed, why it was chosen, and the resulting expression state.
//! - **[`Operation`]**: The type of algebraic manipulation applied (e.g., "add to both sides",
//!   "simplify", "factor").
//!
//! # Use Cases
//!
//! This module is designed for:
//!
//! - **Educational Apps**: Show students how to solve equations step-by-step
//! - **Hint Generation**: Provide progressive hints based on solution steps
//! - **Solution Validation**: Verify that each step is mathematically sound
//! - **Multiple Solution Methods**: Compare different approaches to the same problem
//! - **Slide Rule Training**: Generate appropriate hints for slide rule calculations
//!
//! # Example: Building a Solution Path
//!
//! ```rust
//! use thales::resolution_path::{ResolutionPathBuilder, Operation};
//! use thales::ast::{Expression, Variable};
//!
//! // Solve: 2x + 3 = 7
//! let initial = Expression::Integer(7); // Starting from right side
//! let x = Variable::new("x");
//!
//! let path = ResolutionPathBuilder::new(initial)
//!     .step(
//!         Operation::SubtractBothSides(Expression::Integer(3)),
//!         "Subtract 3 from both sides to isolate the term with x".to_string(),
//!         Expression::Integer(4), // 7 - 3 = 4
//!     )
//!     .step(
//!         Operation::DivideBothSides(Expression::Integer(2)),
//!         "Divide both sides by 2 to solve for x".to_string(),
//!         Expression::Integer(2), // 4 / 2 = 2
//!     )
//!     .finish(Expression::Integer(2));
//!
//! assert_eq!(path.step_count(), 2);
//! assert!(!path.is_empty());
//! ```
//!
//! # Example: Using the Fluent Builder API
//!
//! ```rust
//! use thales::resolution_path::ResolutionPathBuilder;
//! use thales::ast::{Expression, Variable};
//!
//! let x = Variable::new("x");
//! let initial = Expression::Integer(10);
//!
//! // Specialized builder methods for common operations
//! let path = ResolutionPathBuilder::new(initial)
//!     .simplify("Combine like terms".to_string(), Expression::Integer(10))
//!     .isolate(x, "Isolate x on left side".to_string(), Expression::Integer(5))
//!     .finish(Expression::Integer(5));
//!
//! assert_eq!(path.step_count(), 2);
//! ```
//!
//! # Integration with Solver
//!
//! Solvers implementing the [`crate::solver::Solver`] trait return both the solution
//! and the resolution path, enabling applications to show the work:
//!
//! ```ignore
//! use thales::solver::Solver;
//! use thales::ast::{Equation, Variable};
//!
//! let equation = /* ... */;
//! let variable = Variable::new("x");
//!
//! let (solution, path) = solver.solve(&equation, &variable)?;
//!
//! // Generate hints for students
//! for (i, step) in path.steps.iter().enumerate() {
//!     println!("Step {}: {}", i + 1, step.explanation);
//!     println!("  Operation: {}", step.operation.describe());
//!     println!("  Result: {:?}", step.result);
//! }
//! ```
//!
//! # Slide Rule Application Integration
//!
//! For the SlideRuleCoach app, resolution paths can generate appropriate calculation hints:
//!
//! ```ignore
//! // When solving problems like "Find the area: A = πr²"
//! // The path can suggest which slide rule scales to use
//! let path = ResolutionPathBuilder::new(equation)
//!     .step(
//!         Operation::Substitute { variable: r, value: Expression::Float(2.5) },
//!         "Substitute r = 2.5 into the formula".to_string(),
//!         substituted_expr,
//!     )
//!     .step(
//!         Operation::PowerBothSides(Expression::Integer(2)),
//!         "Square the radius using A and B scales on slide rule".to_string(),
//!         squared_expr,
//!     )
//!     .step(
//!         Operation::MultiplyBothSides(Expression::Float(3.14159)),
//!         "Multiply by π using C and D scales".to_string(),
//!         final_result,
//!     )
//!     .finish(final_result);
//! ```

use crate::ast::{Expression, Variable};
use serde_json::{json, Value as JsonValue};

/// Level of detail for resolution path output.
///
/// Controls how much detail is included when rendering a resolution path
/// to text, LaTeX, or other formats.
///
/// # Example
///
/// ```rust
/// use thales::resolution_path::{ResolutionPath, Verbosity};
/// use thales::ast::Expression;
///
/// let path = ResolutionPath::new(Expression::Integer(10));
/// let minimal = path.to_text(Verbosity::Minimal);
/// let detailed = path.to_text(Verbosity::Detailed);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Verbosity {
    /// Key transformations only - shows just the essential operations.
    ///
    /// Best for quick overviews or when the user is already familiar
    /// with the solution technique.
    Minimal,

    /// Major steps - standard level of detail for educational purposes.
    ///
    /// Shows all significant steps without overwhelming detail.
    #[default]
    Standard,

    /// Every algebraic manipulation - maximum detail for learning.
    ///
    /// Includes all intermediate steps and detailed explanations,
    /// ideal for students learning the technique for the first time.
    Detailed,
}

/// Statistics about a resolution path.
///
/// Provides aggregate information about the solution process, useful for
/// analyzing problem difficulty, comparing solution methods, or tracking
/// student progress.
///
/// # Example
///
/// ```rust
/// use thales::resolution_path::{ResolutionPath, ResolutionStep, Operation};
/// use thales::ast::Expression;
///
/// let mut path = ResolutionPath::new(Expression::Integer(10));
/// path.add_step(ResolutionStep::new(
///     Operation::Simplify,
///     "Simplify".to_string(),
///     Expression::Integer(10),
/// ));
/// path.add_step(ResolutionStep::new(
///     Operation::DivideBothSides(Expression::Integer(2)),
///     "Divide by 2".to_string(),
///     Expression::Integer(5),
/// ));
///
/// let stats = path.statistics();
/// assert_eq!(stats.total_steps, 2);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct PathStatistics {
    /// Total number of steps in the path.
    pub total_steps: usize,

    /// Count of operations by category.
    pub operation_counts: OperationCounts,

    /// Unique operation types used.
    pub unique_operations: usize,

    /// Whether the path uses advanced methods (quadratic formula, etc.).
    pub uses_advanced_methods: bool,

    /// Whether the path involves calculus operations.
    pub uses_calculus: bool,

    /// Whether the path involves matrix operations.
    pub uses_matrix_operations: bool,
}

/// Count of operations by category.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct OperationCounts {
    /// Both-sides operations (add, subtract, multiply, divide, etc.)
    pub both_sides: usize,
    /// Expression transformations (simplify, expand, factor, etc.)
    pub transformations: usize,
    /// Variable manipulations (substitute, isolate, move term)
    pub variable_ops: usize,
    /// Identity applications (algebraic, trig, log)
    pub identities: usize,
    /// Advanced methods (quadratic formula, complete square, numerical)
    pub advanced: usize,
    /// Calculus operations (differentiate, integrate, limit, etc.)
    pub calculus: usize,
    /// Matrix operations
    pub matrix: usize,
    /// Custom operations
    pub custom: usize,
}

/// Represents a complete solution path from equation to answer.
///
/// A `ResolutionPath` captures the entire solution journey, from the initial equation
/// state through all intermediate transformations to the final result. This enables
/// educational applications to provide step-by-step explanations and progressive hints.
///
/// # Structure
///
/// - `initial`: The starting equation or expression state before any operations
/// - `steps`: Ordered sequence of operations and their results
/// - `result`: The final simplified expression after all operations
///
/// # Example
///
/// ```rust
/// use thales::resolution_path::{ResolutionPath, ResolutionStep, Operation};
/// use thales::ast::Expression;
///
/// // Create a path for solving 5x = 15
/// let mut path = ResolutionPath::new(Expression::Integer(15));
///
/// // Add step: divide both sides by 5
/// path.add_step(ResolutionStep::new(
///     Operation::DivideBothSides(Expression::Integer(5)),
///     "Divide both sides by 5 to isolate x".to_string(),
///     Expression::Integer(3),
/// ));
///
/// path.set_result(Expression::Integer(3));
///
/// assert_eq!(path.step_count(), 1);
/// assert!(!path.is_empty());
/// ```
///
/// # Educational Use
///
/// Resolution paths support progressive hint systems:
///
/// ```rust
/// use thales::resolution_path::ResolutionPath;
/// use thales::ast::Expression;
///
/// let path = ResolutionPath::new(Expression::Integer(10));
/// // ... add steps ...
///
/// // Hint level 1: Show number of steps needed
/// println!("This problem requires {} steps", path.step_count());
///
/// // Hint level 2: Show first operation type
/// if let Some(first_step) = path.steps.first() {
///     println!("First, try: {}", first_step.operation.describe());
/// }
///
/// // Hint level 3: Show full explanation
/// if let Some(first_step) = path.steps.first() {
///     println!("{}", first_step.explanation);
/// }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct ResolutionPath {
    /// Initial equation state before any transformations.
    ///
    /// This represents the starting point of the solution process,
    /// typically the original equation or one side of it.
    pub initial: Expression,

    /// Sequence of operations applied to reach the solution.
    ///
    /// Each step includes the operation performed, an explanation of why,
    /// and the resulting expression state. Steps are ordered chronologically.
    pub steps: Vec<ResolutionStep>,

    /// Final simplified result after all operations.
    ///
    /// This is the solution to the equation, fully simplified.
    /// For example, solving "2x + 3 = 7" would result in "x = 2".
    pub result: Expression,
}

impl ResolutionPath {
    /// Create a new resolution path starting from an initial expression.
    ///
    /// The path begins with no steps, and the result is initially set to
    /// the same value as the initial expression.
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::ResolutionPath;
    /// use thales::ast::Expression;
    ///
    /// let initial = Expression::Integer(42);
    /// let path = ResolutionPath::new(initial.clone());
    ///
    /// assert_eq!(path.initial, initial);
    /// assert_eq!(path.result, initial);
    /// assert!(path.is_empty());
    /// ```
    pub fn new(initial: Expression) -> Self {
        Self {
            initial: initial.clone(),
            steps: Vec::new(),
            result: initial,
        }
    }

    /// Add a step to the resolution path.
    ///
    /// Steps are appended in chronological order. Each step records the
    /// operation performed, the reasoning behind it, and the resulting
    /// expression state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::{ResolutionPath, ResolutionStep, Operation};
    /// use thales::ast::Expression;
    ///
    /// let mut path = ResolutionPath::new(Expression::Integer(10));
    ///
    /// path.add_step(ResolutionStep::new(
    ///     Operation::Simplify,
    ///     "Simplify the expression".to_string(),
    ///     Expression::Integer(10),
    /// ));
    ///
    /// assert_eq!(path.step_count(), 1);
    /// ```
    pub fn add_step(&mut self, step: ResolutionStep) {
        self.steps.push(step);
    }

    /// Set the final result of the solution path.
    ///
    /// This should be called after all steps have been added to record
    /// the final simplified solution.
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::ResolutionPath;
    /// use thales::ast::Expression;
    ///
    /// let mut path = ResolutionPath::new(Expression::Integer(10));
    /// // ... add steps ...
    /// path.set_result(Expression::Integer(5));
    ///
    /// assert_eq!(path.result, Expression::Integer(5));
    /// ```
    pub fn set_result(&mut self, result: Expression) {
        self.result = result;
    }

    /// Get the number of steps in the path.
    ///
    /// Returns the count of operations that have been applied. This is useful
    /// for educational applications to indicate problem complexity or to
    /// track student progress.
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::{ResolutionPath, ResolutionStep, Operation};
    /// use thales::ast::Expression;
    ///
    /// let mut path = ResolutionPath::new(Expression::Integer(20));
    ///
    /// assert_eq!(path.step_count(), 0);
    ///
    /// path.add_step(ResolutionStep::new(
    ///     Operation::Simplify,
    ///     "Simplify".to_string(),
    ///     Expression::Integer(20),
    /// ));
    ///
    /// assert_eq!(path.step_count(), 1);
    /// ```
    pub fn step_count(&self) -> usize {
        self.steps.len()
    }

    /// Check if the path is empty (no operations applied).
    ///
    /// Returns `true` if no steps have been added to the path yet.
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::{ResolutionPath, ResolutionStep, Operation};
    /// use thales::ast::Expression;
    ///
    /// let mut path = ResolutionPath::new(Expression::Integer(100));
    /// assert!(path.is_empty());
    ///
    /// path.add_step(ResolutionStep::new(
    ///     Operation::Simplify,
    ///     "Simplify".to_string(),
    ///     Expression::Integer(100),
    /// ));
    ///
    /// assert!(!path.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.steps.is_empty()
    }

    /// Generate human-readable explanation of the solution path.
    ///
    /// This method produces a formatted text description of all steps taken
    /// to solve the equation. Currently returns a summary of step count;
    /// full implementation will include detailed step-by-step explanations.
    ///
    /// # Future Implementation
    ///
    /// - Format each step with LaTeX or plain text
    /// - Include reasoning for each operation
    /// - Support different verbosity levels
    /// - Provide slide rule-specific hints
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::ResolutionPath;
    /// use thales::ast::Expression;
    ///
    /// let path = ResolutionPath::new(Expression::Integer(7));
    /// let explanation = path.explain();
    /// assert!(explanation.contains("0 steps"));
    /// ```
    pub fn explain(&self) -> String {
        // TODO: Implement explanation generation
        // TODO: Format each step with LaTeX or plain text
        // TODO: Include reasoning for each operation
        format!("Solution path with {} steps", self.steps.len())
    }

    /// Convert the resolution path to a human-readable text format.
    ///
    /// Generates a formatted text representation of the solution path,
    /// with detail level controlled by the verbosity parameter.
    ///
    /// # Arguments
    ///
    /// * `verbosity` - Level of detail to include in the output
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::{ResolutionPath, ResolutionStep, Operation, Verbosity};
    /// use thales::ast::Expression;
    ///
    /// let mut path = ResolutionPath::new(Expression::Integer(10));
    /// path.add_step(ResolutionStep::new(
    ///     Operation::SubtractBothSides(Expression::Integer(3)),
    ///     "Subtract 3 from both sides".to_string(),
    ///     Expression::Integer(7),
    /// ));
    /// path.set_result(Expression::Integer(7));
    ///
    /// let text = path.to_text(Verbosity::Standard);
    /// assert!(text.contains("Step 1"));
    /// assert!(text.contains("Subtract"));
    /// ```
    pub fn to_text(&self, verbosity: Verbosity) -> String {
        let mut output = String::new();

        match verbosity {
            Verbosity::Minimal => {
                // Just initial, key operations, and result
                output.push_str(&format!("Start: {:?}\n", self.initial));
                for (i, step) in self.steps.iter().enumerate() {
                    if step.operation.is_key_operation() {
                        output.push_str(&format!(
                            "Step {}: {}\n",
                            i + 1,
                            step.operation.describe()
                        ));
                    }
                }
                output.push_str(&format!("Result: {:?}\n", self.result));
            }
            Verbosity::Standard => {
                // All steps with operation and result
                output.push_str(&format!("Initial: {:?}\n\n", self.initial));
                for (i, step) in self.steps.iter().enumerate() {
                    output.push_str(&format!("Step {}: {}\n", i + 1, step.operation.describe()));
                    output.push_str(&format!("  → {:?}\n\n", step.result));
                }
                output.push_str(&format!("Final result: {:?}\n", self.result));
            }
            Verbosity::Detailed => {
                // Full explanation including reasoning
                output.push_str(&format!("=== Solution Path ===\n\n"));
                output.push_str(&format!("Starting expression: {:?}\n\n", self.initial));
                for (i, step) in self.steps.iter().enumerate() {
                    output.push_str(&format!("--- Step {} ---\n", i + 1));
                    output.push_str(&format!("Operation: {}\n", step.operation.describe()));
                    output.push_str(&format!("Explanation: {}\n", step.explanation));
                    output.push_str(&format!("Result: {:?}\n\n", step.result));
                }
                output.push_str(&format!("=== Final Result ===\n"));
                output.push_str(&format!("{:?}\n", self.result));
            }
        }

        output
    }

    /// Convert the resolution path to LaTeX format.
    ///
    /// Generates a LaTeX representation of the solution path, suitable
    /// for rendering in documents, educational materials, or web applications.
    ///
    /// # Arguments
    ///
    /// * `verbosity` - Level of detail to include in the output
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::{ResolutionPath, ResolutionStep, Operation, Verbosity};
    /// use thales::ast::Expression;
    ///
    /// let mut path = ResolutionPath::new(Expression::Integer(10));
    /// path.add_step(ResolutionStep::new(
    ///     Operation::DivideBothSides(Expression::Integer(2)),
    ///     "Divide by 2".to_string(),
    ///     Expression::Integer(5),
    /// ));
    /// path.set_result(Expression::Integer(5));
    ///
    /// let latex = path.to_latex(Verbosity::Standard);
    /// assert!(latex.contains("\\begin{align*}"));
    /// ```
    pub fn to_latex(&self, verbosity: Verbosity) -> String {
        let mut output = String::new();

        output.push_str("\\begin{align*}\n");

        match verbosity {
            Verbosity::Minimal => {
                output.push_str(&format!("  & {} \\\\\n", self.initial.to_latex()));
                // Show only key steps
                for step in &self.steps {
                    if step.operation.is_key_operation() {
                        output.push_str(&format!(
                            "  &\\quad \\text{{{}}} \\\\\n",
                            step.operation.describe_latex()
                        ));
                        output.push_str(&format!("  &= {} \\\\\n", step.result.to_latex()));
                    }
                }
            }
            Verbosity::Standard => {
                output.push_str(&format!("  & {} \\\\\n", self.initial.to_latex()));
                for step in &self.steps {
                    output.push_str(&format!(
                        "  &\\quad \\text{{{}}} \\\\\n",
                        step.operation.describe_latex()
                    ));
                    output.push_str(&format!("  &= {} \\\\\n", step.result.to_latex()));
                }
            }
            Verbosity::Detailed => {
                output.push_str(&format!(
                    "  & \\text{{Initial: }} {} \\\\\n",
                    self.initial.to_latex()
                ));
                for (i, step) in self.steps.iter().enumerate() {
                    output.push_str(&format!(
                        "  &\\quad \\text{{Step {}: {}}} \\\\\n",
                        i + 1,
                        step.operation.describe_latex()
                    ));
                    output.push_str(&format!(
                        "  &\\quad \\text{{({}}})\\\\\n",
                        escape_latex_text(&step.explanation)
                    ));
                    output.push_str(&format!("  &= {} \\\\\n", step.result.to_latex()));
                }
            }
        }

        output.push_str("\\end{align*}\n");
        output
    }

    /// Convert the resolution path to JSON format.
    ///
    /// Generates a JSON representation of the complete solution path,
    /// including all steps, explanations, and metadata. Useful for
    /// API responses, storage, or programmatic manipulation.
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::{ResolutionPath, ResolutionStep, Operation};
    /// use thales::ast::Expression;
    ///
    /// let mut path = ResolutionPath::new(Expression::Integer(10));
    /// path.add_step(ResolutionStep::new(
    ///     Operation::Simplify,
    ///     "Combine terms".to_string(),
    ///     Expression::Integer(10),
    /// ));
    /// path.set_result(Expression::Integer(10));
    ///
    /// let json = path.to_json();
    /// assert!(json["steps"].is_array());
    /// assert_eq!(json["step_count"], 1);
    /// ```
    pub fn to_json(&self) -> JsonValue {
        let steps: Vec<JsonValue> = self
            .steps
            .iter()
            .enumerate()
            .map(|(i, step)| {
                json!({
                    "step_number": i + 1,
                    "operation": step.operation.describe(),
                    "operation_category": step.operation.category(),
                    "explanation": step.explanation,
                    "result": format!("{:?}", step.result),
                    "result_latex": step.result.to_latex(),
                })
            })
            .collect();

        let stats = self.statistics();

        json!({
            "initial": format!("{:?}", self.initial),
            "initial_latex": self.initial.to_latex(),
            "steps": steps,
            "result": format!("{:?}", self.result),
            "result_latex": self.result.to_latex(),
            "step_count": self.steps.len(),
            "statistics": {
                "total_steps": stats.total_steps,
                "unique_operations": stats.unique_operations,
                "uses_advanced_methods": stats.uses_advanced_methods,
                "uses_calculus": stats.uses_calculus,
                "uses_matrix_operations": stats.uses_matrix_operations,
                "operation_counts": {
                    "both_sides": stats.operation_counts.both_sides,
                    "transformations": stats.operation_counts.transformations,
                    "variable_ops": stats.operation_counts.variable_ops,
                    "identities": stats.operation_counts.identities,
                    "advanced": stats.operation_counts.advanced,
                    "calculus": stats.operation_counts.calculus,
                    "matrix": stats.operation_counts.matrix,
                    "custom": stats.operation_counts.custom,
                }
            }
        })
    }

    /// Calculate statistics about the resolution path.
    ///
    /// Returns aggregate information about the solution process, including
    /// operation counts by category and flags for advanced methods.
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::{ResolutionPath, ResolutionStep, Operation};
    /// use thales::ast::Expression;
    ///
    /// let mut path = ResolutionPath::new(Expression::Integer(20));
    /// path.add_step(ResolutionStep::new(
    ///     Operation::Simplify,
    ///     "Simplify".to_string(),
    ///     Expression::Integer(20),
    /// ));
    /// path.add_step(ResolutionStep::new(
    ///     Operation::QuadraticFormula,
    ///     "Apply quadratic formula".to_string(),
    ///     Expression::Integer(5),
    /// ));
    ///
    /// let stats = path.statistics();
    /// assert_eq!(stats.total_steps, 2);
    /// assert!(stats.uses_advanced_methods);
    /// assert_eq!(stats.operation_counts.transformations, 1);
    /// assert_eq!(stats.operation_counts.advanced, 1);
    /// ```
    pub fn statistics(&self) -> PathStatistics {
        let mut counts = OperationCounts::default();
        let mut unique_ops: std::collections::HashSet<String> = std::collections::HashSet::new();
        let mut uses_advanced = false;
        let mut uses_calculus = false;
        let mut uses_matrix = false;

        for step in &self.steps {
            let category = step.operation.category();
            unique_ops.insert(step.operation.describe());

            match category.as_str() {
                "both_sides" => counts.both_sides += 1,
                "transformation" => counts.transformations += 1,
                "variable" => counts.variable_ops += 1,
                "identity" => counts.identities += 1,
                "advanced" => {
                    counts.advanced += 1;
                    uses_advanced = true;
                }
                "calculus" => {
                    counts.calculus += 1;
                    uses_calculus = true;
                }
                "matrix" => {
                    counts.matrix += 1;
                    uses_matrix = true;
                }
                "custom" => counts.custom += 1,
                _ => {}
            }
        }

        PathStatistics {
            total_steps: self.steps.len(),
            operation_counts: counts,
            unique_operations: unique_ops.len(),
            uses_advanced_methods: uses_advanced,
            uses_calculus,
            uses_matrix_operations: uses_matrix,
        }
    }
}

/// Escape special LaTeX characters in text.
fn escape_latex_text(text: &str) -> String {
    text.replace('\\', "\\textbackslash{}")
        .replace('{', "\\{")
        .replace('}', "\\}")
        .replace('$', "\\$")
        .replace('%', "\\%")
        .replace('&', "\\&")
        .replace('#', "\\#")
        .replace('_', "\\_")
        .replace('^', "\\^{}")
        .replace('~', "\\~{}")
}

/// A single step in the solution process.
///
/// Each `ResolutionStep` represents one algebraic operation applied during equation
/// solving. It captures what was done, why it was done, and what the result was.
///
/// # Structure
///
/// - `operation`: The type of algebraic manipulation (e.g., add to both sides, simplify)
/// - `explanation`: Human-readable reasoning for why this step was chosen
/// - `result`: The expression state after applying the operation
///
/// # Example
///
/// ```rust
/// use thales::resolution_path::{ResolutionStep, Operation};
/// use thales::ast::Expression;
///
/// // Step: Divide both sides by 2
/// let step = ResolutionStep::new(
///     Operation::DivideBothSides(Expression::Integer(2)),
///     "Divide both sides by 2 to isolate x".to_string(),
///     Expression::Integer(5),
/// );
///
/// assert_eq!(step.operation.describe(), "Divide both sides by Integer(2)");
/// assert_eq!(step.result, Expression::Integer(5));
/// ```
///
/// # Educational Context
///
/// Steps can be revealed progressively to provide hints:
///
/// ```rust
/// use thales::resolution_path::{ResolutionStep, Operation};
/// use thales::ast::Expression;
///
/// let step = ResolutionStep::new(
///     Operation::Simplify,
///     "Combine like terms: 3x + 2x = 5x".to_string(),
///     Expression::Integer(5),
/// );
///
/// // Hint level 1: Operation type only
/// println!("Try: {}", step.operation.describe());
///
/// // Hint level 2: Full explanation
/// println!("Explanation: {}", step.explanation);
///
/// // Hint level 3: Show result
/// println!("Result: {:?}", step.result);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct ResolutionStep {
    /// The operation performed in this step.
    ///
    /// Describes the algebraic manipulation applied (e.g., adding to both sides,
    /// factoring, simplifying). See [`Operation`] for all available operation types.
    pub operation: Operation,

    /// Description of why this step was taken.
    ///
    /// Provides the educational reasoning behind the operation. For example:
    /// "Subtract 3 from both sides to isolate the term with x" or
    /// "Factor out the common term to simplify".
    pub explanation: String,

    /// Expression state after this step.
    ///
    /// The resulting expression after applying the operation. This becomes
    /// the input for the next step in the solution path.
    pub result: Expression,
}

impl ResolutionStep {
    /// Create a new resolution step.
    ///
    /// Constructs a step with the specified operation, explanation, and result.
    ///
    /// # Arguments
    ///
    /// * `operation` - The algebraic operation to perform
    /// * `explanation` - Human-readable reason for this step
    /// * `result` - Expression state after the operation
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::{ResolutionStep, Operation};
    /// use thales::ast::Expression;
    ///
    /// let step = ResolutionStep::new(
    ///     Operation::AddBothSides(Expression::Integer(5)),
    ///     "Add 5 to both sides to eliminate the negative term".to_string(),
    ///     Expression::Integer(10),
    /// );
    ///
    /// assert_eq!(step.result, Expression::Integer(10));
    /// ```
    pub fn new(operation: Operation, explanation: String, result: Expression) -> Self {
        Self {
            operation,
            explanation,
            result,
        }
    }
}

/// Operations that can be performed during equation solving.
///
/// This enum represents all types of algebraic manipulations that can be applied
/// when solving equations. Each variant captures a specific mathematical operation
/// along with any necessary parameters.
///
/// # Operation Categories
///
/// ## Both-Sides Operations
/// Operations that maintain equation equality by applying the same transformation
/// to both sides: [`AddBothSides`](Operation::AddBothSides),
/// [`SubtractBothSides`](Operation::SubtractBothSides),
/// [`MultiplyBothSides`](Operation::MultiplyBothSides),
/// [`DivideBothSides`](Operation::DivideBothSides),
/// [`PowerBothSides`](Operation::PowerBothSides),
/// [`RootBothSides`](Operation::RootBothSides),
/// [`ApplyFunction`](Operation::ApplyFunction).
///
/// ## Expression Transformations
/// Operations that restructure expressions:
/// [`Simplify`](Operation::Simplify),
/// [`Expand`](Operation::Expand),
/// [`Factor`](Operation::Factor),
/// [`CombineFractions`](Operation::CombineFractions),
/// [`Cancel`](Operation::Cancel).
///
/// ## Variable Manipulation
/// Operations for working with variables:
/// [`Substitute`](Operation::Substitute),
/// [`Isolate`](Operation::Isolate),
/// [`MoveTerm`](Operation::MoveTerm).
///
/// ## Identity Applications
/// Operations that apply mathematical identities:
/// [`ApplyIdentity`](Operation::ApplyIdentity),
/// [`ApplyTrigIdentity`](Operation::ApplyTrigIdentity),
/// [`ApplyLogProperty`](Operation::ApplyLogProperty).
///
/// ## Advanced Methods
/// Specialized solving techniques:
/// [`QuadraticFormula`](Operation::QuadraticFormula),
/// [`CompleteSquare`](Operation::CompleteSquare),
/// [`NumericalApproximation`](Operation::NumericalApproximation).
///
/// # Example
///
/// ```rust
/// use thales::resolution_path::Operation;
/// use thales::ast::{Expression, Variable};
///
/// // Both-sides operation
/// let op1 = Operation::AddBothSides(Expression::Integer(5));
/// assert_eq!(op1.describe(), "Add Integer(5) to both sides");
///
/// // Simplification
/// let op2 = Operation::Simplify;
/// assert_eq!(op2.describe(), "Simplify expression");
///
/// // Variable substitution
/// let x = Variable::new("x");
/// let op3 = Operation::Substitute {
///     variable: x,
///     value: Expression::Integer(10),
/// };
/// assert!(op3.describe().contains("Substitute"));
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum Operation {
    // ===== Both-Sides Operations =====
    /// Add the same expression to both sides of the equation.
    ///
    /// Used to eliminate negative terms or move constants across the equation.
    ///
    /// # Example
    ///
    /// Solving `x - 3 = 7`:
    /// - Apply `AddBothSides(3)` to get `x = 10`
    AddBothSides(Expression),

    /// Subtract the same expression from both sides of the equation.
    ///
    /// Used to eliminate positive terms or move constants across the equation.
    ///
    /// # Example
    ///
    /// Solving `x + 5 = 12`:
    /// - Apply `SubtractBothSides(5)` to get `x = 7`
    SubtractBothSides(Expression),

    /// Multiply both sides of the equation by the same expression.
    ///
    /// Used to eliminate fractions or isolate variables with fractional coefficients.
    ///
    /// # Example
    ///
    /// Solving `x/2 = 6`:
    /// - Apply `MultiplyBothSides(2)` to get `x = 12`
    MultiplyBothSides(Expression),

    /// Divide both sides of the equation by the same expression.
    ///
    /// Used to isolate variables with integer coefficients.
    ///
    /// # Example
    ///
    /// Solving `3x = 15`:
    /// - Apply `DivideBothSides(3)` to get `x = 5`
    DivideBothSides(Expression),

    /// Raise both sides of the equation to the specified power.
    ///
    /// Used to eliminate roots or solve radical equations.
    ///
    /// # Example
    ///
    /// Solving `√x = 4`:
    /// - Apply `PowerBothSides(2)` to get `x = 16`
    PowerBothSides(Expression),

    /// Take the specified root of both sides.
    ///
    /// Used to solve equations with powers.
    ///
    /// # Example
    ///
    /// Solving `x² = 25`:
    /// - Apply `RootBothSides(2)` to get `x = ±5`
    RootBothSides(Expression),

    /// Apply a named function to both sides.
    ///
    /// Used for inverse operations like taking logarithms, applying trig functions, etc.
    ///
    /// # Example
    ///
    /// Solving `e^x = 10`:
    /// - Apply `ApplyFunction("ln")` to get `x = ln(10)`
    ApplyFunction(String),

    // ===== Expression Transformations =====
    /// Simplify the expression by combining like terms, reducing fractions, etc.
    ///
    /// # Example
    ///
    /// Transform `3x + 2x` into `5x`
    Simplify,

    /// Expand the expression by distributing multiplication over addition.
    ///
    /// # Example
    ///
    /// Transform `(x + 2)(x - 3)` into `x² - x - 6`
    Expand,

    /// Factor the expression into a product of simpler expressions.
    ///
    /// # Example
    ///
    /// Transform `x² - 5x + 6` into `(x - 2)(x - 3)`
    Factor,

    /// Combine multiple fractions into a single fraction.
    ///
    /// # Example
    ///
    /// Transform `1/x + 2/y` into `(y + 2x)/(xy)`
    CombineFractions,

    /// Cancel common factors from numerator and denominator.
    ///
    /// # Example
    ///
    /// Transform `(2x)/(4x)` into `1/2`
    Cancel,

    // ===== Variable Manipulation =====
    /// Substitute a variable with a specific value or expression.
    ///
    /// # Example
    ///
    /// In equation `2x + y = 10`, substitute `y = 3` to get `2x + 3 = 10`
    Substitute {
        /// The variable being replaced
        variable: Variable,
        /// The value or expression to substitute
        value: Expression,
    },

    /// Isolate the specified variable on one side of the equation.
    ///
    /// # Example
    ///
    /// Transform `2x + 3y = 12` to `x = (12 - 3y)/2` (isolating x)
    Isolate(Variable),

    /// Move a term from one side of the equation to the other.
    ///
    /// Equivalent to adding or subtracting the term from both sides.
    ///
    /// # Example
    ///
    /// Transform `x + 5 = 12` to `x = 12 - 5`
    MoveTerm(Expression),

    // ===== Identity Applications =====
    /// Apply a named algebraic identity.
    ///
    /// # Example
    ///
    /// Apply "difference of squares": `a² - b² = (a + b)(a - b)`
    ApplyIdentity(String),

    /// Apply a named trigonometric identity.
    ///
    /// # Example
    ///
    /// Apply "Pythagorean identity": `sin²θ + cos²θ = 1`
    ApplyTrigIdentity(String),

    /// Apply a named logarithm property.
    ///
    /// # Example
    ///
    /// Apply "product rule": `log(ab) = log(a) + log(b)`
    ApplyLogProperty(String),

    // ===== Advanced Methods =====
    /// Solve using the quadratic formula: x = (-b ± √(b² - 4ac)) / 2a
    ///
    /// Used for equations in the form `ax² + bx + c = 0`
    QuadraticFormula,

    /// Solve by completing the square.
    ///
    /// Transform `x² + bx + c` into `(x + p)² + q` form
    CompleteSquare,

    /// Use numerical methods to approximate the solution.
    ///
    /// Applied when symbolic methods fail or exact solutions are impractical
    NumericalApproximation,

    // ===== Calculus Operations =====
    /// Differentiate an expression with respect to a variable.
    ///
    /// # Example
    ///
    /// Differentiate `x^3 + 2x` with respect to x: `3x^2 + 2`
    Differentiate {
        /// The variable to differentiate with respect to
        variable: Variable,
        /// The differentiation rule applied (e.g., "power rule", "chain rule")
        rule: String,
    },

    /// Integrate an expression with respect to a variable.
    ///
    /// # Example
    ///
    /// Integrate `2x` with respect to x: `x^2 + C`
    Integrate {
        /// The variable of integration
        variable: Variable,
        /// The integration technique used
        technique: String,
    },

    /// Evaluate a limit.
    ///
    /// # Example
    ///
    /// Evaluate `lim_{x->0} sin(x)/x = 1`
    EvaluateLimit {
        /// The variable approaching a value
        variable: Variable,
        /// The value being approached
        approaches: Expression,
        /// The method used (e.g., "direct substitution", "L'Hôpital's rule")
        method: String,
    },

    /// Apply integration by parts: ∫u dv = uv - ∫v du
    IntegrationByParts {
        /// The function chosen as u
        u: Expression,
        /// The function chosen as dv
        dv: Expression,
    },

    /// Apply u-substitution for integration.
    USubstitution {
        /// The substitution u = g(x)
        substitution: Expression,
    },

    /// Solve an ODE.
    SolveODE {
        /// The method used (e.g., "separation of variables", "integrating factor")
        method: String,
    },

    // ===== Matrix Operations =====
    /// Perform a matrix operation.
    MatrixOperation {
        /// The type of operation (e.g., "row reduction", "transpose", "inverse")
        operation: String,
    },

    /// Apply Gaussian elimination.
    GaussianElimination,

    /// Compute determinant using a specific method.
    ComputeDeterminant {
        /// The method used (e.g., "cofactor expansion", "LU decomposition")
        method: String,
    },

    /// Apply approximation with error bounds.
    ///
    /// Replaces an expression with an approximation (e.g., small angle approximation).
    ApproximationSubstitution {
        /// The original exact expression
        original: Expression,
        /// The approximation expression
        approximation: Expression,
        /// Upper bound on approximation error
        error_bound: f64,
    },

    /// Custom operation with a free-form description.
    ///
    /// Use this for operations not covered by the other variants
    Custom(String),
}

impl Operation {
    /// Get a human-readable description of this operation.
    ///
    /// Returns a string describing what this operation does, suitable for display
    /// in educational contexts, hints, or step-by-step explanations.
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::Operation;
    /// use thales::ast::{Expression, Variable};
    ///
    /// let op = Operation::DivideBothSides(Expression::Integer(3));
    /// assert_eq!(op.describe(), "Divide both sides by Integer(3)");
    ///
    /// let op2 = Operation::Simplify;
    /// assert_eq!(op2.describe(), "Simplify expression");
    ///
    /// let x = Variable::new("x");
    /// let op3 = Operation::Isolate(x);
    /// assert_eq!(op3.describe(), "Isolate x");
    /// ```
    ///
    /// # Usage in Educational Applications
    ///
    /// ```rust
    /// use thales::resolution_path::{ResolutionStep, Operation};
    /// use thales::ast::Expression;
    ///
    /// let step = ResolutionStep::new(
    ///     Operation::AddBothSides(Expression::Integer(7)),
    ///     "Add 7 to eliminate the negative term".to_string(),
    ///     Expression::Integer(14),
    /// );
    ///
    /// // Show just the operation type to student
    /// println!("Hint: {}", step.operation.describe());
    /// // Output: "Add Integer(7) to both sides"
    /// ```
    pub fn describe(&self) -> String {
        match self {
            Operation::AddBothSides(expr) => format!("Add {:?} to both sides", expr),
            Operation::SubtractBothSides(expr) => format!("Subtract {:?} from both sides", expr),
            Operation::MultiplyBothSides(expr) => format!("Multiply both sides by {:?}", expr),
            Operation::DivideBothSides(expr) => format!("Divide both sides by {:?}", expr),
            Operation::PowerBothSides(expr) => format!("Raise both sides to power {:?}", expr),
            Operation::RootBothSides(expr) => format!("Take {:?} root of both sides", expr),
            Operation::ApplyFunction(func) => format!("Apply {} to both sides", func),
            Operation::Simplify => "Simplify expression".to_string(),
            Operation::Expand => "Expand expression".to_string(),
            Operation::Factor => "Factor expression".to_string(),
            Operation::CombineFractions => "Combine fractions".to_string(),
            Operation::Cancel => "Cancel common factors".to_string(),
            Operation::Substitute { variable, value } => {
                format!("Substitute {} = {:?}", variable, value)
            }
            Operation::Isolate(var) => format!("Isolate {}", var),
            Operation::MoveTerm(expr) => format!("Move {:?} to other side", expr),
            Operation::ApplyIdentity(name) => format!("Apply identity: {}", name),
            Operation::ApplyTrigIdentity(name) => format!("Apply trig identity: {}", name),
            Operation::ApplyLogProperty(name) => format!("Apply log property: {}", name),
            Operation::QuadraticFormula => "Apply quadratic formula".to_string(),
            Operation::CompleteSquare => "Complete the square".to_string(),
            Operation::NumericalApproximation => "Use numerical approximation".to_string(),
            // Calculus operations
            Operation::Differentiate { variable, rule } => {
                format!("Differentiate with respect to {} ({})", variable, rule)
            }
            Operation::Integrate {
                variable,
                technique,
            } => {
                format!("Integrate with respect to {} ({})", variable, technique)
            }
            Operation::EvaluateLimit {
                variable,
                approaches,
                method,
            } => {
                format!(
                    "Evaluate limit as {} → {:?} ({})",
                    variable, approaches, method
                )
            }
            Operation::IntegrationByParts { u, dv } => {
                format!("Integration by parts: u = {:?}, dv = {:?}", u, dv)
            }
            Operation::USubstitution { substitution } => {
                format!("U-substitution: u = {:?}", substitution)
            }
            Operation::SolveODE { method } => format!("Solve ODE ({})", method),
            // Matrix operations
            Operation::MatrixOperation { operation } => {
                format!("Matrix operation: {}", operation)
            }
            Operation::GaussianElimination => "Apply Gaussian elimination".to_string(),
            Operation::ComputeDeterminant { method } => {
                format!("Compute determinant ({})", method)
            }
            Operation::ApproximationSubstitution {
                original,
                approximation,
                error_bound,
            } => {
                format!(
                    "Approximate {:?} ≈ {:?} (error bound: {:.2e})",
                    original, approximation, error_bound
                )
            }
            Operation::Custom(desc) => desc.clone(),
        }
    }

    /// Get a LaTeX-friendly description of this operation.
    ///
    /// Similar to `describe()` but with proper escaping for LaTeX text mode.
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::Operation;
    /// use thales::ast::Expression;
    ///
    /// let op = Operation::QuadraticFormula;
    /// assert_eq!(op.describe_latex(), "Apply quadratic formula");
    /// ```
    pub fn describe_latex(&self) -> String {
        // For now, reuse describe() - most descriptions are already LaTeX-safe
        // Special characters in expressions would need escaping
        match self {
            Operation::AddBothSides(expr) => {
                format!("Add {} to both sides", expr.to_latex())
            }
            Operation::SubtractBothSides(expr) => {
                format!("Subtract {} from both sides", expr.to_latex())
            }
            Operation::MultiplyBothSides(expr) => {
                format!("Multiply both sides by {}", expr.to_latex())
            }
            Operation::DivideBothSides(expr) => {
                format!("Divide both sides by {}", expr.to_latex())
            }
            Operation::PowerBothSides(expr) => {
                format!("Raise both sides to power {}", expr.to_latex())
            }
            Operation::RootBothSides(expr) => {
                format!("Take {} root of both sides", expr.to_latex())
            }
            Operation::Substitute { variable, value } => {
                format!("Substitute {} = {}", variable, value.to_latex())
            }
            Operation::MoveTerm(expr) => {
                format!("Move {} to other side", expr.to_latex())
            }
            Operation::IntegrationByParts { u, dv } => {
                format!(
                    "Integration by parts: u = {}, dv = {}",
                    u.to_latex(),
                    dv.to_latex()
                )
            }
            Operation::USubstitution { substitution } => {
                format!("U-substitution: u = {}", substitution.to_latex())
            }
            Operation::EvaluateLimit {
                variable,
                approaches,
                method,
            } => {
                format!(
                    "Evaluate limit as {} \\to {} ({})",
                    variable,
                    approaches.to_latex(),
                    method
                )
            }
            _ => self.describe(),
        }
    }

    /// Get the category of this operation for statistics.
    ///
    /// Returns a string identifier for the operation category.
    ///
    /// # Categories
    ///
    /// - `"both_sides"`: Operations applied to both sides of equation
    /// - `"transformation"`: Expression transformations (simplify, expand, etc.)
    /// - `"variable"`: Variable manipulations (substitute, isolate)
    /// - `"identity"`: Identity applications (algebraic, trig, log)
    /// - `"advanced"`: Advanced methods (quadratic formula, etc.)
    /// - `"calculus"`: Calculus operations (differentiate, integrate, etc.)
    /// - `"matrix"`: Matrix operations
    /// - `"custom"`: Custom operations
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::Operation;
    /// use thales::ast::Expression;
    ///
    /// let op = Operation::Simplify;
    /// assert_eq!(op.category(), "transformation");
    ///
    /// let op2 = Operation::QuadraticFormula;
    /// assert_eq!(op2.category(), "advanced");
    /// ```
    pub fn category(&self) -> String {
        match self {
            // Both-sides operations
            Operation::AddBothSides(_)
            | Operation::SubtractBothSides(_)
            | Operation::MultiplyBothSides(_)
            | Operation::DivideBothSides(_)
            | Operation::PowerBothSides(_)
            | Operation::RootBothSides(_)
            | Operation::ApplyFunction(_) => "both_sides".to_string(),

            // Transformations
            Operation::Simplify
            | Operation::Expand
            | Operation::Factor
            | Operation::CombineFractions
            | Operation::Cancel => "transformation".to_string(),

            // Variable operations
            Operation::Substitute { .. } | Operation::Isolate(_) | Operation::MoveTerm(_) => {
                "variable".to_string()
            }

            // Identity applications
            Operation::ApplyIdentity(_)
            | Operation::ApplyTrigIdentity(_)
            | Operation::ApplyLogProperty(_) => "identity".to_string(),

            // Advanced methods
            Operation::QuadraticFormula
            | Operation::CompleteSquare
            | Operation::NumericalApproximation => "advanced".to_string(),

            // Calculus operations
            Operation::Differentiate { .. }
            | Operation::Integrate { .. }
            | Operation::EvaluateLimit { .. }
            | Operation::IntegrationByParts { .. }
            | Operation::USubstitution { .. }
            | Operation::SolveODE { .. } => "calculus".to_string(),

            // Matrix operations
            Operation::MatrixOperation { .. }
            | Operation::GaussianElimination
            | Operation::ComputeDeterminant { .. } => "matrix".to_string(),

            // Approximation
            Operation::ApproximationSubstitution { .. } => "approximation".to_string(),

            // Custom
            Operation::Custom(_) => "custom".to_string(),
        }
    }

    /// Check if this operation is a "key" operation for minimal verbosity.
    ///
    /// Key operations are major transformations that significantly change
    /// the equation state. Simplification and other minor adjustments
    /// are typically not considered key operations.
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::Operation;
    /// use thales::ast::Expression;
    ///
    /// assert!(!Operation::Simplify.is_key_operation());
    /// assert!(Operation::QuadraticFormula.is_key_operation());
    /// assert!(Operation::DivideBothSides(Expression::Integer(2)).is_key_operation());
    /// ```
    pub fn is_key_operation(&self) -> bool {
        match self {
            // Minor operations - not key
            Operation::Simplify | Operation::Cancel => false,

            // All other operations are considered key
            _ => true,
        }
    }
}

/// Builder for constructing resolution paths with a fluent API.
///
/// `ResolutionPathBuilder` provides a convenient way to construct resolution paths
/// using method chaining. It automatically tracks intermediate results and provides
/// specialized methods for common operations.
///
/// # Fluent API Pattern
///
/// The builder uses the fluent pattern where each method returns `self`, allowing
/// you to chain multiple operations together. Call [`finish()`](ResolutionPathBuilder::finish)
/// at the end to get the final [`ResolutionPath`].
///
/// # Example: Basic Usage
///
/// ```rust
/// use thales::resolution_path::{ResolutionPathBuilder, Operation};
/// use thales::ast::{Expression, Variable};
///
/// // Solve: 2x + 3 = 11
/// let path = ResolutionPathBuilder::new(Expression::Integer(11))
///     .step(
///         Operation::SubtractBothSides(Expression::Integer(3)),
///         "Subtract 3 from both sides".to_string(),
///         Expression::Integer(8),  // 11 - 3 = 8
///     )
///     .step(
///         Operation::DivideBothSides(Expression::Integer(2)),
///         "Divide both sides by 2".to_string(),
///         Expression::Integer(4),  // 8 / 2 = 4
///     )
///     .finish(Expression::Integer(4));
///
/// assert_eq!(path.step_count(), 2);
/// ```
///
/// # Example: Using Specialized Methods
///
/// ```rust
/// use thales::resolution_path::ResolutionPathBuilder;
/// use thales::ast::{Expression, Variable};
///
/// let x = Variable::new("x");
///
/// let path = ResolutionPathBuilder::new(Expression::Integer(20))
///     .simplify("Combine like terms".to_string(), Expression::Integer(20))
///     .isolate(x, "Move x to left side".to_string(), Expression::Integer(10))
///     .finish(Expression::Integer(10));
///
/// assert_eq!(path.step_count(), 2);
/// ```
///
/// # Example: Complex Multi-Step Solution
///
/// ```rust
/// use thales::resolution_path::{ResolutionPathBuilder, Operation};
/// use thales::ast::{Expression, Variable};
///
/// // Solve: x² = 16
/// let x = Variable::new("x");
///
/// let path = ResolutionPathBuilder::new(Expression::Integer(16))
///     .step(
///         Operation::RootBothSides(Expression::Integer(2)),
///         "Take square root of both sides".to_string(),
///         Expression::Integer(4),
///     )
///     .step(
///         Operation::Custom("Consider both positive and negative roots".to_string()),
///         "Solutions are x = 4 and x = -4".to_string(),
///         Expression::Integer(4),
///     )
///     .finish(Expression::Integer(4));
///
/// assert_eq!(path.step_count(), 2);
/// ```
#[derive(Clone)]
pub struct ResolutionPathBuilder {
    /// The resolution path being constructed
    path: ResolutionPath,
}

impl ResolutionPathBuilder {
    /// Create a new builder starting from an initial expression.
    ///
    /// The builder begins with an empty step list. Add steps using
    /// [`step()`](ResolutionPathBuilder::step) or specialized methods like
    /// [`simplify()`](ResolutionPathBuilder::simplify) and
    /// [`isolate()`](ResolutionPathBuilder::isolate).
    ///
    /// # Arguments
    ///
    /// * `initial` - The starting expression (typically one side of an equation)
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::ResolutionPathBuilder;
    /// use thales::ast::Expression;
    ///
    /// let builder = ResolutionPathBuilder::new(Expression::Integer(42));
    /// // Add steps and finish...
    /// ```
    pub fn new(initial: Expression) -> Self {
        Self {
            path: ResolutionPath::new(initial),
        }
    }

    /// Add a step with automatic result tracking.
    ///
    /// This is the general-purpose method for adding any operation to the path.
    /// For common operations, consider using the specialized methods like
    /// [`simplify()`](ResolutionPathBuilder::simplify) or
    /// [`isolate()`](ResolutionPathBuilder::isolate).
    ///
    /// # Arguments
    ///
    /// * `operation` - The operation being performed
    /// * `explanation` - Human-readable explanation of why this step is necessary
    /// * `result` - The expression state after applying the operation
    ///
    /// # Returns
    ///
    /// Returns `self` for method chaining.
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::{ResolutionPathBuilder, Operation};
    /// use thales::ast::Expression;
    ///
    /// let path = ResolutionPathBuilder::new(Expression::Integer(15))
    ///     .step(
    ///         Operation::DivideBothSides(Expression::Integer(3)),
    ///         "Divide by 3 to solve for x".to_string(),
    ///         Expression::Integer(5),
    ///     )
    ///     .finish(Expression::Integer(5));
    ///
    /// assert_eq!(path.step_count(), 1);
    /// ```
    pub fn step(mut self, operation: Operation, explanation: String, result: Expression) -> Self {
        self.path
            .add_step(ResolutionStep::new(operation, explanation, result));
        self
    }

    /// Add a simplification step.
    ///
    /// Convenience method for adding a [`Simplify`](Operation::Simplify) operation.
    /// Use this when combining like terms, reducing fractions, or performing
    /// other simplification operations.
    ///
    /// # Arguments
    ///
    /// * `explanation` - Description of what is being simplified
    /// * `result` - The simplified expression
    ///
    /// # Returns
    ///
    /// Returns `self` for method chaining.
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::ResolutionPathBuilder;
    /// use thales::ast::Expression;
    ///
    /// let path = ResolutionPathBuilder::new(Expression::Integer(12))
    ///     .simplify("Combine like terms".to_string(), Expression::Integer(12))
    ///     .finish(Expression::Integer(12));
    ///
    /// assert_eq!(path.steps[0].operation, thales::resolution_path::Operation::Simplify);
    /// ```
    pub fn simplify(self, explanation: String, result: Expression) -> Self {
        self.step(Operation::Simplify, explanation, result)
    }

    /// Add an isolation step.
    ///
    /// Convenience method for adding an [`Isolate`](Operation::Isolate) operation.
    /// Use this when isolating a variable on one side of the equation.
    ///
    /// # Arguments
    ///
    /// * `variable` - The variable being isolated
    /// * `explanation` - Description of the isolation process
    /// * `result` - The expression with the variable isolated
    ///
    /// # Returns
    ///
    /// Returns `self` for method chaining.
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::ResolutionPathBuilder;
    /// use thales::ast::{Expression, Variable};
    ///
    /// let x = Variable::new("x");
    ///
    /// let path = ResolutionPathBuilder::new(Expression::Integer(7))
    ///     .isolate(x, "Isolate x on the left side".to_string(), Expression::Integer(7))
    ///     .finish(Expression::Integer(7));
    ///
    /// assert_eq!(path.step_count(), 1);
    /// ```
    pub fn isolate(self, variable: Variable, explanation: String, result: Expression) -> Self {
        self.step(Operation::Isolate(variable), explanation, result)
    }

    /// Finalize the path with the final result.
    ///
    /// This method consumes the builder and returns the completed [`ResolutionPath`].
    /// Call this after adding all steps to get the final path object.
    ///
    /// # Arguments
    ///
    /// * `result` - The final solution expression
    ///
    /// # Returns
    ///
    /// The completed [`ResolutionPath`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use thales::resolution_path::{ResolutionPathBuilder, Operation};
    /// use thales::ast::Expression;
    ///
    /// let path = ResolutionPathBuilder::new(Expression::Integer(10))
    ///     .step(
    ///         Operation::Simplify,
    ///         "Simplify".to_string(),
    ///         Expression::Integer(10),
    ///     )
    ///     .finish(Expression::Integer(10));
    ///
    /// assert_eq!(path.result, Expression::Integer(10));
    /// assert_eq!(path.step_count(), 1);
    /// ```
    pub fn finish(mut self, result: Expression) -> ResolutionPath {
        self.path.set_result(result);
        self.path
    }
}

// TODO: Add validation that steps are mathematically sound
// TODO: Add ability to replay/verify steps
// TODO: Add support for branching paths (multiple solution methods)
// TODO: Add difficulty rating for each step
// TODO: Add hints generation from resolution path
// TODO: Add support for partial paths (incomplete solutions)

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

    #[test]
    fn test_verbosity_default() {
        let verbosity = Verbosity::default();
        assert_eq!(verbosity, Verbosity::Standard);
    }

    #[test]
    fn test_to_text_minimal() {
        let mut path = ResolutionPath::new(Expression::Integer(10));
        path.add_step(ResolutionStep::new(
            Operation::Simplify,
            "Simplify".to_string(),
            Expression::Integer(10),
        ));
        path.add_step(ResolutionStep::new(
            Operation::DivideBothSides(Expression::Integer(2)),
            "Divide by 2".to_string(),
            Expression::Integer(5),
        ));
        path.set_result(Expression::Integer(5));

        let text = path.to_text(Verbosity::Minimal);
        // Minimal should skip Simplify (not a key operation)
        assert!(text.contains("Start:"));
        assert!(text.contains("Result:"));
        assert!(text.contains("Divide"));
        // Should NOT contain the simplify step in minimal mode
        assert!(!text.contains("Simplify"));
    }

    #[test]
    fn test_to_text_standard() {
        let mut path = ResolutionPath::new(Expression::Integer(10));
        path.add_step(ResolutionStep::new(
            Operation::SubtractBothSides(Expression::Integer(3)),
            "Subtract 3".to_string(),
            Expression::Integer(7),
        ));
        path.set_result(Expression::Integer(7));

        let text = path.to_text(Verbosity::Standard);
        assert!(text.contains("Initial:"));
        assert!(text.contains("Step 1:"));
        assert!(text.contains("Subtract"));
        assert!(text.contains("Final result:"));
    }

    #[test]
    fn test_to_text_detailed() {
        let mut path = ResolutionPath::new(Expression::Integer(10));
        path.add_step(ResolutionStep::new(
            Operation::AddBothSides(Expression::Integer(5)),
            "Add 5 to isolate the term".to_string(),
            Expression::Integer(15),
        ));
        path.set_result(Expression::Integer(15));

        let text = path.to_text(Verbosity::Detailed);
        assert!(text.contains("=== Solution Path ==="));
        assert!(text.contains("Starting expression:"));
        assert!(text.contains("--- Step 1 ---"));
        assert!(text.contains("Operation:"));
        assert!(text.contains("Explanation:"));
        assert!(text.contains("Add 5 to isolate the term"));
        assert!(text.contains("=== Final Result ==="));
    }

    #[test]
    fn test_to_latex_standard() {
        let mut path = ResolutionPath::new(Expression::Integer(10));
        path.add_step(ResolutionStep::new(
            Operation::DivideBothSides(Expression::Integer(2)),
            "Divide by 2".to_string(),
            Expression::Integer(5),
        ));
        path.set_result(Expression::Integer(5));

        let latex = path.to_latex(Verbosity::Standard);
        assert!(latex.contains("\\begin{align*}"));
        assert!(latex.contains("\\end{align*}"));
        assert!(latex.contains("\\text{"));
    }

    #[test]
    fn test_to_json() {
        let mut path = ResolutionPath::new(Expression::Integer(20));
        path.add_step(ResolutionStep::new(
            Operation::Simplify,
            "Combine like terms".to_string(),
            Expression::Integer(20),
        ));
        path.add_step(ResolutionStep::new(
            Operation::QuadraticFormula,
            "Apply quadratic formula".to_string(),
            Expression::Integer(5),
        ));
        path.set_result(Expression::Integer(5));

        let json = path.to_json();
        assert!(json["steps"].is_array());
        assert_eq!(json["step_count"], 2);
        assert_eq!(json["statistics"]["total_steps"], 2);
        assert_eq!(json["statistics"]["uses_advanced_methods"], true);
        assert_eq!(json["statistics"]["operation_counts"]["transformations"], 1);
        assert_eq!(json["statistics"]["operation_counts"]["advanced"], 1);
    }

    #[test]
    fn test_statistics() {
        let mut path = ResolutionPath::new(Expression::Integer(100));

        // Add various operations
        path.add_step(ResolutionStep::new(
            Operation::AddBothSides(Expression::Integer(5)),
            "Add".to_string(),
            Expression::Integer(105),
        ));
        path.add_step(ResolutionStep::new(
            Operation::Simplify,
            "Simplify".to_string(),
            Expression::Integer(105),
        ));
        path.add_step(ResolutionStep::new(
            Operation::Factor,
            "Factor".to_string(),
            Expression::Integer(105),
        ));
        path.add_step(ResolutionStep::new(
            Operation::Isolate(Variable::new("x")),
            "Isolate x".to_string(),
            Expression::Integer(21),
        ));
        path.add_step(ResolutionStep::new(
            Operation::QuadraticFormula,
            "Apply quadratic formula".to_string(),
            Expression::Integer(7),
        ));

        let stats = path.statistics();

        assert_eq!(stats.total_steps, 5);
        assert_eq!(stats.operation_counts.both_sides, 1);
        assert_eq!(stats.operation_counts.transformations, 2); // Simplify + Factor
        assert_eq!(stats.operation_counts.variable_ops, 1);
        assert_eq!(stats.operation_counts.advanced, 1);
        assert!(stats.uses_advanced_methods);
        assert!(!stats.uses_calculus);
        assert!(!stats.uses_matrix_operations);
    }

    #[test]
    fn test_statistics_calculus() {
        let mut path = ResolutionPath::new(Expression::Integer(0));
        path.add_step(ResolutionStep::new(
            Operation::Differentiate {
                variable: Variable::new("x"),
                rule: "power rule".to_string(),
            },
            "Differentiate".to_string(),
            Expression::Integer(0),
        ));
        path.add_step(ResolutionStep::new(
            Operation::Integrate {
                variable: Variable::new("x"),
                technique: "substitution".to_string(),
            },
            "Integrate".to_string(),
            Expression::Integer(0),
        ));

        let stats = path.statistics();
        assert!(stats.uses_calculus);
        assert_eq!(stats.operation_counts.calculus, 2);
    }

    #[test]
    fn test_statistics_matrix() {
        let mut path = ResolutionPath::new(Expression::Integer(0));
        path.add_step(ResolutionStep::new(
            Operation::GaussianElimination,
            "Apply Gaussian elimination".to_string(),
            Expression::Integer(0),
        ));
        path.add_step(ResolutionStep::new(
            Operation::ComputeDeterminant {
                method: "cofactor expansion".to_string(),
            },
            "Compute determinant".to_string(),
            Expression::Integer(0),
        ));

        let stats = path.statistics();
        assert!(stats.uses_matrix_operations);
        assert_eq!(stats.operation_counts.matrix, 2);
    }

    #[test]
    fn test_operation_category() {
        assert_eq!(
            Operation::AddBothSides(Expression::Integer(1)).category(),
            "both_sides"
        );
        assert_eq!(Operation::Simplify.category(), "transformation");
        assert_eq!(
            Operation::Isolate(Variable::new("x")).category(),
            "variable"
        );
        assert_eq!(
            Operation::ApplyIdentity("difference of squares".to_string()).category(),
            "identity"
        );
        assert_eq!(Operation::QuadraticFormula.category(), "advanced");
        assert_eq!(
            Operation::Differentiate {
                variable: Variable::new("x"),
                rule: "power".to_string()
            }
            .category(),
            "calculus"
        );
        assert_eq!(Operation::GaussianElimination.category(), "matrix");
        assert_eq!(
            Operation::Custom("custom op".to_string()).category(),
            "custom"
        );
    }

    #[test]
    fn test_is_key_operation() {
        assert!(!Operation::Simplify.is_key_operation());
        assert!(!Operation::Cancel.is_key_operation());
        assert!(Operation::QuadraticFormula.is_key_operation());
        assert!(Operation::DivideBothSides(Expression::Integer(2)).is_key_operation());
        assert!(Operation::Factor.is_key_operation());
        assert!(Operation::GaussianElimination.is_key_operation());
    }

    #[test]
    fn test_describe_latex() {
        let op = Operation::AddBothSides(Expression::Integer(5));
        let latex = op.describe_latex();
        assert!(latex.contains("Add"));
        assert!(latex.contains("5"));
        assert!(latex.contains("both sides"));

        let op2 = Operation::QuadraticFormula;
        assert_eq!(op2.describe_latex(), "Apply quadratic formula");
    }

    #[test]
    fn test_operation_counts_default() {
        let counts = OperationCounts::default();
        assert_eq!(counts.both_sides, 0);
        assert_eq!(counts.transformations, 0);
        assert_eq!(counts.variable_ops, 0);
        assert_eq!(counts.identities, 0);
        assert_eq!(counts.advanced, 0);
        assert_eq!(counts.calculus, 0);
        assert_eq!(counts.matrix, 0);
        assert_eq!(counts.custom, 0);
    }

    #[test]
    fn test_empty_path_statistics() {
        let path = ResolutionPath::new(Expression::Integer(42));
        let stats = path.statistics();

        assert_eq!(stats.total_steps, 0);
        assert_eq!(stats.unique_operations, 0);
        assert!(!stats.uses_advanced_methods);
        assert!(!stats.uses_calculus);
        assert!(!stats.uses_matrix_operations);
    }

    #[test]
    fn test_unique_operations_count() {
        let mut path = ResolutionPath::new(Expression::Integer(10));

        // Add same operation twice
        path.add_step(ResolutionStep::new(
            Operation::Simplify,
            "First simplify".to_string(),
            Expression::Integer(10),
        ));
        path.add_step(ResolutionStep::new(
            Operation::Simplify,
            "Second simplify".to_string(),
            Expression::Integer(10),
        ));
        // Add different operation
        path.add_step(ResolutionStep::new(
            Operation::Factor,
            "Factor".to_string(),
            Expression::Integer(10),
        ));

        let stats = path.statistics();
        assert_eq!(stats.total_steps, 3);
        // Unique operations should be 2 (Simplify and Factor)
        assert_eq!(stats.unique_operations, 2);
    }

    #[test]
    fn test_escape_latex_text() {
        let text = "Use $x_1$ and {braces} with 50% & 100#";
        let escaped = escape_latex_text(text);
        assert!(escaped.contains("\\$"));
        assert!(escaped.contains("\\_"));
        assert!(escaped.contains("\\{"));
        assert!(escaped.contains("\\}"));
        assert!(escaped.contains("\\%"));
        assert!(escaped.contains("\\&"));
        assert!(escaped.contains("\\#"));
    }
}