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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Comprehensive error handling system for MCP AI Data Scientist.

Provides centralized error handling, recovery mechanisms, and user-friendly error messages.

"""

import logging
import traceback
import asyncio
import re
import json
from typing import Dict, Any, Optional, List, Callable, Union, Type
from datetime import datetime, timezone
from enum import Enum
from dataclasses import dataclass
from contextlib import asynccontextmanager
import time
import random

from .monitoring import get_logger, record_error, record_metric


class ErrorSeverity(Enum):
    """Error severity levels."""
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    CRITICAL = "critical"


class ErrorCategory(Enum):
    """Error categories for classification."""
    VALIDATION = "validation"
    AUTHENTICATION = "authentication"
    AUTHORIZATION = "authorization"
    DATA_PROCESSING = "data_processing"
    MCP_SERVER = "mcp_server"
    DATABASE = "database"
    NETWORK = "network"
    SYSTEM = "system"
    BUSINESS_LOGIC = "business_logic"
    EXTERNAL_API = "external_api"


@dataclass
class ErrorContext:
    """Context information for errors."""
    user_id: Optional[str] = None
    session_id: Optional[str] = None
    component: Optional[str] = None
    operation: Optional[str] = None
    request_id: Optional[str] = None
    additional_data: Optional[Dict[str, Any]] = None


@dataclass
class ErrorInfo:
    """Comprehensive error information."""
    error_id: str
    category: ErrorCategory
    severity: ErrorSeverity
    message: str
    user_message: str
    technical_details: str
    context: ErrorContext
    timestamp: datetime
    stack_trace: Optional[str] = None
    recovery_suggestions: Optional[List[str]] = None
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary for serialization."""
        return {
            "error_id": self.error_id,
            "category": self.category.value,
            "severity": self.severity.value,
            "message": self.message,
            "user_message": self.user_message,
            "technical_details": self.technical_details,
            "timestamp": self.timestamp.isoformat(),
            "context": {
                "user_id": self.context.user_id,
                "session_id": self.context.session_id,
                "component": self.context.component,
                "operation": self.context.operation,
                "request_id": self.context.request_id,
                "additional_data": self.context.additional_data
            },
            "stack_trace": self.stack_trace,
            "recovery_suggestions": self.recovery_suggestions
        }


class ApplicationError(Exception):
    """Base application error with enhanced context."""
    
    def __init__(

        self,

        message: str,

        category: ErrorCategory = ErrorCategory.SYSTEM,

        severity: ErrorSeverity = ErrorSeverity.MEDIUM,

        user_message: Optional[str] = None,

        context: Optional[ErrorContext] = None,

        recovery_suggestions: Optional[List[str]] = None

    ):
        super().__init__(message)
        self.category = category
        self.severity = severity
        self.user_message = user_message or self._generate_user_message()
        self.context = context or ErrorContext()
        self.recovery_suggestions = recovery_suggestions or []
    
    def _generate_user_message(self) -> str:
        """Generate user-friendly error message."""
        category_messages = {
            ErrorCategory.VALIDATION: "Please check your input and try again.",
            ErrorCategory.AUTHENTICATION: "Please log in and try again.",
            ErrorCategory.AUTHORIZATION: "You don't have permission to perform this action.",
            ErrorCategory.DATA_PROCESSING: "There was an issue processing your data. Please try again.",
            ErrorCategory.MCP_SERVER: "A service is temporarily unavailable. Please try again later.",
            ErrorCategory.DATABASE: "There was a database issue. Please try again later.",
            ErrorCategory.NETWORK: "Network connection issue. Please check your connection and try again.",
            ErrorCategory.SYSTEM: "A system error occurred. Please try again later.",
            ErrorCategory.BUSINESS_LOGIC: "Unable to complete the requested operation.",
            ErrorCategory.EXTERNAL_API: "An external service is unavailable. Please try again later."
        }
        
        return category_messages.get(
            self.category,
            "An unexpected error occurred. Please try again later."
        )


class ValidationError(ApplicationError):
    """Validation-specific error."""
    
    def __init__(self, message: str, field: str = None, **kwargs):
        super().__init__(
            message,
            category=ErrorCategory.VALIDATION,
            severity=ErrorSeverity.LOW,
            **kwargs
        )
        self.field = field


class AuthenticationError(ApplicationError):
    """Authentication-specific error."""
    
    def __init__(self, message: str, **kwargs):
        super().__init__(
            message,
            category=ErrorCategory.AUTHENTICATION,
            severity=ErrorSeverity.HIGH,
            **kwargs
        )


