#!/usr/bin/env bash
# Mint a dev JWT for the ward gateway API (issuer vigilcare-gateway).
# Usage: mint-gateway-jwt.sh [username] [clinical_role]
# Prints the token to stdout.

set -euo pipefail

USERNAME="${1:-nurse.demo}"
ROLE="${2:-NURSE}"

python3 - "$USERNAME" "$ROLE" <<'PY'
import json, hmac, hashlib, base64, datetime, os, sys

def b64url(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).decode().rstrip("=")

username = sys.argv[1]
role = sys.argv[2].upper()
secret = os.environ.get(
    "GATEWAY_JWT_SECRET", "dev-signing-key-minimum-32-bytes-long!!").encode()
user_id = os.environ.get(
    "GATEWAY_JWT_USER_ID", "11111111-1111-1111-1111-111111111111")
display = os.environ.get("GATEWAY_JWT_DISPLAY_NAME", "Demo Nurse")

header = b64url(json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode())
now = int(datetime.datetime.now(datetime.timezone.utc).timestamp())
payload = {
    "iss": "vigilcare-gateway",
    "aud": "vigilcare-dashboard",
    "exp": now + 86400,
    "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": user_id,
    "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": username,
    "display_name": display,
    "clinical_role": role,
}
payload_b64 = b64url(json.dumps(payload, separators=(",", ":")).encode())
signing_input = f"{header}.{payload_b64}".encode()
sig = b64url(hmac.new(secret, signing_input, hashlib.sha256).digest())
print(f"{header}.{payload_b64}.{sig}", end="")
PY
