"""
FTP-related utility functions for ENA submissions.

Provides fast methods to interact with remote FTP/FTPS servers,
avoiding slow directory listings. Ideal for checking large file
existence and size before uploads.
"""

# ENA requires FTP, SFTP/FTPS is not supported
import ftplib  # nosec: B402


def get_remote_file_size(host: str, user: str, password: str, filename: str):
    """
    Quickly get the size of a remote file on an FTPS server.

    This function uses the FTP SIZE command, which is much faster than
    performing a directory listing.

    Parameters
    ----------
    host : str
        FTPS server hostname (e.g., "webin.ebi.ac.uk")
    user : str
        FTP username
    password : str
        FTP password
    filename : str
        Path to the remote file

    Returns
    -------
    int or None
        Size of the remote file in bytes if it exists; None otherwise.

    """
    try:
        # Open a secure FTP connection
        with ftplib.FTP_TLS(host) as ftp:  # noqa: S321
            # Authenticate
            ftp.login(user=user, passwd=password)
            # Secure the data channel (required by ENA)
            ftp.prot_p()
            try:
                # Directly query remote file size (very fast)
                return ftp.size(filename)
            except ftplib.error_perm as e:
                # 550 = file not found
                if "550" in str(e):
                    return None
                raise
    except Exception:
        # Return None for any connection or protocol issues
        return None
