import requests
import os
from urllib.parse import urlparse

def download_file_to_directory(url, download_dir):
    """
    Downloads a file from a URL to a specified directory.

    Args:
        url (str): The URL of the file to download.
        download_dir (str): The explicit directory path to save the file in.
    """
    try:
        # IMPORTANT: Ensure the target directory exists.
        # The exist_ok=True flag prevents an error if the directory already exists.
        print(f"Ensuring download directory exists: {download_dir}")
        os.makedirs(download_dir, exist_ok=True)
        
        # Parse the URL to get the filename
        parsed_url = urlparse(url)
        filename = os.path.basename(parsed_url.path)

        if not filename:
            filename = "downloaded_file" # Default filename if not found in URL

        # Create the full path to save the file
        destination_path = os.path.join(download_dir, filename)

        print(f"Attempting to download from: {url}")
        
        # Make the request to the URL
        response = requests.get(url, allow_redirects=True, timeout=15)
        
        # Check if the request was successful (HTTP status code 200)
        response.raise_for_status() 

        # Write the content to the file in binary mode
        with open(destination_path, 'wb') as f:
            f.write(response.content)

        print(f"\nSuccess! File downloaded to: {destination_path}")
        print("Please review the file manually before moving or executing it.")

    except requests.exceptions.RequestException as e:
        print(f"An error occurred during download: {e}")
    except IOError as e:
        print(f"An error occurred while writing the file: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
    # The URL of the Palo Alto Networks WildFire test file
    test_file_url = "https://wildfire.paloaltonetworks.com/publicapi/test/pe"
    
    # --- EDIT THIS LINE ---
    # Set your desired explicit download path here for the cron job.
    #
    # WARNING: For security, avoid using web server directories (e.g., /var/www/html)
    # or other system-critical paths. A dedicated directory in /tmp/, /var/log/,
    # or /opt/ is generally a safer choice for automated tasks.
    explicit_download_path = "/var/www/html/test malware/pancar"

    download_file_to_directory(test_file_url, explicit_download_path)

