"""
One-time Google Drive OAuth setup for BizNode Backup.

Usage:
  1. Go to https://console.cloud.google.com/apis/credentials
  2. Create project (or select existing) -> Enable Google Drive API
  3. Create OAuth 2.0 Client ID -> Application type: Desktop app
  4. Download JSON -> Save as backup/credentials.json
  5. Run: python backup/setup_gdrive.py
"""

import sys
from pathlib import Path

# Add project root to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from backup.gdrive_uploader import get_drive_service, get_or_create_folder, CREDENTIALS_PATH, TOKEN_PATH, GDRIVE_FOLDER_NAME


def main():
    print("=" * 60)
    print("BizNode Backup - Google Drive Setup")
    print("=" * 60)

    if not CREDENTIALS_PATH.exists():
        print(f"\nERROR: credentials.json not found at:\n  {CREDENTIALS_PATH}")
        print("\nSteps to get credentials:")
        print("  1. Go to https://console.cloud.google.com/apis/credentials")
        print("  2. Create project or select existing one")
        print("  3. Enable 'Google Drive API' in APIs & Services")
        print("  4. Create OAuth 2.0 Client ID (Desktop app)")
        print("  5. Download the JSON file")
        print(f"  6. Save it as: {CREDENTIALS_PATH}")
        print("  7. Run this script again")
        sys.exit(1)

    print("\nAuthenticating with Google Drive...")
    print("(A browser window will open for authorization)\n")

    try:
        service = get_drive_service()
        folder_id = get_or_create_folder(service, GDRIVE_FOLDER_NAME)

        about = service.about().get(fields="user").execute()
        email = about["user"]["emailAddress"]

        print(f"\nAuthentication successful!")
        print(f"  Google Account: {email}")
        print(f"  Backup folder:  {GDRIVE_FOLDER_NAME} (ID: {folder_id})")
        print(f"  Token saved to: {TOKEN_PATH}")
        print(f"\nBackups will be stored in: Google Drive > {GDRIVE_FOLDER_NAME}")
        print("You can now run backups with: python backup/run_backup.py")

    except Exception as e:
        print(f"\nSetup failed: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
