torsh-core 0.1.2

Core types and traits for ToRSh deep learning framework
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
//! Development-time Shape Validation with Detailed Error Messages
//!
//! This module provides comprehensive shape validation for development environments,
//! offering detailed error messages, suggestions, and interactive debugging capabilities
//! to help developers understand and fix tensor shape issues.

use crate::shape_debug::ShapeDebugger;
use crate::{Result, Shape, TorshError};
use std::fmt;

/// Configuration for development-time shape validation
#[derive(Debug, Clone)]
pub struct ValidationConfig {
    /// Whether to enable strict validation (more checks, slower)
    pub strict_mode: bool,
    /// Whether to provide optimization suggestions
    pub suggest_optimizations: bool,
    /// Whether to show visual representations of shape mismatches
    pub show_visual_aids: bool,
    /// Whether to capture context from previous operations
    pub track_operation_context: bool,
    /// Maximum number of suggestions to provide per error
    pub max_suggestions: usize,
    /// Whether to enable interactive debugging prompts
    pub interactive_mode: bool,
    /// Whether to perform performance impact analysis
    pub analyze_performance: bool,
    /// Whether to suggest memory-efficient alternatives
    pub suggest_memory_optimizations: bool,
    /// Whether to enable auto-correction suggestions
    pub enable_auto_correction: bool,
    /// Verbosity level for error messages (1-5)
    pub verbosity_level: u8,
}

impl Default for ValidationConfig {
    fn default() -> Self {
        Self {
            strict_mode: true,
            suggest_optimizations: true,
            show_visual_aids: true,
            track_operation_context: true,
            max_suggestions: 5,
            interactive_mode: false, // Disabled by default for CI/CD compatibility
            analyze_performance: true,
            suggest_memory_optimizations: true,
            enable_auto_correction: true,
            verbosity_level: 3, // Medium verbosity
        }
    }
}

/// Detailed shape validation error with context and suggestions
#[derive(Debug, Clone)]
pub struct ShapeValidationError {
    /// Core error information
    pub error_type: ValidationErrorType,
    /// Detailed explanation of what went wrong
    pub explanation: String,
    /// Visual representation of the problem (if available)
    pub visual_aid: Option<String>,
    /// Suggested fixes
    pub suggestions: Vec<String>,
    /// Code examples showing how to fix the issue
    pub examples: Vec<CodeExample>,
    /// Context from previous operations
    pub operation_context: Vec<OperationContext>,
    /// Severity of the error
    pub severity: ErrorSeverity,
    /// Performance impact analysis
    pub performance_impact: Option<PerformanceAnalysis>,
    /// Memory efficiency suggestions
    pub memory_suggestions: Vec<String>,
    /// Auto-correction suggestions (executable code)
    pub auto_corrections: Vec<AutoCorrection>,
    /// Error location information
    pub location_info: Option<LocationInfo>,
}

/// Types of shape validation errors
#[derive(Debug, Clone, PartialEq)]
pub enum ValidationErrorType {
    /// Dimension count mismatch
    DimensionCountMismatch {
        expected: usize,
        got: usize,
        operation: String,
    },
    /// Specific dimension size mismatch
    DimensionSizeMismatch {
        dimension: usize,
        expected: usize,
        got: usize,
        operation: String,
    },
    /// Broadcasting incompatibility
    BroadcastingError {
        shape1: Vec<usize>,
        shape2: Vec<usize>,
        conflicting_dims: Vec<usize>,
    },
    /// Matrix multiplication incompatibility
    MatMulIncompatible {
        left_shape: Vec<usize>,
        right_shape: Vec<usize>,
        inner_dims: (usize, usize),
    },
    /// Convolution parameter mismatch
    ConvolutionError {
        input_shape: Vec<usize>,
        kernel_shape: Vec<usize>,
        error_detail: String,
    },
    /// Reduction operation error
    ReductionError {
        input_shape: Vec<usize>,
        dimension: Option<usize>,
        error_detail: String,
    },
    /// Reshape impossibility
    ReshapeError {
        original_shape: Vec<usize>,
        target_shape: Vec<usize>,
        original_size: usize,
        target_size: usize,
    },
    /// Index out of bounds
    IndexError {
        shape: Vec<usize>,
        indices: Vec<isize>,
        problematic_dim: usize,
    },
    /// Memory layout incompatibility
    LayoutError {
        operation: String,
        required_layout: String,
        actual_layout: String,
    },
    /// Custom validation error
    Custom {
        operation: String,
        description: String,
    },
}

/// Error severity levels
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum ErrorSeverity {
    /// Warning - operation might work but could be inefficient
    Warning,
    /// Error - operation will definitely fail
    Error,
    /// Critical - operation will cause undefined behavior or crashes
    Critical,
}

/// Code example showing how to fix an issue
#[derive(Debug, Clone)]
pub struct CodeExample {
    /// Description of what this example demonstrates
    pub description: String,
    /// Problematic code (what not to do)
    pub bad_code: Option<String>,
    /// Corrected code (what to do instead)
    pub good_code: String,
    /// Additional explanation
    pub explanation: String,
}

/// Context information about previous operations
#[derive(Debug, Clone)]
pub struct OperationContext {
    /// Operation name
    pub operation: String,
    /// Input shapes
    pub input_shapes: Vec<Vec<usize>>,
    /// Output shape
    pub output_shape: Vec<usize>,
    /// When this operation occurred
    pub sequence_number: usize,
}

/// Performance impact analysis for shape operations
#[derive(Debug, Clone)]
pub struct PerformanceAnalysis {
    /// Estimated computational complexity (FLOPs)
    pub computational_cost: u64,
    /// Estimated memory usage (bytes)
    pub memory_usage: usize,
    /// Performance bottleneck analysis
    pub bottlenecks: Vec<String>,
    /// Optimization opportunities
    pub optimizations: Vec<String>,
    /// Relative performance impact (1.0 = baseline)
    pub relative_impact: f64,
}