class DataProcessingError(ApplicationError):
    """Data processing-specific error."""
    
    def __init__(self, message: str, stage: str = None, **kwargs):
        super().__init__(
            message,
            category=ErrorCategory.DATA_PROCESSING,
            severity=ErrorSeverity.MEDIUM,
            **kwargs
        )
        self.stage = stage


class MCPServerError(ApplicationError):
    """MCP server-specific error."""
    
    def __init__(self, message: str, server_name: str = None, **kwargs):
        super().__init__(
            message,
            category=ErrorCategory.MCP_SERVER,
            severity=ErrorSeverity.HIGH,
            **kwargs
        )
        self.server_name = server_name


class ErrorHandler:
    """Centralized error handler with recovery mechanisms."""
    
    def __init__(self):
        self.logger = get_logger("error_handler")
        self.error_history: List[ErrorInfo] = []
        self.recovery_handlers: Dict[ErrorCategory, List[Callable]] = {}
        self.error_count_by_category: Dict[ErrorCategory, int] = {}
    
    def register_recovery_handler(self, category: ErrorCategory, handler: Callable):
        """Register a recovery handler for specific error category."""
        if category not in self.recovery_handlers:
            self.recovery_handlers[category] = []
        self.recovery_handlers[category].append(handler)
    
    async def handle_error(

        self,

        error: Exception,

        context: Optional[ErrorContext] = None,

        attempt_recovery: bool = True

    ) -> ErrorInfo:
        """Handle an error with comprehensive logging and recovery."""
        
        # Generate error ID
        error_id = f"err_{int(datetime.now().timestamp())}_{id(error)}"
        
        # Determine error details
        if isinstance(error, ApplicationError):
            category = error.category
            severity = error.severity
            user_message = error.user_message
            recovery_suggestions = error.recovery_suggestions
            error_context = error.context
        else:
            category = self._classify_error(error)
            severity = self._determine_severity(error, category)
            user_message = self._generate_user_message(error, category)
            recovery_suggestions = self._generate_recovery_suggestions(error, category)
            error_context = context or ErrorContext()
        
        # Create error info
        error_info = ErrorInfo(
            error_id=error_id,
            category=category,
            severity=severity,
            message=str(error),
            user_message=user_message,
            technical_details=self._get_technical_details(error),
            context=error_context,
            timestamp=datetime.now(timezone.utc),
            stack_trace=traceback.format_exc(),
            recovery_suggestions=recovery_suggestions
        )
        
        # Log error
        self._log_error(error_info)
        
        # Record metrics
        self._record_error_metrics(error_info)
        
        # Store in history
        self.error_history.append(error_info)
        
        # Keep only last 1000 errors
        if len(self.error_history) > 1000:
            self.error_history = self.error_history[-1000:]
        
        # Attempt recovery if enabled
        if attempt_recovery:
            await self._attempt_recovery(error_info)
        
        return error_info
    
    def _classify_error(self, error: Exception) -> ErrorCategory:
        """Classify error into appropriate category."""
        error_type = type(error).__name__
        error_message = str(error).lower()
        
        # Classification rules
        if "validation" in error_message or "invalid" in error_message:
            return ErrorCategory.VALIDATION
        elif "auth" in error_message or "permission" in error_message:
            return ErrorCategory.AUTHENTICATION
        elif "database" in error_message or "connection" in error_message:
            return ErrorCategory.DATABASE
        elif "network" in error_message or "timeout" in error_message:
            return ErrorCategory.NETWORK
        elif "mcp" in error_message or "server" in error_message:
            return ErrorCategory.MCP_SERVER
        elif error_type in ["ValueError", "TypeError", "KeyError"]:
            return ErrorCategory.VALIDATION
        elif error_type in ["ConnectionError", "TimeoutError"]:
            return ErrorCategory.NETWORK
        else:
            return ErrorCategory.SYSTEM
    
    def _determine_severity(self, error: Exception, category: ErrorCategory) -> ErrorSeverity:
        """Determine error severity based on type and category."""
        
        # Critical errors
        if isinstance(error, (SystemExit, KeyboardInterrupt)):
            return ErrorSeverity.CRITICAL
        
        # High severity errors
        if category in [ErrorCategory.AUTHENTICATION, ErrorCategory.DATABASE]:
            return ErrorSeverity.HIGH
        
        # Medium severity errors
        if category in [ErrorCategory.MCP_SERVER, ErrorCategory.DATA_PROCESSING]:
            return ErrorSeverity.MEDIUM
        
        # Low severity errors
        if category == ErrorCategory.VALIDATION:
            return ErrorSeverity.LOW
        
        return ErrorSeverity.MEDIUM
    
    def _generate_user_message(self, error: Exception, category: ErrorCategory) -> str:
        """Generate user-friendly error message."""
        
        category_messages = {
            ErrorCategory.VALIDATION: "Please check your input and try again.",
            ErrorCategory.AUTHENTICATION: "Authentication failed. Please log in again.",
            ErrorCategory.AUTHORIZATION: "You don't have permission for this action.",
            ErrorCategory.DATA_PROCESSING: "Error processing your data. Please try again.",
            ErrorCategory.MCP_SERVER: "Service temporarily unavailable. Please try again later.",
            ErrorCategory.DATABASE: "Database error. Please try again later.",
            ErrorCategory.NETWORK: "Network error. Please check your connection.",
            ErrorCategory.SYSTEM: "System error. Please try again later.",
            ErrorCategory.BUSINESS_LOGIC: "Unable to complete the operation.",
            ErrorCategory.EXTERNAL_API: "External service unavailable. Please try again later."
        }
        
        return category_messages.get(category, "An error occurred. Please try again.")
    
    def _generate_recovery_suggestions(self, error: Exception, category: ErrorCategory) -> List[str]:
        """Generate recovery suggestions based on error type."""
        
        suggestions = {
            ErrorCategory.VALIDATION: [
                "Check your input format and try again",
                "Ensure all required fields are filled",
                "Verify data types match expected format"
            ],
            ErrorCategory.AUTHENTICATION: [
                "Log out and log back in",
                "Clear browser cache and cookies",
                "Contact support if issue persists"
            ],
            ErrorCategory.DATA_PROCESSING: [
                "Try with a smaller dataset",
                "Check data format and encoding",
                "Remove any special characters or formatting"
            ],
            ErrorCategory.MCP_SERVER: [
                "Wait a few minutes and try again",
                "Check system status page",
                "Contact support if issue persists"
            ],
            ErrorCategory.NETWORK: [
                "Check your internet connection",
                "Try refreshing the page",
                "Wait a moment and try again"
            ]
        }
        
        return suggestions.get(category, ["Try again later", "Contact support if issue persists"])
    
    def _get_technical_details(self, error: Exception) -> str:
        """Get technical details for debugging."""
        return f"{type(error).__name__}: {str(error)}"
    
    def _log_error(self, error_info: ErrorInfo):
        """Log error with appropriate level."""
        
        log_message = (
            f"Error {error_info.error_id}: {error_info.message} "
            f"[{error_info.category.value}/{error_info.severity.value}]"
        )
        
        if error_info.context.user_id:
            log_message += f" User: {error_info.context.user_id}"
        
        if error_info.context.session_id:
            log_message += f" Session: {error_info.context.session_id}"
        
        # Log based on severity
        if error_info.severity == ErrorSeverity.CRITICAL:
            self.logger.critical(log_message)
        elif error_info.severity == ErrorSeverity.HIGH:
            self.logger.error(log_message)
        elif error_info.severity == ErrorSeverity.MEDIUM:
            self.logger.warning(log_message)
        else:
            self.logger.info(log_message)
        
        # Log stack trace for high/critical errors
        if error_info.severity in [ErrorSeverity.HIGH, ErrorSeverity.CRITICAL]:
            if error_info.stack_trace:
                self.logger.debug(f"Stack trace for {error_info.error_id}:\n{error_info.stack_trace}")
    
    def _record_error_metrics(self, error_info: ErrorInfo):
        """Record error metrics for monitoring."""
        
        # Record error count
        record_error(
            error_info.context.component or "unknown",
            error_info.category.value,
            error_info.context.operation or "unknown"
        )
        
        # Record error by severity
        record_metric(
            "errors.by_severity",
            1,
            tags={
                "severity": error_info.severity.value,
                "category": error_info.category.value
            }
        )
        
        # Update category count
        if error_info.category not in self.error_count_by_category:
            self.error_count_by_category[error_info.category] = 0
        self.error_count_by_category[error_info.category] += 1
    
    async def _attempt_recovery(self, error_info: ErrorInfo):
        """Attempt error recovery using registered handlers."""
        
        if error_info.category not in self.recovery_handlers:
            return
        
        for handler in self.recovery_handlers[error_info.category]:
            try:
                await handler(error_info)
                self.logger.info(f"Recovery attempted for error {error_info.error_id}")
                break
            except Exception as recovery_error:
                self.logger.error(f"Recovery handler failed for {error_info.error_id}: {recovery_error}")
    
    def get_error_statistics(self) -> Dict[str, Any]:
        """Get error statistics for monitoring."""
        
        total_errors = len(self.error_history)
        
        if total_errors == 0:
            return {"total_errors": 0}
        
        # Recent errors (last hour)
        recent_cutoff = datetime.now(timezone.utc).timestamp() - 3600
        recent_errors = [
            err for err in self.error_history
            if err.timestamp.timestamp() > recent_cutoff
        ]
        
        # Category breakdown
        category_counts = {}
        for category in ErrorCategory:
            category_counts[category.value] = self.error_count_by_category.get(category, 0)
        
        # Severity breakdown
        severity_counts = {}
        for error in self.error_history:
            severity = error.severity.value
            severity_counts[severity] = severity_counts.get(severity, 0) + 1
        
        return {
            "total_errors": total_errors,
            "recent_errors_1h": len(recent_errors),
            "category_breakdown": category_counts,
            "severity_breakdown": severity_counts,
            "error_rate_per_hour": len(recent_errors)
        }


