import requests


def submit_task(task: dict, username: str, password: str) -> str:
    """
    Submits a task using the AppEEARS API.

    Parameters
    ----------
    task:      dictionary following the AppEEARS API task object format
    username:  Earthdata username
    password:  Earthdata password

    Returns
    -------
    Task ID

    Notes
    -----
    For more information about the task object convention and all the
    properties that can be specified, check the documentation:
    https://lpdaacsvc.cr.usgs.gov/appeears/api/#task-object
    """
    api_url = "https://lpdaacsvc.cr.usgs.gov/appeears/api"

    try:
        # get authorization token and build headers
        r = requests.post(f"{api_url}/login", auth=(username, password))
        r.raise_for_status()
        token = r.json()["token"]
        headers = {"Authorization": f"Bearer {token}"}

        # submit the task and logout to dispose of the authentication
        r = requests.post(f"{api_url}/task", json=task, headers=headers)
        requests.post(f"{api_url}/logout", headers=headers)

        return r.json()["task_id"]

    except requests.HTTPError as err:
        raise Exception(f"Error submitting task. {err}")