/// Auto-correction suggestion with executable code
#[derive(Debug, Clone)]
pub struct AutoCorrection {
    /// Description of the correction
    pub description: String,
    /// Rust code that would fix the issue
    pub correction_code: String,
    /// Confidence level (0.0-1.0)
    pub confidence: f64,
    /// Whether this correction is safe to auto-apply
    pub is_safe: bool,
    /// Expected outcome after applying correction
    pub expected_outcome: String,
}

/// Location information for error context
#[derive(Debug, Clone)]
pub struct LocationInfo {
    /// File name where error occurred
    pub file_name: Option<String>,
    /// Line number
    pub line_number: Option<u32>,
    /// Column number
    pub column_number: Option<u32>,
    /// Function or method name
    pub function_name: Option<String>,
    /// Additional context
    pub context: Option<String>,
}

/// Development-time shape validator
pub struct ShapeValidator {
    /// Configuration
    config: ValidationConfig,
    /// Operation history for context
    operation_history: Vec<OperationContext>,
    /// Shape debugger for analysis
    debugger: ShapeDebugger,
    /// Next sequence number
    next_sequence: usize,
}

impl ShapeValidator {
    /// Create a new shape validator with default configuration
    pub fn new() -> Self {
        Self::with_config(ValidationConfig::default())
    }

    /// Create a new shape validator with custom configuration
    pub fn with_config(config: ValidationConfig) -> Self {
        Self {
            config,
            operation_history: Vec::new(),
            debugger: ShapeDebugger::new(),
            next_sequence: 1,
        }
    }

    /// Validate element-wise operation compatibility
    pub fn validate_elementwise(
        &mut self,
        shapes: &[&Shape],
        operation: &str,
    ) -> Result<Vec<usize>> {
        if shapes.is_empty() {
            return Err(self.create_error(
                ValidationErrorType::Custom {
                    operation: operation.to_string(),
                    description: "No input shapes provided for element-wise operation".to_string(),
                },
                "Element-wise operations require at least one input tensor".to_string(),
            ));
        }

        let mut result_shape = shapes[0].dims().to_vec();

        for (_i, shape) in shapes.iter().enumerate().skip(1) {
            let compat = self
                .debugger
                .check_broadcast_compatibility(&result_shape, shape.dims());

            if !compat.is_broadcastable {
                return Err(self.create_broadcasting_error(
                    result_shape,
                    shape.dims().to_vec(),
                    operation,
                ));
            }

            result_shape = compat.resulting_shape.unwrap_or(result_shape);
        }

        // Record successful operation
        self.record_operation(operation, shapes, &result_shape);

        Ok(result_shape)
    }

    /// Validate matrix multiplication compatibility
    pub fn validate_matmul(&mut self, left: &Shape, right: &Shape) -> Result<Vec<usize>> {
        let left_dims = left.dims();
        let right_dims = right.dims();

        // Check minimum dimensionality
        if left_dims.len() < 2 || right_dims.len() < 2 {
            return Err(self.create_error(
                ValidationErrorType::MatMulIncompatible {
                    left_shape: left_dims.to_vec(),
                    right_shape: right_dims.to_vec(),
                    inner_dims: (0, 0),
                },
                "Matrix multiplication requires tensors with at least 2 dimensions".to_string(),
            ));
        }

        let left_inner = left_dims[left_dims.len() - 1];
        let right_inner = right_dims[right_dims.len() - 2];

        if left_inner != right_inner {
            return Err(self.create_matmul_error(left_dims, right_dims, left_inner, right_inner));
        }

        // Check batch dimensions compatibility
        let left_batch = &left_dims[..left_dims.len() - 2];
        let right_batch = &right_dims[..right_dims.len() - 2];

        let batch_compat = self
            .debugger
            .check_broadcast_compatibility(left_batch, right_batch);
        if !batch_compat.is_broadcastable {
            return Err(self.create_error(
                ValidationErrorType::BroadcastingError {
                    shape1: left_dims.to_vec(),
                    shape2: right_dims.to_vec(),
                    conflicting_dims: vec![], // Could be improved to identify specific dims
                },
                "Batch dimensions are not compatible for matrix multiplication".to_string(),
            ));
        }

        // Construct result shape
        let batch_shape = batch_compat.resulting_shape.unwrap_or_else(Vec::new);
        let mut result_shape = batch_shape;
        result_shape.push(left_dims[left_dims.len() - 2]); // rows from left
        result_shape.push(right_dims[right_dims.len() - 1]); // cols from right

        self.record_operation("matmul", &[left, right], &result_shape);

        Ok(result_shape)
    }

    /// Validate reshape operation
    pub fn validate_reshape(&mut self, original: &Shape, target_shape: &[usize]) -> Result<()> {
        let original_size = original.numel();
        let target_size: usize = target_shape.iter().product();

        if original_size != target_size {
            return Err(self.create_reshape_error(
                original.dims().to_vec(),
                target_shape.to_vec(),
                original_size,
                target_size,
            ));
        }

        self.record_operation("reshape", &[original], target_shape);

        Ok(())
    }

