import json
import yaml
import toml
from typing import Dict, List
from .vulnerability_checker import VulnerabilityChecker
from .cve_data_fetcher import CVEDataFetcher

class DependencyScanner:
    def __init__(self, cve_data_fetcher: CVEDataFetcher):
        self.vulnerability_checker = VulnerabilityChecker(cve_data_fetcher)

    async def scan_dependencies(self, file_path: str) -> Dict[str, List[Dict]]:
        dependencies = self._parse_dependency_file(file_path)
        vulnerabilities = {}

        for package, version in dependencies.items():
            vulns = await self.vulnerability_checker.check_vulnerabilities(package, version)
            if vulns:
                vulnerabilities[package] = vulns

        return vulnerabilities

    def _parse_dependency_file(self, file_path: str) -> Dict[str, str]:
        if file_path.endswith('.txt'):
            return self._parse_requirements_txt(file_path)
        elif file_path.endswith('.json'):
            return self._parse_package_json(file_path)
        elif file_path.endswith('.yaml') or file_path.endswith('.yml'):
            return self._parse_yaml_file(file_path)
        elif file_path.endswith('.toml'):
            return self._parse_toml_file(file_path)
        else:
            raise ValueError(f"Unsupported file format: {file_path}")

    def _parse_requirements_txt(self, file_path: str) -> Dict[str, str]:
        dependencies = {}
        with open(file_path, 'r') as f:
            for line in f:
                if '==' in line:
                    package, version = line.strip().split('==')
                    dependencies[package] = version
        return dependencies

    def _parse_package_json(self, file_path: str) -> Dict[str, str]:
        with open(file_path, 'r') as f:
            data = json.load(f)
        return {**data.get('dependencies', {}), **data.get('devDependencies', {})}

    def _parse_yaml_file(self, file_path: str) -> Dict[str, str]:
        with open(file_path, 'r') as f:
            data = yaml.safe_load(f)
        return data.get('dependencies', {})

    def _parse_toml_file(self, file_path: str) -> Dict[str, str]:
        with open(file_path, 'r') as f:
            data = toml.load(f)
        return data.get('dependencies', {})