# Input validation classes and functions
class ValidationRule:
    """Base validation rule."""
    
    def __init__(self, field_name: str, error_message: str = None):
        self.field_name = field_name
        self.error_message = error_message or f"Invalid value for {field_name}"
    
    def validate(self, value: Any) -> bool:
        """Validate the value. Override in subclasses."""
        return True
    
    def get_error_message(self, value: Any) -> str:
        """Get error message for invalid value."""
        return self.error_message


class RequiredRule(ValidationRule):
    """Validates that a field is present and not None/empty."""
    
    def validate(self, value: Any) -> bool:
        if value is None:
            return False
        if isinstance(value, str) and not value.strip():
            return False
        if isinstance(value, (list, dict)) and len(value) == 0:
            return False
        return True
    
    def get_error_message(self, value: Any) -> str:
        return f"{self.field_name} is required"


class TypeRule(ValidationRule):
    """Validates that a field is of the correct type."""
    
    def __init__(self, field_name: str, expected_type: Type, error_message: str = None):
        self.expected_type = expected_type
        super().__init__(field_name, error_message)
    
    def validate(self, value: Any) -> bool:
        if value is None:
            return True  # Type validation only applies to non-None values
        return isinstance(value, self.expected_type)
    
    def get_error_message(self, value: Any) -> str:
        return f"{self.field_name} must be of type {self.expected_type.__name__}, got {type(value).__name__}"


