import os
from typing import List
from dep_shield.models import Dependency, Ecosystem
from dep_shield.parsers.base import BaseParser
from packaging.requirements import Requirement

class PyPIParser(BaseParser):
    def can_handle(self, file_path: str) -> bool:
        return file_path.endswith("requirements.txt")

    def parse(self, file_path: str) -> List[Dependency]:
        deps = []
        with open(file_path, "r") as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith("#"):
                    continue
                try:
                    req = Requirement(line)
                    # Simple resolution: take the first specific version found
                    # In a real tool, we would resolve ranges.
                    version = "0.0.0" 
                    if req.specifier:
                        # Extract exact version if pinned (==)
                        for spec in req.specifier:
                            if spec.operator == "==":
                                version = spec.version
                                break
                    
                    deps.append(Dependency(
                        name=req.name,
                        version=version,
                        ecosystem=Ecosystem.PYPI,
                        source_file=os.path.basename(file_path)
                    ))
                except Exception:
                    continue # Skip invalid lines safely
        return deps