import os.path
import csv
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

# --- CONFIGURATION ---
# Enter your email here to exclude yourself from the report.
# Leave empty "" if you want to see your own permissions.
OWNER_EMAIL = "m.hosseini.solutions@gmail.com"
# ---------------------

SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']


def main():
    creds = None
    # Load token if it exists
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)

    # If no valid token, start login flow
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the token for next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    service = build('drive', 'v3', credentials=creds)

    print("Scanning Google Drive...")

    # Query API (exclude trashed files)
    results = service.files().list(
        q="trashed=false",
        pageSize=1000,
        fields="nextPageToken, files(id, name, webViewLink, permissions)"
    ).execute()

    items = results.get('files', [])

    if not items:
        print('No files found.')
    else:
        print(f'{len(items)} files found. Generating CSV report...')

        with open('drive_audit.csv', 'w', newline='', encoding='utf-8') as file:
            writer = csv.writer(file)
            writer.writerow(["File Name", "Link", "User Name", "User Email", "Role"])

            for item in items:
                if 'permissions' in item:
                    for perm in item['permissions']:

                        # Filter: Skip Owner role
                        if perm.get('role') == 'owner':
                            continue

                        # Filter: Skip specific email address (defined in CONFIG)
                        if OWNER_EMAIL and perm.get('emailAddress') == OWNER_EMAIL:
                            continue

                        writer.writerow([
                            item['name'],
                            item.get('webViewLink', ''),
                            perm.get('displayName', 'Unknown'),
                            perm.get('emailAddress', 'N/A'),
                            perm.get('role', 'N/A')
                        ])

        print("Done. Report saved as 'drive_audit.csv'.")


if __name__ == '__main__':
    main()