class RangeRule(ValidationRule):
    """Validates that a numeric field is within a specified range."""
    
    def __init__(self, field_name: str, min_val: float = None, max_val: float = None, error_message: str = None):
        self.min_val = min_val
        self.max_val = max_val
        super().__init__(field_name, error_message)
    
    def validate(self, value: Any) -> bool:
        if value is None or not isinstance(value, (int, float)):
            return True  # Range validation only applies to numeric values
        
        if self.min_val is not None and value < self.min_val:
            return False
        if self.max_val is not None and value > self.max_val:
            return False
        return True
    
    def get_error_message(self, value: Any) -> str:
        if self.min_val is not None and self.max_val is not None:
            return f"{self.field_name} must be between {self.min_val} and {self.max_val}"
        elif self.min_val is not None:
            return f"{self.field_name} must be at least {self.min_val}"
        elif self.max_val is not None:
            return f"{self.field_name} must be at most {self.max_val}"
        return self.error_message


class LengthRule(ValidationRule):
    """Validates string/list length."""
    
    def __init__(self, field_name: str, min_length: int = None, max_length: int = None, error_message: str = None):
        self.min_length = min_length
        self.max_length = max_length
        super().__init__(field_name, error_message)
    
    def validate(self, value: Any) -> bool:
        if value is None:
            return True
        
        if not hasattr(value, '__len__'):
            return False
        
        length = len(value)
        if self.min_length is not None and length < self.min_length:
            return False
        if self.max_length is not None and length > self.max_length:
            return False
        return True
    
    def get_error_message(self, value: Any) -> str:
        if self.min_length is not None and self.max_length is not None:
            return f"{self.field_name} length must be between {self.min_length} and {self.max_length}"
        elif self.min_length is not None:
            return f"{self.field_name} must be at least {self.min_length} characters/items"
        elif self.max_length is not None:
            return f"{self.field_name} must be at most {self.max_length} characters/items"
        return self.error_message


class PatternRule(ValidationRule):
    """Validates string against regex pattern."""
    
    def __init__(self, field_name: str, pattern: str, error_message: str = None):
        self.pattern = re.compile(pattern)
        super().__init__(field_name, error_message)
    
    def validate(self, value: Any) -> bool:
        if value is None or not isinstance(value, str):
            return True
        return bool(self.pattern.match(value))
    
    def get_error_message(self, value: Any) -> str:
        return f"{self.field_name} format is invalid"


