import os
import requests
import json
from dotenv import load_dotenv

# Load config
load_dotenv(dotenv_path="../.env")
client_id = os.getenv("SO_CLIENT_ID") or os.getenv("SO_SOD")
client_secret = os.getenv("SO_CLIENT_SECRET")
redirect_uri = "http://localhost" # Ensure this is in "Allowed Redirect URLs" in Dev Portal

if not client_id or not client_secret:
    print("Error: Please set SO_CLIENT_ID (or SO_SOD) and SO_CLIENT_SECRET in .env first.")
    exit(1)

# Step 1: Generate Authorization URL
auth_url = (
    f"https://sod.superoffice.com/login/common/oauth/authorize"
    f"?client_id={client_id}"
    f"&redirect_uri={redirect_uri}"
    f"&response_type=code"
    f"&scope=openid"  # Scope might be needed, try without first
)

print(f"\n--- STEP 1: Authorization ---")
print(f"Please open this URL in your browser:\n\n{auth_url}\n")
print("1. Log in to your test tenant (Cust55774).")
print("2. Click 'Allow' / 'Zulassen'.")
print("3. You will be redirected to a localhost URL (it might fail to load, that's fine).")
print("4. Copy the full URL from your browser's address bar and paste it here.")

redirected_url = input("\nPaste the full redirect URL here: ").strip()

# Extract code
try:
    from urllib.parse import urlparse, parse_qs
    parsed = urlparse(redirected_url)
    code = parse_qs(parsed.query)['code'][0]
except Exception as e:
    print(f"Error extracting code: {e}")
    exit(1)

# Step 2: Exchange Code for Tokens
print(f"\n--- STEP 2: Token Exchange ---")
token_url = "https://sod.superoffice.com/login/common/oauth/tokens"
payload = {
    "grant_type": "authorization_code",
    "client_id": client_id,
    "client_secret": client_secret,
    "code": code,
    "redirect_uri": redirect_uri
}

try:
    resp = requests.post(token_url, data=payload)
    resp.raise_for_status()
    tokens = resp.json()
    
    refresh_token = tokens.get("refresh_token")
    access_token = tokens.get("access_token")
    
    print("\nSUCCESS! Here are your tokens:")
    print(f"\nSO_REFRESH_TOKEN=\"{refresh_token}\"\n")
    print(f"\n(Access Token for testing: {access_token[:20]}...)")
    
    print("\nAction: Please update your .env file with the SO_REFRESH_TOKEN value above!")

except Exception as e:
    print(f"Error exchanging code: {e}")
    if hasattr(e, 'response') and e.response:
        print(f"Response: {e.response.text}")
