import requests
from typing import List, Optional
from dep_shield.models import Dependency, Vulnerability, Severity, Ecosystem

OSV_API_URL = "https://api.osv.dev/v1/query"

class OSVProvider:
    def check(self, dependency: Dependency) -> List[Vulnerability]:
        payload = {
            "version": dependency.version,
            "package": {
                "name": dependency.name,
                "ecosystem": dependency.ecosystem.value
            }
        }
        
        try:
            response = requests.post(OSV_API_URL, json=payload, timeout=5)
            if response.status_code != 200:
                return []
                
            data = response.json()
            vulns = []
            
            for v in data.get("vulns", []):
                # 1. Normalize Severity
                sev_level = Severity.UNKNOWN
                if "database_specific" in v and "severity" in v["database_specific"]:
                     sev_str = v["database_specific"]["severity"].upper()
                     if "HIGH" in sev_str: sev_level = Severity.HIGH
                     elif "CRIT" in sev_str: sev_level = Severity.CRITICAL
                     elif "MODERATE" in sev_str: sev_level = Severity.MODERATE
                     elif "LOW" in sev_str: sev_level = Severity.LOW
                
                # 2. Extract "Fixed" Version
                fixed_version = None
                for affected in v.get("affected", []):
                    if affected.get("package", {}).get("name") == dependency.name:
                        for rng in affected.get("ranges", []):
                            for event in rng.get("events", []):
                                if "fixed" in event:
                                    fixed_version = event["fixed"]
                                    break
                
                vulns.append(Vulnerability(
                    id=v.get("id"),
                    summary=v.get("summary", "No summary available"),
                    details=v.get("details", "")[:200] + "...", 
                    severity=sev_level,
                    fixed_in=fixed_version, # <--- NEW FIELD POPULATED
                    references=[ref.get("url") for ref in v.get("references", [])]
                ))
            return vulns
            
        except requests.RequestException:
            return []