    /// Validate convolution operation
    pub fn validate_convolution(
        &mut self,
        input: &Shape,
        kernel: &Shape,
        stride: &[usize],
        padding: &[usize],
        dilation: &[usize],
    ) -> Result<Vec<usize>> {
        let input_dims = input.dims();
        let kernel_dims = kernel.dims();

        // Check minimum dimensions (NCHW format)
        if input_dims.len() != 4 || kernel_dims.len() != 4 {
            return Err(self.create_convolution_error(
                input_dims.to_vec(),
                kernel_dims.to_vec(),
                "Convolution requires 4D tensors (NCHW format)".to_string(),
            ));
        }

        // Check channel compatibility
        let input_channels = input_dims[1];
        let kernel_in_channels = kernel_dims[1];

        if input_channels != kernel_in_channels {
            return Err(self.create_convolution_error(
                input_dims.to_vec(),
                kernel_dims.to_vec(),
                format!(
                    "Input channels ({}) don't match kernel input channels ({})",
                    input_channels, kernel_in_channels
                ),
            ));
        }

        // Calculate output dimensions
        let batch_size = input_dims[0];
        let out_channels = kernel_dims[0];

        let output_height = self.calculate_conv_output_size(
            input_dims[2],
            kernel_dims[2],
            stride[0],
            padding[0],
            dilation[0],
        )?;

        let output_width = self.calculate_conv_output_size(
            input_dims[3],
            kernel_dims[3],
            stride[1],
            padding[1],
            dilation[1],
        )?;

        let result_shape = vec![batch_size, out_channels, output_height, output_width];

        self.record_operation("convolution", &[input, kernel], &result_shape);

        Ok(result_shape)
    }

    /// Validate reduction operation
    pub fn validate_reduction(
        &mut self,
        input: &Shape,
        dimensions: Option<&[usize]>,
        keep_dims: bool,
        operation: &str,
    ) -> Result<Vec<usize>> {
        let input_dims = input.dims();

        if let Some(dims) = dimensions {
            // Check that all dimensions are valid
            for &dim in dims {
                if dim >= input_dims.len() {
                    return Err(self.create_error(
                        ValidationErrorType::ReductionError {
                            input_shape: input_dims.to_vec(),
                            dimension: Some(dim),
                            error_detail: format!(
                                "Dimension {} is out of bounds for tensor with {} dimensions",
                                dim,
                                input_dims.len()
                            ),
                        },
                        format!("Invalid dimension for {} operation", operation),
                    ));
                }
            }
        }

        let result_shape = self.calculate_reduction_shape(input_dims, dimensions, keep_dims);

        self.record_operation(&format!("reduce_{}", operation), &[input], &result_shape);

        Ok(result_shape)
    }

    /// Validate indexing operation
    pub fn validate_indexing(&mut self, shape: &Shape, indices: &[isize]) -> Result<Vec<usize>> {
        let dims = shape.dims();

        if indices.len() > dims.len() {
            return Err(self.create_error(
                ValidationErrorType::IndexError {
                    shape: dims.to_vec(),
                    indices: indices.to_vec(),
                    problematic_dim: indices.len().saturating_sub(1),
                },
                format!(
                    "Too many indices: got {}, tensor has {} dimensions",
                    indices.len(),
                    dims.len()
                ),
            ));
        }

        for (i, &idx) in indices.iter().enumerate() {
            let dim_size = dims[i] as isize;

            // Check bounds (allowing negative indexing)
            if idx >= dim_size || idx < -dim_size {
                return Err(self.create_error(
                    ValidationErrorType::IndexError {
                        shape: dims.to_vec(),
                        indices: indices.to_vec(),
                        problematic_dim: i,
                    },
                    format!(
                        "Index {} is out of bounds for dimension {} with size {}",
                        idx, i, dim_size
                    ),
                ));
            }
        }

        // Calculate result shape (simplified - assumes single element indexing)
        let result_shape = dims[indices.len()..].to_vec();

        self.record_operation("indexing", &[shape], &result_shape);

        Ok(result_shape)
    }

    /// Get operation history for debugging
    pub fn get_operation_history(&self) -> &[OperationContext] {
        &self.operation_history
    }

    /// Clear operation history
    pub fn clear_history(&mut self) {
        self.operation_history.clear();
        self.next_sequence = 1;
    }

    /// Generate a comprehensive validation report
    pub fn generate_validation_report(&self) -> String {
        let mut report = String::new();
        report.push_str("=== Shape Validation Report ===\n\n");

        report.push_str(&format!(
            "Total operations validated: {}\n",
            self.operation_history.len()
        ));
        report.push_str(&format!(
            "Validation mode: {}\n",
            if self.config.strict_mode {
                "Strict"
            } else {
                "Permissive"
            }
        ));

        if !self.operation_history.is_empty() {
            report.push_str("\nRecent operations:\n");
            for (_i, op) in self.operation_history.iter().rev().take(10).enumerate() {
                report.push_str(&format!(
                    "  {}. {} -> {:?}\n",
                    op.sequence_number, op.operation, op.output_shape
                ));
            }
        }

        report
    }

    // Private helper methods

    fn record_operation(&mut self, operation: &str, inputs: &[&Shape], output: &[usize]) {
        if self.config.track_operation_context {
            let context = OperationContext {
                operation: operation.to_string(),
                input_shapes: inputs.iter().map(|s| s.dims().to_vec()).collect(),
                output_shape: output.to_vec(),
                sequence_number: self.next_sequence,
            };

            self.operation_history.push(context);
            self.next_sequence += 1;

            // Limit history size
            if self.operation_history.len() > 100 {
                self.operation_history.remove(0);
            }
        }
    }

    fn create_error(&self, error_type: ValidationErrorType, explanation: String) -> TorshError {
        let validation_error = ShapeValidationError {
            error_type: error_type.clone(),
            explanation: explanation.clone(),
            visual_aid: self.create_visual_aid(&error_type),
            suggestions: self.generate_suggestions(&error_type),
            examples: self.generate_examples(&error_type),
            operation_context: self.get_relevant_context(&error_type),
            severity: self.determine_severity(&error_type),
            performance_impact: if self.config.analyze_performance {
                Some(self.analyze_performance_impact(&error_type))
            } else {
                None
            },
            memory_suggestions: if self.config.suggest_memory_optimizations {
                self.generate_memory_suggestions(&error_type)
            } else {
                Vec::new()
            },
            auto_corrections: if self.config.enable_auto_correction {
                self.generate_auto_corrections(&error_type)
            } else {
                Vec::new()
            },
            location_info: self.capture_location_info(),
        };

        TorshError::InvalidShape(format!("{}", validation_error))
    }

