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


def delete_remote_file(host, user, password, filename):
    """
    Delete a file from a remote FTP server.

    Attempts deletion using the provided filename; if that fails (as sometimes
    happens with ENA), it retries using the full path under `/webin-inbox/`.

    Parameters
    ----------
    host : str
        FTP server hostname.
    user : str
        Username for FTP authentication.
    password : str
        Password for FTP authentication.
    filename : str
        Name of the file to delete. Can be a simple filename or a path.

    Raises
    ------
    RuntimeError
        If the file cannot be deleted using either the given path or the
        fallback ENA path (`/webin-inbox/<filename>`).

    """
    ftp = FTP(host, timeout=60)  # noqa:S321 # nosec: B321
    ftp.login(user, password)
    try:
        ftp.delete(filename)
    except error_perm as e:
        # ENA sometimes requires full path
        try:
            ftp.delete(f"/webin-inbox/{filename}")
        except error_perm:
            ftp.quit()
            raise RuntimeError(f"Failed to delete remote file {filename}: {e}")
    ftp.quit()
