import os.path
import json
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow

# Scopes for Business Profile API
# https://developers.google.com/my-business/content/basic-setup#request_scopes
SCOPES = [
    'https://www.googleapis.com/auth/business.manage' 
]

def authorize():
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            print("Starting OAuth flow...")
            print("If you are running this on a remote server without a browser, you may need to:")
            print("1. Run this script on your local machine to generate token.json")
            print("2. Upload token.json to this directory.")
            print("Or use port forwarding (e.g. ssh -L 8080:localhost:8080 user@host).")
            
            flow = InstalledAppFlow.from_client_secrets_file(
                'client_secret.json', SCOPES)
            
            # Using a fixed port 8080 to make port forwarding easier if needed
            creds = flow.run_local_server(port=8080, open_browser=True)
            
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
            print("Token saved to token.json")

if __name__ == '__main__':
    authorize()