    fn create_broadcasting_error(
        &self,
        shape1: Vec<usize>,
        shape2: Vec<usize>,
        operation: &str,
    ) -> TorshError {
        let conflicting_dims = self.find_conflicting_dims(&shape1, &shape2);

        self.create_error(
            ValidationErrorType::BroadcastingError {
                shape1: shape1.clone(),
                shape2: shape2.clone(),
                conflicting_dims,
            },
            format!(
                "Cannot broadcast shapes {:?} and {:?} for {} operation",
                shape1, shape2, operation
            ),
        )
    }

    fn create_matmul_error(
        &self,
        left_shape: &[usize],
        right_shape: &[usize],
        left_inner: usize,
        right_inner: usize,
    ) -> TorshError {
        self.create_error(
            ValidationErrorType::MatMulIncompatible {
                left_shape: left_shape.to_vec(),
                right_shape: right_shape.to_vec(),
                inner_dims: (left_inner, right_inner),
            },
            format!(
                "Matrix multiplication incompatible: left inner dimension {} != right inner dimension {}",
                left_inner, right_inner
            ),
        )
    }

    fn create_reshape_error(
        &self,
        original: Vec<usize>,
        target: Vec<usize>,
        original_size: usize,
        target_size: usize,
    ) -> TorshError {
        self.create_error(
            ValidationErrorType::ReshapeError {
                original_shape: original,
                target_shape: target,
                original_size,
                target_size,
            },
            format!(
                "Cannot reshape tensor: element count mismatch ({} != {})",
                original_size, target_size
            ),
        )
    }

    fn create_convolution_error(
        &self,
        input_shape: Vec<usize>,
        kernel_shape: Vec<usize>,
        detail: String,
    ) -> TorshError {
        self.create_error(
            ValidationErrorType::ConvolutionError {
                input_shape,
                kernel_shape,
                error_detail: detail.clone(),
            },
            format!("Convolution error: {}", detail),
        )
    }

    fn calculate_conv_output_size(
        &self,
        input_size: usize,
        kernel_size: usize,
        stride: usize,
        padding: usize,
        dilation: usize,
    ) -> Result<usize> {
        let effective_kernel_size = dilation * (kernel_size - 1) + 1;
        let numerator = input_size + 2 * padding;

        if numerator < effective_kernel_size {
            return Err(TorshError::InvalidArgument(
                "Effective kernel size is larger than padded input".to_string(),
            ));
        }

        Ok((numerator - effective_kernel_size) / stride + 1)
    }

    fn calculate_reduction_shape(
        &self,
        input_dims: &[usize],
        dimensions: Option<&[usize]>,
        keep_dims: bool,
    ) -> Vec<usize> {
        match dimensions {
            Some(dims) => {
                let mut result = input_dims.to_vec();
                let mut sorted_dims = dims.to_vec();
                sorted_dims.sort_by(|a, b| b.cmp(a)); // Sort in descending order

                for &dim in &sorted_dims {
                    if keep_dims {
                        result[dim] = 1;
                    } else {
                        result.remove(dim);
                    }
                }
                result
            }
            None => {
                if keep_dims {
                    vec![1; input_dims.len()]
                } else {
                    vec![]
                }
            }
        }
    }

    fn find_conflicting_dims(&self, shape1: &[usize], shape2: &[usize]) -> Vec<usize> {
        let max_len = shape1.len().max(shape2.len());
        let mut conflicts = Vec::new();

        for i in 0..max_len {
            let dim1 = shape1
                .get(shape1.len().saturating_sub(max_len) + i)
                .copied()
                .unwrap_or(1);
            let dim2 = shape2
                .get(shape2.len().saturating_sub(max_len) + i)
                .copied()
                .unwrap_or(1);

            if dim1 != dim2 && dim1 != 1 && dim2 != 1 {
                conflicts.push(i);
            }
        }

        conflicts
    }

    fn create_visual_aid(&self, error_type: &ValidationErrorType) -> Option<String> {
        if !self.config.show_visual_aids {
            return None;
        }

        match error_type {
            ValidationErrorType::BroadcastingError { shape1, shape2, .. } => {
                Some(self.create_broadcasting_visual(shape1, shape2))
            }
            ValidationErrorType::MatMulIncompatible {
                left_shape,
                right_shape,
                ..
            } => Some(self.create_matmul_visual(left_shape, right_shape)),
            ValidationErrorType::ReshapeError {
                original_shape,
                target_shape,
                ..
            } => Some(self.create_reshape_visual(original_shape, target_shape)),
            _ => None,
        }
    }

    fn create_broadcasting_visual(&self, shape1: &[usize], shape2: &[usize]) -> String {
        format!(
            "Broadcasting shapes:\n  {:?}\n  {:?}\n  ↑ Incompatible dimensions",
            shape1, shape2
        )
    }

    fn create_matmul_visual(&self, left: &[usize], right: &[usize]) -> String {
        format!(
            "Matrix multiplication:\n  Left:  {:?} (inner: {})\n  Right: {:?} (inner: {})\n  ↑ Inner dimensions must match",
            left, left.get(left.len().saturating_sub(1)).unwrap_or(&0),
            right, right.get(right.len().saturating_sub(2)).unwrap_or(&0)
        )
    }

    fn create_reshape_visual(&self, original: &[usize], target: &[usize]) -> String {
        let orig_size: usize = original.iter().product();
        let target_size: usize = target.iter().product();
        format!(
            "Reshape:\n  Original: {:?} ({} elements)\n  Target:   {:?} ({} elements)\n  ↑ Element counts must match",
            original, orig_size, target, target_size
        )
    }

