import requests
import sys

def download_file(url, local_filename=None):
    """
    Downloads a file from a URL and saves it locally.

    Args:
        url (str): The URL of the file to download.
        local_filename (str, optional): The local path to save the file.
                                        If not provided, the filename from the URL will be used.
    """
    if local_filename is None:
        local_filename = url.split('/')[-1]
        if not local_filename:
            print("Could not determine filename from URL. Please provide one.")
            return

    try:
        # It's good practice to stream large files
        with requests.get(url, stream=True) as r:
            # Raise an exception for bad status codes (4xx or 5xx)
            r.raise_for_status()
            
            total_size = int(r.headers.get('content-length', 0))
            block_size = 8192 # 8 Kilobytes
            
            print(f"Downloading {local_filename} from {url}")
            
            with open(local_filename, 'wb') as f:
                downloaded_size = 0
                for chunk in r.iter_content(chunk_size=block_size):
                    f.write(chunk)
                    downloaded_size += len(chunk)
                    # Calculate and display progress
                    progress = downloaded_size / total_size * 100
                    sys.stdout.write(f"\rProgress: {progress:.2f}%")
                    sys.stdout.flush()

        print(f"\nSuccessfully downloaded and saved to {local_filename}")

    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    # This script is now configured to download a specific benign test file
    # from Palo Alto Networks Wildfire to test security controls.
    file_url = "https://wildfire.paloaltonetworks.com/publicapi/test/pe"
    local_name = "wildfire_test_pe.exe" # Saving as .exe for clarity

    download_file(file_url, local_name)