class EmailRule(PatternRule):
    """Validates email format."""
    
    def __init__(self, field_name: str):
        email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
        super().__init__(field_name, email_pattern, f"{field_name} must be a valid email address")


class FileExtensionRule(ValidationRule):
    """Validates file extension."""
    
    def __init__(self, field_name: str, allowed_extensions: List[str], error_message: str = None):
        self.allowed_extensions = [ext.lower() for ext in allowed_extensions]
        super().__init__(field_name, error_message)
    
    def validate(self, value: Any) -> bool:
        if value is None or not isinstance(value, str):
            return True
        
        # Extract extension from filename
        if '.' not in value:
            return False
        
        ext = value.split('.')[-1].lower()
        return ext in self.allowed_extensions
    
    def get_error_message(self, value: Any) -> str:
        return f"{self.field_name} must have one of these extensions: {', '.join(self.allowed_extensions)}"


class InputValidator:
    """Comprehensive input validator."""
    
    def __init__(self):
        self.rules: Dict[str, List[ValidationRule]] = {}
    
    def add_rule(self, field_name: str, rule: ValidationRule):
        """Add a validation rule for a field."""
        if field_name not in self.rules:
            self.rules[field_name] = []
        self.rules[field_name].append(rule)
    
    def add_rules(self, field_name: str, rules: List[ValidationRule]):
        """Add multiple validation rules for a field."""
        for rule in rules:
            self.add_rule(field_name, rule)
    
    def validate(self, data: Dict[str, Any]) -> Dict[str, List[str]]:
        """Validate data against all rules. Returns dict of field -> error messages."""
        errors = {}
        
        for field_name, rules in self.rules.items():
            field_errors = []
            value = data.get(field_name)
            
            for rule in rules:
                if not rule.validate(value):
                    field_errors.append(rule.get_error_message(value))
            
            if field_errors:
                errors[field_name] = field_errors
        
        return errors
    
    def validate_and_raise(self, data: Dict[str, Any], context: Optional[ErrorContext] = None):
        """Validate data and raise ValidationError if invalid."""
        errors = self.validate(data)
        if errors:
            error_messages = []
            for field, field_errors in errors.items():
                error_messages.extend([f"{field}: {err}" for err in field_errors])
            
            raise ValidationError(
                message=f"Validation failed: {'; '.join(error_messages)}",
                context=context,
                recovery_suggestions=[
                    "Check your input format and try again",
                    "Ensure all required fields are provided",
                    "Verify data types match expected format"
                ]
            )


# Retry mechanism with exponential backoff
class RetryConfig:
    """Configuration for retry mechanism."""
    
    def __init__(

        self,

        max_attempts: int = 3,

        base_delay: float = 1.0,

        max_delay: float = 60.0,

        exponential_base: float = 2.0,

        jitter: bool = True,

        retryable_exceptions: List[Type[Exception]] = None

    ):
        self.max_attempts = max_attempts
        self.base_delay = base_delay
        self.max_delay = max_delay
        self.exponential_base = exponential_base
        self.jitter = jitter
        self.retryable_exceptions = retryable_exceptions or [
            ConnectionError,
            TimeoutError,
            OSError,
            # Add more retryable exceptions as needed
        ]
    
    def is_retryable(self, exception: Exception) -> bool:
        """Check if an exception is retryable."""
        return any(isinstance(exception, exc_type) for exc_type in self.retryable_exceptions)
    
    def calculate_delay(self, attempt: int) -> float:
        """Calculate delay for the given attempt number."""
        delay = self.base_delay * (self.exponential_base ** (attempt - 1))
        delay = min(delay, self.max_delay)
        
        if self.jitter:
            # Add random jitter to prevent thundering herd
            delay *= (0.5 + random.random() * 0.5)
        
        return delay


