import json
import os
from typing import List
from dep_shield.models import Dependency, Ecosystem
from dep_shield.parsers.base import BaseParser

class NPMParser(BaseParser):
    def can_handle(self, file_path: str) -> bool:
        return file_path.endswith("package.json")

    def parse(self, file_path: str) -> List[Dependency]:
        deps = []
        try:
            with open(file_path, "r") as f:
                data = json.load(f)
                
            # Check both dependencies and devDependencies
            all_deps = {**data.get("dependencies", {}), **data.get("devDependencies", {})}
            
            for name, version in all_deps.items():
                # Clean generic semver chars for basic matching (^1.0.0 -> 1.0.0)
                # Real implementation needs full semver resolution
                clean_version = version.replace("^", "").replace("~", "")
                
                deps.append(Dependency(
                    name=name,
                    version=clean_version,
                    ecosystem=Ecosystem.NPM,
                    source_file=os.path.basename(file_path)
                ))
        except json.JSONDecodeError:
            pass # Fail safely
        return deps