import requests
from typing import Optional
from datetime import datetime


def get_latest_block(alchemy_request_url: str, session: requests.Session) -> Optional[str]:
    """Get the latest block on the network.

    Computing the latest block and using it throughout other methods insures
    for correctness if the network moves to another block while the script is running.

    [Alchemy API docs](https://docs.alchemy.com/alchemy/apis/ethereum/eth-blocknumber)

    Args:
        alchemy_request_url: Request URL used to query Alchemy's API
        session: Session object used for sharing state across requests

    Returns:
        Latest block, None if unsuccessful. If latest block returns None
        due to a network error, the "latest" block is taken at time of API call.
    """
    payload = {
        "jsonrpc": "2.0",
        "id": 0,
        "method": "eth_blockNumber",
        "params": [],
    }

    try:
        response = session.post(alchemy_request_url, json=payload)
        response.raise_for_status()

        latest_block = response.json()['result']

        print(f"Latest block as of time {str(datetime.now())} is {latest_block}")
        return latest_block
    except requests.exceptions.HTTPError as e:
        print(e)
        return None