async def retry_with_backoff(

    func: Callable,

    *args,

    retry_config: RetryConfig = None,

    context: Optional[ErrorContext] = None,

    **kwargs

) -> Any:
    """Execute function with retry and exponential backoff."""
    
    if retry_config is None:
        retry_config = RetryConfig()
    
    last_exception = None
    
    for attempt in range(1, retry_config.max_attempts + 1):
        try:
            if asyncio.iscoroutinefunction(func):
                return await func(*args, **kwargs)
            else:
                return func(*args, **kwargs)
        
        except Exception as e:
            last_exception = e
            
            # Check if exception is retryable
            if not retry_config.is_retryable(e):
                # Log non-retryable error
                logger = get_logger("retry_handler")
                logger.error(f"Non-retryable error on attempt {attempt}: {e}")
                raise
            
            # Check if we have more attempts
            if attempt >= retry_config.max_attempts:
                logger = get_logger("retry_handler")
                logger.error(f"Max retry attempts ({retry_config.max_attempts}) exceeded: {e}")
                break
            
            # Calculate delay and wait
            delay = retry_config.calculate_delay(attempt)
            logger = get_logger("retry_handler")
            logger.warning(f"Attempt {attempt} failed: {e}. Retrying in {delay:.2f}s...")
            
            await asyncio.sleep(delay)
    
    # All attempts failed
    if context:
        context.additional_data = context.additional_data or {}
        context.additional_data["retry_attempts"] = retry_config.max_attempts
    
    raise ApplicationError(
        message=f"Operation failed after {retry_config.max_attempts} attempts: {str(last_exception)}",
        category=ErrorCategory.SYSTEM,
        severity=ErrorSeverity.HIGH,
        context=context,
        recovery_suggestions=[
            "Check your network connection",
            "Verify service availability",
            "Try again later",
            "Contact support if issue persists"
        ]
    ) from last_exception


# Data corruption detection
class DataCorruptionDetector:
    """Detects various forms of data corruption."""
    
    @staticmethod
    def check_file_integrity(file_path: str, expected_size: int = None) -> List[str]:
        """Check file integrity and return list of issues found."""
        issues = []
        
        try:
            import os
            
            if not os.path.exists(file_path):
                issues.append("File does not exist")
                return issues
            
            file_size = os.path.getsize(file_path)
            
            if file_size == 0:
                issues.append("File is empty")
                return issues
            
            # Check expected size if provided
            if expected_size and abs(file_size - expected_size) > expected_size * 0.1:
                issues.append(f"File size mismatch: expected ~{expected_size}, got {file_size}")
            
            # Check file permissions
            if not os.access(file_path, os.R_OK):
                issues.append("File is not readable")
            
            return issues
            
        except Exception as e:
            issues.append(f"File integrity check failed: {str(e)}")
            return issues
    
    @staticmethod
    def check_dataframe_integrity(df, filename: str = None) -> List[str]:
        """Check DataFrame integrity and return list of issues found."""
        issues = []
        
        try:
            # Check if DataFrame is empty
            if df.empty:
                issues.append("Dataset contains no data")
                return issues
            
            # Check for completely empty columns
            empty_columns = df.columns[df.isnull().all()].tolist()
            if empty_columns:
                issues.append(f"Columns contain no data: {empty_columns}")
            
            # Check for duplicate columns
            duplicate_columns = df.columns[df.columns.duplicated()].tolist()
            if duplicate_columns:
                issues.append(f"Duplicate column names found: {duplicate_columns}")
            
            # Check for suspicious data patterns
            for col in df.columns:
                # Check for columns with all identical values (except NaN)
                non_null_values = df[col].dropna()
                if len(non_null_values) > 1 and non_null_values.nunique() == 1:
                    issues.append(f"Column '{col}' contains only identical values")
                
                # Check for columns with extreme missing value rates
                missing_rate = df[col].isnull().sum() / len(df)
                if missing_rate > 0.95:
                    issues.append(f"Column '{col}' has {missing_rate:.1%} missing values")
            
            # Check memory usage
            memory_mb = df.memory_usage(deep=True).sum() / (1024 * 1024)
            if memory_mb > 1000:  # 1GB threshold
                issues.append(f"Dataset is very large ({memory_mb:.1f}MB) - may cause performance issues")
            
            return issues
            
        except Exception as e:
            issues.append(f"DataFrame integrity check failed: {str(e)}")
            return issues
    
    @staticmethod
    def detect_encoding_issues(file_content: bytes, filename: str) -> List[str]:
        """Detect text encoding issues in file content."""
        issues = []
        
        try:
            # Try different encodings
            encodings = ['utf-8', 'latin-1', 'cp1252', 'iso-8859-1']
            successful_encodings = []
            
            for encoding in encodings:
                try:
                    file_content.decode(encoding)
                    successful_encodings.append(encoding)
                except UnicodeDecodeError:
                    continue
            
            if not successful_encodings:
                issues.append("File contains invalid character encoding")
            elif len(successful_encodings) > 1:
                issues.append(f"File encoding is ambiguous (works with: {successful_encodings})")
            
            # Check for BOM (Byte Order Mark)
            if file_content.startswith(b'\xef\xbb\xbf'):
                issues.append("File contains UTF-8 BOM which may cause parsing issues")
            
            return issues
            
        except Exception as e:
            issues.append(f"Encoding detection failed: {str(e)}")
            return issues


