"""The auth module provides tools to authenticate agents and scripts with the Sherlock API."""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/02_auth.ipynb.

# %% auto 0
__all__ = ['authenticate']

# %% ../nbs/02_auth.ipynb 3
import httpx
from cryptography.hazmat.primitives.asymmetric import ed25519

from .crypto import *

# %% ../nbs/02_auth.ipynb 9
def _handle_response(r):
    "Process response: raise for status and return json if possible."
    r.raise_for_status()
    try: return r.json()
    except: return r

def _get_challenge(pub_key: str, # public key
                   base_url: str = "https://api.sherlockdomains.com"): # base url
    "Get authentication challenge for a public key"
    r = httpx.post(f"{base_url}/api/v0/auth/challenge", json={"public_key": pub_key})
    return _handle_response(r)['challenge']

# %% ../nbs/02_auth.ipynb 13
def _sign_challenge(pk: ed25519.Ed25519PrivateKey, 
                    c: str): # challenge
    "Sign a challenge with a private key"
    return pk.sign(bytes.fromhex(c)).hex()

# %% ../nbs/02_auth.ipynb 16
def _submit_challenge(pub: str, # public key
                      c: str, # challenge
                      sig: str, # signature
                      base_url: str = "https://api.sherlockdomains.com"): # base url
    "Submit a challenge and signature to the server to get access and refresh tokens"
    r = httpx.post(f"{base_url}/api/v0/auth/login", json={
        "public_key": pub,
        "challenge": c,
        "signature": sig
    })
    r = _handle_response(r)
    return r['access'], r['refresh']

# %% ../nbs/02_auth.ipynb 19
def authenticate(priv: ed25519.Ed25519PrivateKey, # private key
                 base_url: str = "https://api.sherlockdomains.com"): # base url
    "Authenticate with the server and return access and refresh tokens"
    pub = priv.public_key().public_bytes_raw().hex()
    c = _get_challenge(pub, base_url)
    sig = _sign_challenge(priv, c)
    return _submit_challenge(pub, c, sig, base_url)
