from typing import Optional
import requests


def get_def_tenant_id(sub_id: str) -> Optional[str]:
    """
    Get the tenant ID for a subscription.

    Parameters
    ----------
    sub_id : str
        Subscription ID

    Returns
    -------
    Optional[str]
        TenantID or None if it could not be found.

    Notes
    -----
    This function returns the tenant ID that owns the subscription.
    This may not be the correct ID to use if you are using delegated
    authorization via Azure Lighthouse.

    """
    get_tenant_url = (
        "https://management.azure.com/subscriptions/{subscriptionid}"
        + "?api-version=2015-01-01"
    )
    resp = requests.get(get_tenant_url.format(subscriptionid=sub_id))
    # Tenant ID is returned in the WWW-Authenticate header/Bearer authorization_uri
    www_header = resp.headers.get("WWW-Authenticate")
    if not www_header:
        return None
    hdr_dict = {
        item.split("=")[0]: item.split("=")[1].strip('"')
        for item in www_header.split(", ")
    }
    tenant_path = hdr_dict.get("Bearer authorization_uri", "").split("/")
    return tenant_path[-1] if tenant_path else None