import hashlib


def generate_unique_filename(dicom_header, extension=".dcm"):
    """
    Generates and returns a unique filename based on the Patient ID and
    internal unique idientifier contained in the DICOM header metadata.

    Unique names are created in the following format:

        ```text {PatientID}_{InstanceHash}{Extension}
        ```
    where `{PatientID}` is the `Patient ID` field from the DICOM header,
    `{InstanceHash}` is the initial 16 characters of the hexadecimal encoding
    of the *sha-1* hash of the `SOP Instance UID` field from the DICOM header,
    and `{Extension}` is the file extension e.g. `.dcm` for DICOM files and
    `.png` for PNG format.
    """
    patient_id = dicom_header.PatientID
    sop_instance_uid = dicom_header.SOPInstanceUID
    instance_hash = hashlib.sha1(sop_instance_uid.encode("utf-8")).hexdigest()[:16]
    return "{}_{}{}".format(patient_id, instance_hash, extension)