"""
Practice: what the Inspector did for you, step by step, against the acme-crm-mcp demo:
follow a 401 to the metadata, decide how a client can get a token, and read a token's claims.

Fill in the four TODOs, then run the tests:
    pytest test_inspector_practice.py        (locally)
or press "Run tests" on the chapter page.
"""
import base64
import json
import re


def resource_metadata_url(www_authenticate: str) -> str | None:
    """From a 401's WWW-Authenticate header, return the resource_metadata URL, or None.
    e.g.  Bearer resource_metadata="http://localhost:8787/.well-known/oauth-protected-resource", error="invalid_token"

    TODO 1
    """
    return None


def how_to_get_a_token(as_metadata: dict) -> str:
    """From authorization-server metadata, decide how a client can get a token:
      - "browser sign-in"     if it has an authorization_endpoint AND "code" is in response_types_supported
      - "client credentials"  else, if "client_credentials" is in grant_types_supported
      - "none"                otherwise

    TODO 2
    """
    return ""


def decode_claims(token: str) -> dict:
    """The claims (the middle part of a JWT), base64url-decoded and parsed as JSON. Padding may be
    missing: add "=" until the length is a multiple of 4. This is decoding, not verifying: anyone
    can do it, and it proves nothing about who issued the token.

    TODO 3
    """
    return {}


def token_problems(claims: dict, now: int, resource: str, needed_scope: str) -> list[str]:
    """Why this token won't work for a call that needs `needed_scope` on `resource`, in this order:
      - "no tenant"          if there's no org_id claim
      - "wrong audience"     if aud != resource
      - "expired"            if exp <= now
      - "missing <scope>"    if needed_scope isn't in the space-separated scope claim
    An empty list means the claims look right. (The server still checks the signature and issuer.)

    TODO 4
    """
    return []
