"""Google Sign-In for apps hosted on SolveIt"""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/05_solve_auth.ipynb.

# %% auto #0
__all__ = ['solve_signin_rt', 'SolveSigninError', 'setup_solve_signin', 'sub_from_signin']

# %% ../nbs/05_solve_auth.ipynb #3ab8149a
import os, json, httpx, jwt

# %% ../nbs/05_solve_auth.ipynb #b8dad395
class SolveSigninError(Exception): pass

_AUTH_URL = 'https://auth.solve.it.com/request_signin'

def _key(): return os.environ['AAI_USER_KEY']
def _app_url(port): return f'https://{json.loads(os.environ["PUBLIC_DOMAINS"])[str(port)]}.solve.it.com'

# %% ../nbs/05_solve_auth.ipynb #b8c32209
solve_signin_rt = '/solve_signin'
def setup_solve_signin(app, port=8000, callback_rt='/signin_completed'):
    "Add /solve_signin route to `app` that redirects to Google via SolveIt auth"
    from starlette.responses import RedirectResponse
    callback = _app_url(port) + callback_rt
    @app.route(solve_signin_rt)
    def solve_signin():
        r = httpx.post(_AUTH_URL, headers={'Authorization': _key()}, json={'callback_url': callback})
        return RedirectResponse(r.json()['signin_url'])

# %% ../nbs/05_solve_auth.ipynb #69a137b0
def sub_from_signin(session, signin_reply):
    "Decode signin JWT, validate, and return Google sub ID. Raises SolveSigninError on failure."
    try:
        payload = jwt.decode(signin_reply, _key(), algorithms=['HS256'])
        if 'err' in payload: raise SolveSigninError(payload['err'])
        return str(payload['sub'])
    except jwt.PyJWTError as e: raise SolveSigninError(f'JWT validation failed: {e}') from e