    fn generate_suggestions(&self, error_type: &ValidationErrorType) -> Vec<String> {
        if !self.config.suggest_optimizations {
            return Vec::new();
        }

        let mut suggestions = Vec::new();

        match error_type {
            ValidationErrorType::BroadcastingError { .. } => {
                suggestions.push(
                    "Use explicit expand() or unsqueeze() to make shapes compatible".to_string(),
                );
                suggestions.push("Check if you need to transpose one of the tensors".to_string());
                suggestions
                    .push("Consider using reshape() to adjust tensor dimensions".to_string());
            }
            ValidationErrorType::MatMulIncompatible { .. } => {
                suggestions
                    .push("Transpose one of the matrices using .t() or .transpose()".to_string());
                suggestions.push("Check matrix dimensions: (m×k) @ (k×n) = (m×n)".to_string());
                suggestions.push("Use reshape() to adjust inner dimensions if needed".to_string());
            }
            ValidationErrorType::ReshapeError { .. } => {
                suggestions
                    .push("Use -1 for one dimension to infer size automatically".to_string());
                suggestions.push(
                    "Check total element count: original and target must be equal".to_string(),
                );
                suggestions
                    .push("Consider using view() instead of reshape() if possible".to_string());
            }
            ValidationErrorType::ConvolutionError { .. } => {
                suggestions.push(
                    "Check input format: expected NCHW (batch, channels, height, width)"
                        .to_string(),
                );
                suggestions.push("Verify kernel and input channel dimensions match".to_string());
                suggestions.push(
                    "Adjust padding or stride parameters if output size is invalid".to_string(),
                );
            }
            _ => {
                suggestions
                    .push("Check tensor documentation for expected input shapes".to_string());
                suggestions.push("Use tensor.shape to inspect current dimensions".to_string());
            }
        }

        suggestions.truncate(self.config.max_suggestions);
        suggestions
    }

    fn generate_examples(&self, error_type: &ValidationErrorType) -> Vec<CodeExample> {
        match error_type {
            ValidationErrorType::BroadcastingError { .. } => {
                vec![CodeExample {
                    description: "Fix broadcasting with unsqueeze".to_string(),
                    bad_code: Some("a.add(b)  // where a=[3,4], b=[4]".to_string()),
                    good_code: "a.add(b.unsqueeze(0))  // b becomes [1,4]".to_string(),
                    explanation: "Add dimensions to make shapes compatible".to_string(),
                }]
            }
            ValidationErrorType::MatMulIncompatible { .. } => {
                vec![CodeExample {
                    description: "Fix matrix multiplication dimensions".to_string(),
                    bad_code: Some("a.matmul(b)  // where a=[3,4], b=[3,5]".to_string()),
                    good_code: "a.matmul(b.t())  // transpose b to [5,3], then use [3,4] @ [4,5]"
                        .to_string(),
                    explanation: "Inner dimensions must match for matrix multiplication"
                        .to_string(),
                }]
            }
            _ => Vec::new(),
        }
    }

    fn get_relevant_context(&self, _error_type: &ValidationErrorType) -> Vec<OperationContext> {
        // Return last few operations for context
        self.operation_history
            .iter()
            .rev()
            .take(3)
            .cloned()
            .collect()
    }

    fn determine_severity(&self, error_type: &ValidationErrorType) -> ErrorSeverity {
        match error_type {
            ValidationErrorType::DimensionCountMismatch { .. }
            | ValidationErrorType::DimensionSizeMismatch { .. }
            | ValidationErrorType::BroadcastingError { .. }
            | ValidationErrorType::MatMulIncompatible { .. }
            | ValidationErrorType::ConvolutionError { .. }
            | ValidationErrorType::ReshapeError { .. }
            | ValidationErrorType::IndexError { .. } => ErrorSeverity::Error,

            ValidationErrorType::LayoutError { .. } => ErrorSeverity::Warning,

            ValidationErrorType::ReductionError { .. } | ValidationErrorType::Custom { .. } => {
                ErrorSeverity::Error
            }
        }
    }

    fn analyze_performance_impact(&self, error_type: &ValidationErrorType) -> PerformanceAnalysis {
        match error_type {
            ValidationErrorType::BroadcastingError { shape1, shape2, .. } => {
                let size1: usize = shape1.iter().product();
                let size2: usize = shape2.iter().product();
                let computational_cost = (size1.max(size2) as u64) * 2; // Basic estimate

                PerformanceAnalysis {
                    computational_cost,
                    memory_usage: (size1 + size2) * 4, // Assuming f32
                    bottlenecks: vec![
                        "Broadcasting creates temporary tensors".to_string(),
                        "Memory allocation overhead".to_string(),
                    ],
                    optimizations: vec![
                        "Use in-place operations when possible".to_string(),
                        "Reshape tensors before operation".to_string(),
                    ],
                    relative_impact: if size1 != size2 { 1.5 } else { 1.0 },
                }
            }
            ValidationErrorType::MatMulIncompatible {
                left_shape,
                right_shape,
                ..
            } => {
                let left_size: usize = left_shape.iter().product();
                let right_size: usize = right_shape.iter().product();

                PerformanceAnalysis {
                    computational_cost: (left_size * right_size) as u64 / 1000, // Rough estimate
                    memory_usage: (left_size + right_size) * 4,
                    bottlenecks: vec![
                        "Matrix dimensions incompatible".to_string(),
                        "Potential transpose overhead".to_string(),
                    ],
                    optimizations: vec![
                        "Transpose smaller matrix if needed".to_string(),
                        "Consider batch operations".to_string(),
                    ],
                    relative_impact: 2.0, // Matrix ops are expensive when wrong
                }
            }
            _ => PerformanceAnalysis {
                computational_cost: 1000,
                memory_usage: 1024,
                bottlenecks: vec!["Shape mismatch".to_string()],
                optimizations: vec!["Fix shape compatibility".to_string()],
                relative_impact: 1.2,
            },
        }
    }

