import time
import json
import os
import urllib.request
import urllib.parse

try:
    import jwt
    from cryptography.hazmat.primitives import serialization
except ImportError:
    print("Error: Missing dependencies. Run: pip3 install PyJWT cryptography")
    exit(1)

base_path = os.path.expanduser("~/.hammerspoon/")
key_file = os.path.join(base_path, "google-key.json")

if not os.path.exists(key_file):
    print(f"Error: {key_file} not found")
    exit(1)

with open(key_file) as f:
    key_data = json.load(f)

iat = int(time.time())
exp = iat + 3600
payload = {
    'iss': key_data['client_email'],
    'sub': key_data['client_email'],
    'aud': 'https://oauth2.googleapis.com/token',
    'iat': iat,
    'exp': exp,
    'scope': 'https://www.googleapis.com/auth/monitoring.read'
}

try:
    # Sign the JWT using the private key from JSON
    signed_jwt = jwt.encode(payload, key_data['private_key'], algorithm='RS256')

    # Exchange for Access Token
    url = 'https://oauth2.googleapis.com/token'
    params = urllib.parse.urlencode({
        'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion': signed_jwt
    }).encode('utf-8')

    req = urllib.request.Request(url, data=params, method='POST')
    with urllib.request.urlopen(req) as response:
        res_data = json.loads(response.read().decode('utf-8'))
        print(res_data['access_token'])
except Exception as e:
    print(f"Auth Error: {str(e)}")
    exit(1)