# Graceful degradation handler
class GracefulDegradationHandler:
    """Handles graceful degradation when components fail."""
    
    def __init__(self):
        self.logger = get_logger("degradation_handler")
        self.fallback_handlers: Dict[str, Callable] = {}
        self.component_health: Dict[str, bool] = {}
        self.degraded_components: set = set()
    
    def register_fallback(self, component_name: str, fallback_handler: Callable):
        """Register a fallback handler for a component."""
        self.fallback_handlers[component_name] = fallback_handler
        self.component_health[component_name] = True
    
    def mark_component_degraded(self, component_name: str, reason: str = None):
        """Mark a component as degraded."""
        self.component_health[component_name] = False
        self.degraded_components.add(component_name)
        self.logger.warning(f"Component {component_name} marked as degraded: {reason}")
    
    def mark_component_healthy(self, component_name: str):
        """Mark a component as healthy."""
        self.component_health[component_name] = True
        if component_name in self.degraded_components:
            self.degraded_components.remove(component_name)
        self.logger.info(f"Component {component_name} restored to healthy state")
    
    async def execute_with_fallback(

        self,

        component_name: str,

        primary_func: Callable,

        *args,

        **kwargs

    ) -> Any:
        """Execute function with fallback if component is degraded."""
        
        # Check if component is healthy
        if self.component_health.get(component_name, True):
            try:
                if asyncio.iscoroutinefunction(primary_func):
                    return await primary_func(*args, **kwargs)
                else:
                    return primary_func(*args, **kwargs)
            except Exception as e:
                self.logger.error(f"Primary function failed for {component_name}: {e}")
                self.mark_component_degraded(component_name, str(e))
        
        # Use fallback if available
        if component_name in self.fallback_handlers:
            try:
                fallback_func = self.fallback_handlers[component_name]
                self.logger.info(f"Using fallback for {component_name}")
                
                if asyncio.iscoroutinefunction(fallback_func):
                    return await fallback_func(*args, **kwargs)
                else:
                    return fallback_func(*args, **kwargs)
            except Exception as e:
                self.logger.error(f"Fallback also failed for {component_name}: {e}")
                raise ApplicationError(
                    f"Both primary and fallback failed for {component_name}",
                    category=ErrorCategory.SYSTEM,
                    severity=ErrorSeverity.HIGH,
                    recovery_suggestions=[
                        "Check component health status",
                        "Restart the affected service",
                        "Contact system administrator"
                    ]
                )
        
        # No fallback available
        raise ApplicationError(
            f"Component {component_name} is degraded and no fallback available",
            category=ErrorCategory.SYSTEM,
            severity=ErrorSeverity.HIGH,
            recovery_suggestions=[
                "Wait for component to recover",
                "Check system status",
                "Contact support if issue persists"
            ]
        )
    
    def get_system_health_status(self) -> Dict[str, Any]:
        """Get overall system health status."""
        total_components = len(self.component_health)
        healthy_components = sum(1 for healthy in self.component_health.values() if healthy)
        
        return {
            "overall_health": "healthy" if len(self.degraded_components) == 0 else "degraded",
            "healthy_components": healthy_components,
            "total_components": total_components,
            "degraded_components": list(self.degraded_components),
            "health_percentage": (healthy_components / total_components * 100) if total_components > 0 else 100
        }


# Enhanced retry configuration for different scenarios
class RetryScenarios:
    """Pre-configured retry scenarios for different use cases."""
    
    @staticmethod
    def get_network_retry() -> RetryConfig:
        """Retry configuration for network operations."""
        return RetryConfig(
            max_attempts=5,
            base_delay=1.0,
            max_delay=30.0,
            exponential_base=2.0,
            jitter=True,
            retryable_exceptions=[
                ConnectionError,
                TimeoutError,
                OSError,
                # Add network-specific exceptions
            ]
        )
    
    @staticmethod
    def get_database_retry() -> RetryConfig:
        """Retry configuration for database operations."""
        return RetryConfig(
            max_attempts=3,
            base_delay=0.5,
            max_delay=10.0,
            exponential_base=2.0,
            jitter=True,
            retryable_exceptions=[
                ConnectionError,
                TimeoutError,
                # Add database-specific exceptions
            ]
        )
    
    @staticmethod
    def get_mcp_server_retry() -> RetryConfig:
        """Retry configuration for MCP server operations."""
        return RetryConfig(
            max_attempts=3,
            base_delay=2.0,
            max_delay=20.0,
            exponential_base=1.5,
            jitter=True,
            retryable_exceptions=[
                ConnectionError,
                TimeoutError,
                MCPServerError,
            ]
        )
    
    @staticmethod
    def get_file_operation_retry() -> RetryConfig:
        """Retry configuration for file operations."""
        return RetryConfig(
            max_attempts=2,
            base_delay=0.1,
            max_delay=1.0,
            exponential_base=2.0,
            jitter=False,
            retryable_exceptions=[
                OSError,
                IOError,
                PermissionError,
            ]
        )


