from typing import Optional
import requests


def tinypng_compress(img_url: str) -> Optional[bytes]:
    """
    Fetch the original webp image and compress it using tinypng.

    Parameters
    ----------
    img_url : str

    Returns
    -------
    bytes or None
        Binary data of the compressed image.
    """
    if img_url is None or not img_url:
        return None

    headers = {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:83.0) Gecko/20100101 Firefox/83.0",
        "Accept": "*/*",
        "Accept-Language": "en-US,en;q=0.5",
        "Content-Type": "image/webp",
        "Origin": "https://tinypng.com",
        "DNT": "1",
        "Connection": "keep-alive",
        "Referer": "https://tinypng.com/",
        "TE": "Trailers",
    }

    # download the input image
    in_img = requests.get(img_url)
    data = in_img.content

    # post request to compress the img
    res = requests.post("https://tinypng.com/web/shrink", headers=headers, data=data)

    # download the compressed img
    out_img_url = res.json()["output"]["url"]
    out_img = requests.get(out_img_url)
    return out_img.content