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
from googleapiclient.discovery import build

SCOPES = [
    'https://www.googleapis.com/auth/business.manage'
]

def get_creds():
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    return creds

def list_locations():
    creds = get_creds()
    if not creds:
        print("No token.json found. Please run authorize.py first.")
        return

    try:
        # 1. Get the Account ID
        # "mybusinessaccountmanagement" service is needed to get the account
        service_account = build('mybusinessaccountmanagement', 'v1', credentials=creds)
        accounts_result = service_account.accounts().list().execute()
        accounts = accounts_result.get('accounts', [])

        if not accounts:
            print("No Google Business accounts found.")
            return

        # Use the first account (usually there's only one or the user wants the main one)
        # You might want to list them if there are multiple.
        account = accounts[0]
        account_name = account['name'] # Format: accounts/{accountId}
        print(f"Using Account: {account['accountName']} ({account_name})")

        # 2. List Locations for that Account
        # "mybusinessbusinessinformation" service is used for locations
        service_locations = build('mybusinessbusinessinformation', 'v1', credentials=creds)
        
        print("\nFetching locations...\n")
        print(f"{'Store Code':<15} | {'Location ID':<40} | {'Outlet Name'}")
        print("-" * 80)

        request = service_locations.accounts().locations().list(
            parent=account_name,
            readMask="name,title,storeCode"
        )
        
        while request is not None:
            response = request.execute()
            locations = response.get('locations', [])

            for loc in locations:
                # name is "locations/{locationId}"
                location_id = loc.get('name', '').split('/')[-1]
                title = loc.get('title', 'N/A')
                store_code = loc.get('storeCode', 'N/A')
                
                print(f"{store_code:<15} | {location_id:<40} | {title}")

            request = service_locations.accounts().locations().list_next(request, response)
            
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == '__main__':
    list_locations()