# Circuit breaker pattern for preventing cascade failures
class CircuitBreaker:
    """Circuit breaker to prevent cascade failures."""
    
    def __init__(

        self,

        failure_threshold: int = 5,

        recovery_timeout: float = 60.0,

        expected_exception: Type[Exception] = Exception

    ):
        self.failure_threshold = failure_threshold
        self.recovery_timeout = recovery_timeout
        self.expected_exception = expected_exception
        
        self.failure_count = 0
        self.last_failure_time = None
        self.state = "closed"  # closed, open, half-open
        self.logger = get_logger("circuit_breaker")
    
    async def call(self, func: Callable, *args, **kwargs) -> Any:
        """Execute function through circuit breaker."""
        
        if self.state == "open":
            if self._should_attempt_reset():
                self.state = "half-open"
                self.logger.info("Circuit breaker moving to half-open state")
            else:
                raise ApplicationError(
                    "Circuit breaker is open - service temporarily unavailable",
                    category=ErrorCategory.SYSTEM,
                    severity=ErrorSeverity.HIGH,
                    recovery_suggestions=[
                        "Wait for service to recover",
                        "Check service health status",
                        "Try again later"
                    ]
                )
        
        try:
            if asyncio.iscoroutinefunction(func):
                result = await func(*args, **kwargs)
            else:
                result = func(*args, **kwargs)
            
            # Success - reset failure count
            self._on_success()
            return result
            
        except self.expected_exception as e:
            self._on_failure()
            raise
    
    def _should_attempt_reset(self) -> bool:
        """Check if circuit breaker should attempt to reset."""
        return (
            self.last_failure_time and
            time.time() - self.last_failure_time >= self.recovery_timeout
        )
    
    def _on_success(self):
        """Handle successful execution."""
        self.failure_count = 0
        if self.state == "half-open":
            self.state = "closed"
            self.logger.info("Circuit breaker reset to closed state")
    
    def _on_failure(self):
        """Handle failed execution."""
        self.failure_count += 1
        self.last_failure_time = time.time()
        
        if self.failure_count >= self.failure_threshold:
            self.state = "open"
            self.logger.warning(f"Circuit breaker opened after {self.failure_count} failures")


# Global instances
error_handler = ErrorHandler()
degradation_handler = GracefulDegradationHandler()


# Context manager for error handling
@asynccontextmanager
async def error_context(

    component: str,

    operation: str,

    user_id: str = None,

    session_id: str = None,

    additional_data: Dict[str, Any] = None

):
    """Context manager for consistent error handling."""
    context = ErrorContext(
        user_id=user_id,
        session_id=session_id,
        component=component,
        operation=operation,
        additional_data=additional_data
    )
    
    try:
        yield context
    except Exception as e:
        await error_handler.handle_error(e, context)
        raise


# Decorator for automatic error handling
def handle_errors(

    component: str,

    operation: str = None,

    retry_config: RetryConfig = None,

    circuit_breaker: CircuitBreaker = None

):
    """Decorator for automatic error handling with retry and circuit breaker."""
    def decorator(func):
        async def wrapper(*args, **kwargs):
            op_name = operation or func.__name__
            
            # Extract user context if available
            user_id = None
            for arg in args:
                if hasattr(arg, 'user_id'):
                    user_id = arg.user_id
                    break
            
            context = ErrorContext(
                user_id=user_id,
                component=component,
                operation=op_name
            )
            
            async def execute():
                if asyncio.iscoroutinefunction(func):
                    return await func(*args, **kwargs)
                else:
                    return func(*args, **kwargs)
            
            try:
                # Apply circuit breaker if provided
                if circuit_breaker:
                    if retry_config:
                        return await retry_with_backoff(
                            circuit_breaker.call,
                            execute,
                            retry_config=retry_config,
                            context=context
                        )
                    else:
                        return await circuit_breaker.call(execute)
                
                # Apply retry if provided
                elif retry_config:
                    return await retry_with_backoff(
                        execute,
                        retry_config=retry_config,
                        context=context
                    )
                
                # Direct execution
                else:
                    return await execute()
                    
            except Exception as e:
                await error_handler.handle_error(e, context)
                raise
        
        return wrapper
    return decorator