from pydantic import BaseModel, Field
from pathlib import Path
from typing import Dict, List
import yaml


class LanguageConfig(BaseModel):
    """Configuration for a specific programming language"""
    extensions: List[str]
    security_rules: List[str]


class CodeAnalysisSettings(BaseModel):
    """Pydantic Settings for scanner configuration loaded from YAML"""

    # Core settings
    timeout_seconds: int = Field(default=120, description="security scan timeout in seconds")
    rules_base_paths: List[str] = Field(
        default_factory=lambda: ["../rules/custom-rules"],
        description="Base paths for analysis rules"
    )

    # Language configurations
    languages: Dict[str, LanguageConfig] = Field(default_factory=dict)

    @classmethod
    def load_from_yaml(cls, yaml_file: str = "code_analysis_rules.yaml") -> "CodeAnalysisSettings":
        """Load settings from YAML configuration file"""
        config_dir = Path(__file__).parent
        yaml_path = config_dir / yaml_file

        if not yaml_path.exists():
            raise FileNotFoundError(f"Configuration file not found: {yaml_path}")

        with open(yaml_path, 'r') as f:
            yaml_config = yaml.safe_load(f)

        # Parse language configurations
        languages = {}
        if 'languages' in yaml_config:
            for lang_name, lang_config in yaml_config['languages'].items():
                languages[lang_name] = LanguageConfig(**lang_config)

        # Support both old (single path) and new (multiple paths) config formats
        rules_paths = yaml_config.get('rules_base_paths')
        if rules_paths is None:
            # Fallback to old single-path format for backwards compatibility
            single_path = yaml_config.get('rules_base_path', "../rules/custom-rules")
            rules_paths = [single_path]

        return cls(
            timeout_seconds=yaml_config.get('timeout_seconds', 120),
            rules_base_paths=rules_paths,
            languages=languages
        )


# Global settings instance - loaded from YAML
code_analysis_settings = CodeAnalysisSettings.load_from_yaml()