import logging
from typing import Dict, Any, List
import os

logger = logging.getLogger(__name__)

class ConfigValidator:
    """설정 파일 검증"""
    
    @staticmethod
    def validate_evaluation_config(config: Dict[str, Any]) -> List[str]:
        """평가 설정 검증"""
        errors = []
        
        # 임계값 검증
        thresholds = config.get('EVALUATION_THRESHOLDS', {})
        for metric, threshold in thresholds.items():
            if not isinstance(threshold, (int, float)):
                errors.append(f"Invalid threshold type for {metric}: {type(threshold)}")
            elif threshold <= 0:
                errors.append(f"Invalid threshold value for {metric}: {threshold}")
        
        # 가중치 검증
        weights = config.get('METRIC_WEIGHTS', {})
        total_weight = sum(weights.values())
        if abs(total_weight - 1.0) > 0.01:
            errors.append(f"Metric weights sum to {total_weight}, should be 1.0")
        
        # 파일 경로 검증
        data_paths = config.get('DATA_PATHS', {})
        for path_name, path_value in data_paths.items():
            if not os.path.exists(path_value):
                errors.append(f"Path does not exist for {path_name}: {path_value}")
        
        return errors
    
    @staticmethod
    def validate_and_fix_config(config: Dict[str, Any]) -> Dict[str, Any]:
        """설정 검증 및 자동 수정"""
        errors = ConfigValidator.validate_evaluation_config(config)
        
        if errors:
            logger.warning(f"Config validation errors found: {errors}")
            
            # 자동 수정 시도
            fixed_config = config.copy()
            
            # 임계값 자동 조정
            if 'EVALUATION_THRESHOLDS' in fixed_config:
                for metric, threshold in fixed_config['EVALUATION_THRESHOLDS'].items():
                    if threshold <= 0:
                        # 기본값으로 설정
                        default_thresholds = {
                            'chamfer_distance': 0.1,
                            'emd': 0.15,
                            'class_accuracy': 0.8
                        }
                        fixed_config['EVALUATION_THRESHOLDS'][metric] = default_thresholds.get(metric, 0.1)
                        logger.info(f"Auto-fixed threshold for {metric}")
        
        return fixed_config
