#!/usr/bin/python

from ftplib import FTP
import os
from datetime import datetime, date, time, timedelta
import time

def download_from_public_ftp(server, remote_dir, filename, local_dir):
    """
    Downloads a file from a public FTP server.
    
    :param server: The FTP server address (e.g., 'ftp.ncbi.nlm.nih.gov')
    :param remote_dir: The directory path on the server (e.g., 'pub/README')
    :param filename: The name of the file to download
    :param local_dir: The local folder where the file should be saved
    """
    # Combine local directory and filename
    local_filepath = os.path.join(local_dir, filename)
    
    print(f"Connecting to {server}...")
    # Establish a connection using a context manager to ensure proper closure
    with FTP(server) as ftp:
        # Log in anonymously (uses 'anonymous' as user, and a dummy email as password)
        ftp.login(user='anonymous', passwd='guest')
        print("Logged in successfully.")
        
        # Navigate to the target directory on the server
        if remote_dir:
            ftp.cwd(remote_dir)
            print(f"Changed directory to: {remote_dir}")
        
        print(f"Downloading '{filename}'...")
        # Open the local file in write-binary ('wb') mode
        with open(local_filepath, 'wb') as local_file:
            # RETR is the standard FTP command to retrieve a copy of a file
            ftp.retrbinary(f"RETR {filename}", local_file.write)
            
    print(f"Download complete! File saved to: {local_filepath}")

if __name__ == "__main__":
    FTP_SERVER = "ftp.swpc.noaa.gov"
    REMOTE_DIRECTORY = "pub/indices/events"
    now = datetime.utcnow() - timedelta(1,0,0,0,0,0,0) # days, s, us, ms, m, h, w offset (get previous day's log file)
    fdate=now.strftime("%Y%m%d")
    fyear=now.strftime("%Y")
    os.makedirs(fyear, exist_ok=True)
    LOCAL_DIRECTORY = fyear
    FILE_TO_DOWNLOAD = fdate + "events.txt"
    download_from_public_ftp(FTP_SERVER, REMOTE_DIRECTORY, FILE_TO_DOWNLOAD, LOCAL_DIRECTORY)
