import requests

def check_malware(url, API_KEY):
    """Check if a website is malicious using Google Safe Browsing API."""
    api_url = "https://safebrowsing.googleapis.com/v4/threatMatches:find"
    headers = {"Content-Type": "application/json"}
    payload = {
        "client": {
            "clientId": "CyberSentinel",
            "clientVersion": "0.2.0"
        },
        "threatInfo": {
            "threatTypes": ["MALWARE", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE"],
            "platformTypes": ["ANY_PLATFORM"],
            "threatEntryTypes": ["URL"],
            "threatEntries": [{"url": url}]
        }
    }

    try:
        response = requests.post(api_url, json=payload, headers=headers, params={"key": API_KEY})
        if response.status_code == 200:
            data = response.json()
            if "matches" in data and len(data["matches"]) > 0:
                return True  # The site is flagged as malicious
            return False  # No matches found, site is safe
        else:
            print(f"❌ API Request Failed! Status Code: {response.status_code}")
            return False
    except requests.RequestException as e:
        print(f"❌ Error connecting to Safe Browsing API: {e}")
        return False