    fn generate_memory_suggestions(&self, error_type: &ValidationErrorType) -> Vec<String> {
        match error_type {
            ValidationErrorType::BroadcastingError { .. } => {
                vec![
                    "Use view() instead of expand() when possible to avoid memory copies"
                        .to_string(),
                    "Consider using in-place operations (+=, *=, etc.)".to_string(),
                    "Pre-allocate output tensor to avoid reallocations".to_string(),
                ]
            }
            ValidationErrorType::ReshapeError {
                original_size,
                target_size,
                ..
            } => {
                vec![
                    format!(
                        "Reshape is memory-neutral but element count mismatch ({} vs {}) will fail",
                        original_size, target_size
                    ),
                    "Use view() for zero-copy shape changes when memory layout allows".to_string(),
                ]
            }
            ValidationErrorType::ConvolutionError { .. } => {
                vec![
                    "Consider using depthwise separable convolutions for efficiency".to_string(),
                    "Use im2col-free convolution implementations when available".to_string(),
                    "Optimize memory layout (NCHW vs NHWC) for your hardware".to_string(),
                ]
            }
            _ => vec![
                "Ensure tensors are contiguous for optimal memory access".to_string(),
                "Consider using smaller data types (f16) if precision allows".to_string(),
            ],
        }
    }

    fn generate_auto_corrections(&self, error_type: &ValidationErrorType) -> Vec<AutoCorrection> {
        match error_type {
            ValidationErrorType::BroadcastingError { shape1, shape2, .. } => {
                let mut corrections = Vec::new();

                // Suggest unsqueeze for missing dimensions
                if shape1.len() < shape2.len() {
                    corrections.push(AutoCorrection {
                        description: "Add missing dimensions to first tensor".to_string(),
                        correction_code: "tensor1.unsqueeze(0)".to_string(),
                        confidence: 0.8,
                        is_safe: true,
                        expected_outcome: format!("Shape becomes compatible: {:?}", shape2),
                    });
                }

                corrections
            }
            ValidationErrorType::MatMulIncompatible {
                left_shape,
                right_shape,
                ..
            } => {
                vec![AutoCorrection {
                    description: "Transpose right matrix to make dimensions compatible".to_string(),
                    correction_code: "right_tensor.transpose(-2, -1)".to_string(),
                    confidence: 0.9,
                    is_safe: true,
                    expected_outcome: format!(
                        "Matrix multiplication becomes: {:?} @ {:?}",
                        left_shape,
                        right_shape.iter().rev().cloned().collect::<Vec<_>>()
                    ),
                }]
            }
            ValidationErrorType::ReshapeError {
                original_shape,
                target_shape,
                ..
            } => {
                let original_size: usize = original_shape.iter().product();
                vec![AutoCorrection {
                    description: "Use -1 for automatic dimension inference".to_string(),
                    correction_code: format!("tensor.reshape([{}, -1])", target_shape[0]),
                    confidence: 0.7,
                    is_safe: true,
                    expected_outcome: format!(
                        "Auto-infer second dimension: [{}, {}]",
                        target_shape[0],
                        original_size / target_shape[0]
                    ),
                }]
            }
            _ => Vec::new(),
        }
    }

    fn capture_location_info(&self) -> Option<LocationInfo> {
        // In a real implementation, this would use std::panic::Location
        // or debug information to capture the actual call site
        Some(LocationInfo {
            file_name: Some("shape_validation.rs".to_string()),
            line_number: Some(std::line!()),
            column_number: None,
            function_name: Some("validate_operation".to_string()),
            context: Some("Shape validation during tensor operation".to_string()),
        })
    }
}

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

impl fmt::Display for ShapeValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "🔍 Shape Validation Error ({:?}):", self.severity)?;
        writeln!(f, "{}", self.explanation)?;

        // Location info
        if let Some(ref location) = self.location_info {
            if let (Some(ref file), Some(line)) = (&location.file_name, location.line_number) {
                writeln!(f, "📍 Location: {}:{}", file, line)?;
            }
            if let Some(ref func) = &location.function_name {
                writeln!(f, "🔧 Function: {}", func)?;
            }
        }

        if let Some(ref visual) = self.visual_aid {
            writeln!(f, "\n🎨 Visual representation:")?;
            writeln!(f, "{}", visual)?;
        }

        if !self.suggestions.is_empty() {
            writeln!(f, "\n💡 Suggestions:")?;
            for (i, suggestion) in self.suggestions.iter().enumerate() {
                writeln!(f, "  {}. {}", i + 1, suggestion)?;
            }
        }

        // Memory suggestions
        if !self.memory_suggestions.is_empty() {
            writeln!(f, "\n🧠 Memory optimization:")?;
            for (i, suggestion) in self.memory_suggestions.iter().enumerate() {
                writeln!(f, "  {}. {}", i + 1, suggestion)?;
            }
        }

        // Performance analysis
        if let Some(ref perf) = self.performance_impact {
            writeln!(f, "\n⚡ Performance impact:")?;
            writeln!(f, "  Computational cost: {} FLOPs", perf.computational_cost)?;
            writeln!(f, "  Memory usage: {} bytes", perf.memory_usage)?;
            writeln!(f, "  Relative impact: {:.1}x", perf.relative_impact)?;
            if !perf.bottlenecks.is_empty() {
                writeln!(f, "  Bottlenecks: {}", perf.bottlenecks.join(", "))?;
            }
        }

        // Auto-corrections
        if !self.auto_corrections.is_empty() {
            writeln!(f, "\n🤖 Auto-corrections:")?;
            for (i, correction) in self.auto_corrections.iter().enumerate() {
                writeln!(
                    f,
                    "  {}. {} (confidence: {:.1}%)",
                    i + 1,
                    correction.description,
                    correction.confidence * 100.0
                )?;
                writeln!(f, "     Code: {}", correction.correction_code)?;
                if correction.is_safe {
                    writeln!(f, "     ✅ Safe to auto-apply")?;
                } else {
                    writeln!(f, "     ⚠️  Manual review recommended")?;
                }
            }
        }

        if !self.examples.is_empty() {
            writeln!(f, "\n📝 Examples:")?;
            for example in &self.examples {
                writeln!(f, "  {}", example.description)?;
                if let Some(ref bad) = example.bad_code {
                    writeln!(f, "{}", bad)?;
                }
                writeln!(f, "{}", example.good_code)?;
                writeln!(f, "    ℹ️  {}", example.explanation)?;
            }
        }

        if !self.operation_context.is_empty() {
            writeln!(f, "\n📜 Recent operations:")?;
            for context in &self.operation_context {
                writeln!(
                    f,
                    "  {}. {} -> {:?}",
                    context.sequence_number, context.operation, context.output_shape
                )?;
            }
        }

        Ok(())
    }
}

