#!/usr/bin/env python3
"""
One-time Google OAuth2 setup script.

Run this once on Bill's Mac to authorize the WhatsApp agent
to access Google Drive and Gmail:

    cd ~/clawd/whatsapp-agent
    python setup_google_auth.py

Prerequisites:
    1. pip install google-auth google-auth-oauthlib google-api-python-client
    2. Download OAuth credentials from Google Cloud Console
       → Save as ~/clawd/.google-credentials.json
    3. Enable Google Drive API and Gmail API in the Cloud Console
"""

import os
import sys
import json
from pathlib import Path

# Add parent to path for imports
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from google_auth import CREDENTIALS_PATH, TOKEN_PATH, SCOPES, _save_token


def main():
    print("=" * 60)
    print("  CLAWD — Google API Authorization Setup")
    print("=" * 60)
    print()

    # Check for credentials file
    if not os.path.exists(CREDENTIALS_PATH):
        print(f"ERROR: Credentials file not found at:")
        print(f"  {CREDENTIALS_PATH}")
        print()
        print("To set up Google API access:")
        print("  1. Go to https://console.cloud.google.com")
        print("  2. Create a project (or select existing)")
        print("  3. Enable: Google Drive API, Gmail API")
        print("  4. Go to Credentials → Create Credentials → OAuth 2.0 Client ID")
        print("  5. Choose 'Desktop App' as application type")
        print("  6. Download the JSON file")
        print(f"  7. Save it as: {CREDENTIALS_PATH}")
        print()
        print("Then run this script again.")
        sys.exit(1)

    print(f"Credentials found: {CREDENTIALS_PATH}")
    print(f"Token will be saved to: {TOKEN_PATH}")
    print()
    print("Requesting scopes:")
    for scope in SCOPES:
        print(f"  - {scope}")
    print()

    try:
        from google_auth_oauthlib.flow import InstalledAppFlow
    except ImportError:
        print("ERROR: Missing package. Install with:")
        print("  pip install google-auth-oauthlib")
        sys.exit(1)

    # Run the OAuth flow
    print("Opening browser for authorization...")
    print("(If browser doesn't open, copy the URL from the terminal)")
    print()

    flow = InstalledAppFlow.from_client_secrets_file(CREDENTIALS_PATH, SCOPES)
    creds = flow.run_local_server(
        port=8090,
        prompt="consent",
        access_type="offline",
    )

    # Save the token
    _save_token(creds)

    print()
    print("Authorization successful!")
    print(f"Token saved to: {TOKEN_PATH}")
    print()
    print("The WhatsApp agent can now access:")
    print("  - Google Drive (search & download Health Connect files)")
    print("  - Gmail (read emails for morning briefing)")
    print()
    print("You can restart the agent to activate Google integration.")


if __name__ == "__main__":
    main()
