import base64
import json
import os

from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec

# A signer key file with hex keys, the format the console's
# Users page downloads.
with open(os.environ["SIGNER_KEY_FILE"]) as f:
    signer = json.load(f)
key = ec.derive_private_key(
    int(signer["signer_private_key"], 16), ec.SECP256R1()
)
public_key = (
    key.public_key()
    .public_bytes(
        serialization.Encoding.X962,
        serialization.PublicFormat.CompressedPoint,
    )
    .hex()
)


def stamp(payload: str) -> str:
    signature = key.sign(
        payload.encode(), ec.ECDSA(hashes.SHA256())
    )
    envelope = json.dumps(
        {
            "publicKey": public_key,
            "signature": signature.hex(),
            "scheme": "SIGNATURE_SCHEME_TK_API_P256",
        }
    )
    return (
        base64.urlsafe_b64encode(envelope.encode())
        .decode()
        .rstrip("=")
    )
