import globus_sdk
import datetime
import time
import os
from dotenv import load_dotenv


load_dotenv()  # take environment variables from .env file
GLOBUS_ID = os.getenv("GLOBUS_ID")
GLOBUS_SECRET = os.getenv("GLOBUS_SECRET")

print ("Using Globus ID: ", GLOBUS_ID)

# Create a confidential client
client = globus_sdk.ConfidentialAppAuthClient(GLOBUS_ID, GLOBUS_SECRET)
# Start the OAuth flow
client.oauth2_start_flow(
    redirect_uri="http://localhost:5000/callback",  # or your registered redirect URI
    requested_scopes=["openid", "profile", "email", "urn:globus:auth:scope:auth.globus.org:view_identities"]
)
# Get the authorization URL
authorize_url = client.oauth2_get_authorize_url()
print(f"Visit this URL in your browser:\n{authorize_url}\n")

# After visiting the URL and authorizing, you'll be redirected to a URL with a code parameter
auth_code = input("Paste the 'code' parameter from the redirect URL: ")

# Exchange the code for tokens

token_response = client.oauth2_exchange_code_for_tokens(auth_code)
access_token_data = token_response.by_resource_server['auth.globus.org']
access_token = access_token_data['access_token']
expires_at = access_token_data['expires_at_seconds']

# Convert to human-readable time
expiration_time = datetime.datetime.fromtimestamp(expires_at)
print(f"Token expires at: {expiration_time}")

# Calculate how long until expiration
seconds_until_expiration = expires_at - time.time()
hours_until_expiration = seconds_until_expiration / 3600

print(f"Token expires in {hours_until_expiration:.2f} hours")
# print("---------------------")
# print(access_token_data)
# print("---------------------")
print(f"\nYour access token:\n{access_token}")
