import requests

# Function to search for CVEs related to a given service name and version using the cve.circl.lu API
# service_name: The name of the service (e.g., 'apache', 'nginx', 'openssh')
# version: The version string of the service (e.g., '2.4.49')
def search_cves(service_name, version=None):
    """
    Searches the cve.circl.lu API for CVEs related to the specified service and version.
    Args:
        service_name (str): The name of the service/software to search for.
        version (str, optional): The version of the service/software.
    Returns:
        list: A list of dictionaries, each containing CVE details (id, summary, references, etc.).
    """
    # Construct the search query
    if version:
        query = f"{service_name} {version}"
    else:
        query = service_name

    # API endpoint for searching CVEs by keyword
    url = f"https://cve.circl.lu/api/search/{query}"

    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()  # Raise an error for bad responses
        data = response.json()
        # The API returns a dictionary with a 'results' key containing a list of CVEs
        cves = data.get('results', [])
        # For each CVE, extract relevant fields
        cve_list = []
        for cve in cves:
            cve_list.append({
                'id': cve.get('id'),
                'summary': cve.get('summary'),
                'cvss': cve.get('cvss'),
                'references': cve.get('references'),
                'published': cve.get('Published'),
            })
        return cve_list
    except requests.RequestException as e:
        print(f"Error querying CVE API: {e}")
        return []
    except Exception as e:
        print(f"Unexpected error: {e}")
        return []

# Example usage (uncomment to test directly)
# if __name__ == "__main__":
#     service = "apache"
#     version = "2.4.49"
#     cves = search_cves(service, version)
#     for cve in cves:
#         print(f"{cve['id']}: {cve['summary']}") 