import requests


def get_token(session: requests.Session, endpoint: str, username: str, password: str) -> str:
    """
    Getting a token which can be used to issue write statements is a multistep process:
        1. Obtain a login token by logging in (this method might be deprecated soon)
        2. Use the login token to issue the log-in command and retrieve a session token
        3. Use the session token to issue a CSRF token request
    """
    session_token = (
        session.get(
            url=endpoint,
            params={"action": "query", "meta": "tokens", "type": "login", "format": "json"},
        )
        .json()
        .get("query", {})
        .get("tokens", {})
        .get("logintoken")
    )

    login_result = session.post(
        url=endpoint,
        data={
            "action": "login",
            "lgname": username,
            "lgpassword": password,
            "lgtoken": session_token,
            "format": "json",
        },
    ).json()
    assert login_result.get("login", {}).get("result") == "Success", f"Login failed: {login_result}"

    csrf_token = (
        session.get(url=endpoint, params={"action": "query", "meta": "tokens", "format": "json"})
        .json()
        .get("query", {})
        .get("tokens", {})
        .get("csrftoken")
    )
    assert csrf_token is not None, "Error retrieving CSRF token"

    return csrf_token