/// Global validator instance for convenience
static GLOBAL_VALIDATOR: std::sync::OnceLock<std::sync::Mutex<ShapeValidator>> =
    std::sync::OnceLock::new();

/// Initialize global validator with custom configuration
pub fn init_global_validator(config: ValidationConfig) -> Result<()> {
    GLOBAL_VALIDATOR
        .set(std::sync::Mutex::new(ShapeValidator::with_config(config)))
        .map_err(|_| {
            TorshError::InvalidState("Global validator already initialized".to_string())
        })?;
    Ok(())
}

/// Get reference to global validator
///
/// # Panics
///
/// This function will not panic even if the mutex is poisoned. In case of a poisoned
/// mutex (which occurs when a thread panicked while holding the lock), this function
/// recovers the inner validator state, as shape validation is safe to continue.
pub fn get_global_validator() -> std::sync::MutexGuard<'static, ShapeValidator> {
    GLOBAL_VALIDATOR
        .get_or_init(|| std::sync::Mutex::new(ShapeValidator::new()))
        .lock()
        .unwrap_or_else(|poisoned| {
            // Recover from poisoned mutex - shape validation is safe to continue
            poisoned.into_inner()
        })
}

/// Convenience macros for validation
#[macro_export]
macro_rules! validate_shapes {
    (elementwise, $op:expr, $($shape:expr),+) => {{
        let shapes = vec![$($shape),+];
        $crate::shape_validation::get_global_validator().validate_elementwise(&shapes, $op)
    }};

    (matmul, $left:expr, $right:expr) => {{
        $crate::shape_validation::get_global_validator().validate_matmul($left, $right)
    }};

    (reshape, $original:expr, $target:expr) => {{
        $crate::shape_validation::get_global_validator().validate_reshape($original, $target)
    }};
}

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

    #[test]
    fn test_validator_creation() {
        let validator = ShapeValidator::new();
        assert_eq!(validator.operation_history.len(), 0);
    }

    #[test]
    fn test_elementwise_validation_success() {
        let mut validator = ShapeValidator::new();
        let shape1 = Shape::new(vec![3, 4]);
        let shape2 = Shape::new(vec![1, 4]);

        let result = validator.validate_elementwise(&[&shape1, &shape2], "add");
        assert!(result.is_ok());
        assert_eq!(
            result.expect("validate_elementwise should succeed"),
            vec![3, 4]
        );
    }

    #[test]
    fn test_elementwise_validation_failure() {
        let mut validator = ShapeValidator::new();
        let shape1 = Shape::new(vec![3, 4]);
        let shape2 = Shape::new(vec![3, 5]);

        let result = validator.validate_elementwise(&[&shape1, &shape2], "add");
        assert!(result.is_err());
    }

    #[test]
    fn test_matmul_validation_success() {
        let mut validator = ShapeValidator::new();
        let left = Shape::new(vec![3, 4]);
        let right = Shape::new(vec![4, 5]);

        let result = validator.validate_matmul(&left, &right);
        assert!(result.is_ok());
        assert_eq!(result.expect("validate_matmul should succeed"), vec![3, 5]);
    }

    #[test]
    fn test_matmul_validation_failure() {
        let mut validator = ShapeValidator::new();
        let left = Shape::new(vec![3, 4]);
        let right = Shape::new(vec![5, 6]);

        let result = validator.validate_matmul(&left, &right);
        assert!(result.is_err());
    }

    #[test]
    fn test_reshape_validation() {
        let mut validator = ShapeValidator::new();
        let shape = Shape::new(vec![2, 3, 4]);

        // Valid reshape
        let result = validator.validate_reshape(&shape, &[6, 4]);
        assert!(result.is_ok());

        // Invalid reshape
        let result = validator.validate_reshape(&shape, &[5, 5]);
        assert!(result.is_err());
    }

    #[test]
    fn test_convolution_validation() {
        let mut validator = ShapeValidator::new();
        let input = Shape::new(vec![1, 3, 32, 32]); // NCHW
        let kernel = Shape::new(vec![16, 3, 3, 3]); // Out, In, H, W

        let result = validator.validate_convolution(
            &input,
            &kernel,
            &[1, 1], // stride
            &[0, 0], // padding
            &[1, 1], // dilation
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_operation_history_tracking() {
        let mut validator = ShapeValidator::new();
        let shape1 = Shape::new(vec![3, 4]);
        let shape2 = Shape::new(vec![3, 4]);

        let _result = validator.validate_elementwise(&[&shape1, &shape2], "add");

        assert_eq!(validator.operation_history.len(), 1);
        assert_eq!(validator.operation_history[0].operation, "add");
    }

    #[test]
    fn test_global_validator() {
        let validator = get_global_validator();
        // Just test that we can get the global validator without panicking
        drop(validator);
    }

    #[test]
    fn test_enhanced_error_messages() {
        let config = ValidationConfig {
            analyze_performance: true,
            suggest_memory_optimizations: true,
            enable_auto_correction: true,
            verbosity_level: 5,
            ..Default::default()
        };

        let mut validator = ShapeValidator::with_config(config);
        let shape1 = Shape::new(vec![3, 4]);
        let shape2 = Shape::new(vec![3, 5]);

        let result = validator.validate_elementwise(&[&shape1, &shape2], "add");
        assert!(result.is_err());

        // Check that the error contains enhanced information
        let error_msg = format!("{}", result.unwrap_err());
        assert!(error_msg.contains("Performance impact"));
        assert!(error_msg.contains("Memory optimization"));
    }

    #[test]
    fn test_performance_analysis() {
        let mut validator = ShapeValidator::new();
        let left = Shape::new(vec![1000, 1000]);
        let right = Shape::new(vec![1000, 1000]);

        let result = validator.validate_matmul(&left, &right);
        assert!(result.is_ok());

        // Test with incompatible shapes to trigger performance analysis
        let left_bad = Shape::new(vec![1000, 500]);
        let right_bad = Shape::new(vec![1000, 500]); // Wrong inner dimension

        let result = validator.validate_matmul(&left_bad, &right_bad);
        assert!(result.is_err());
    }

    #[test]
    fn test_auto_corrections() {
        let config = ValidationConfig {
            enable_auto_correction: true,
            ..Default::default()
        };

        let mut validator = ShapeValidator::with_config(config);
        let left = Shape::new(vec![3, 4]);
        let right = Shape::new(vec![3, 5]); // Incompatible for matmul

        let result = validator.validate_matmul(&left, &right);
        assert!(result.is_err());

        let error_msg = format!("{}", result.unwrap_err());
        assert!(error_msg.contains("Auto-corrections"));
        assert!(error_msg.contains("transpose"));
    }

    #[test]
    fn test_memory_suggestions() {
        let config = ValidationConfig {
            suggest_memory_optimizations: true,
            ..Default::default()
        };

        let mut validator = ShapeValidator::with_config(config);
        let original = Shape::new(vec![2, 3, 4]);

        // Invalid reshape to trigger memory suggestions
        let result = validator.validate_reshape(&original, &[5, 5]);
        assert!(result.is_err());

        let error_msg = format!("{}", result.unwrap_err());
        assert!(error_msg.contains("Memory optimization"));
    }

    #[test]
    fn test_validation_config_customization() {
        let config = ValidationConfig {
            strict_mode: false,
            suggest_optimizations: false,
            show_visual_aids: false,
            analyze_performance: false,
            suggest_memory_optimizations: false,
            enable_auto_correction: false,
            verbosity_level: 1,
            ..Default::default()
        };

        let mut validator = ShapeValidator::with_config(config);
        let shape1 = Shape::new(vec![3, 4]);
        let shape2 = Shape::new(vec![3, 5]);

        let result = validator.validate_elementwise(&[&shape1, &shape2], "add");
        assert!(result.is_err());

        // With minimal config, error should be less verbose
        let error_msg = format!("{}", result.unwrap_err());
        assert!(!error_msg.contains("Performance impact"));
        assert!(!error_msg.contains("Auto-corrections"));
    }

    #[test]
    fn test_operation_history_with_context() {
        let mut validator = ShapeValidator::new();
        let shape1 = Shape::new(vec![2, 3]);
        let shape2 = Shape::new(vec![3, 4]);
        let shape3 = Shape::new(vec![2, 4]);

        // Perform a series of operations
        let _result1 = validator.validate_matmul(&shape1, &shape2);
        let _result2 = validator.validate_elementwise(&[&shape3], "relu");

        // Now cause an error and check context
        let result = validator.validate_matmul(&shape1, &shape3);
        assert!(result.is_err());

        let error_msg = format!("{}", result.unwrap_err());
        assert!(error_msg.contains("Recent operations"));
        assert!(error_msg.contains("matmul"));
        assert!(error_msg.contains("relu"));
    }

    #[test]
    fn test_convolution_detailed_validation() {
        let mut validator = ShapeValidator::new();
        let input = Shape::new(vec![1, 64, 224, 224]); // Batch, Channels, Height, Width
        let kernel = Shape::new(vec![128, 32, 3, 3]); // Out channels, Wrong in channels, H, W

        let result = validator.validate_convolution(
            &input,
            &kernel,
            &[1, 1], // stride
            &[1, 1], // padding
            &[1, 1], // dilation
        );

        assert!(result.is_err());
        let error_msg = format!("{}", result.unwrap_err());
        assert!(error_msg.contains("Input channels"));
        assert!(error_msg.contains("kernel input channels"));
    }

    #[test]
    fn test_reduction_validation_edge_cases() {
        let mut validator = ShapeValidator::new();
        let input = Shape::new(vec![2, 3, 4]);

        // Valid reduction
        let result = validator.validate_reduction(&input, Some(&[1]), true, "sum");
        assert!(result.is_ok());
        assert_eq!(
            result.expect("validate_reduction should succeed"),
            vec![2, 1, 4]
        );

        // Invalid dimension
        let result = validator.validate_reduction(&input, Some(&[5]), false, "mean");
        assert!(result.is_err());

        let error_msg = format!("{}", result.unwrap_err());
        // Error message should contain "Invalid" or "dimension" since dimension 5 is invalid for shape [2, 3, 4]
        assert!(error_msg.contains("Invalid") || error_msg.contains("dimension"));
    }

    #[test]
    fn test_indexing_validation_comprehensive() {
        let mut validator = ShapeValidator::new();
        let shape = Shape::new(vec![10, 20, 30]);

        // Valid indexing
        let result = validator.validate_indexing(&shape, &[5, 10]);
        assert!(result.is_ok());
        assert_eq!(result.expect("validate_indexing should succeed"), vec![30]);

        // Out of bounds positive index
        let result = validator.validate_indexing(&shape, &[15, 5]);
        assert!(result.is_err());

        // Out of bounds negative index
        let result = validator.validate_indexing(&shape, &[-15, 5]);
        assert!(result.is_err());

        // Too many indices
        let result = validator.validate_indexing(&shape, &[1, 2, 3, 4]);
        assert!(result.is_err());
    }
}