"""
Setup OAuth2 token untuk Google Drive.

Jalankan SEKALI dari mesin yang punya browser (local atau server dengan X11):
    cd backend
    python scripts/gdrive_oauth_setup.py

Hasilnya: file token.json yang path-nya diset di .env sebagai GDRIVE_TOKEN_PATH.

Untuk re-auth (jika token expired/revoked), jalankan script ini lagi.
"""

import json
import os
import sys

SCOPES = ["https://www.googleapis.com/auth/drive"]
DEFAULT_TOKEN_PATH = "./gdrive_token.json"
DEFAULT_CREDENTIALS_PATH = "./gdrive_credentials.json"


def main():
    try:
        from google_auth_oauthlib.flow import InstalledAppFlow
        from google.oauth2.credentials import Credentials
        from google.auth.transport.requests import Request
    except ImportError:
        print("ERROR: Install dependencies dulu:")
        print("  pip install google-auth-oauthlib google-auth google-api-python-client")
        sys.exit(1)

    credentials_path = os.environ.get("GDRIVE_CREDENTIALS_PATH", DEFAULT_CREDENTIALS_PATH)
    token_path = os.environ.get("GDRIVE_TOKEN_PATH", DEFAULT_TOKEN_PATH)

    # Cek apakah token sudah ada dan masih valid
    if os.path.exists(token_path):
        creds = Credentials.from_authorized_user_file(token_path, SCOPES)
        if creds.valid:
            print(f"Token sudah valid di: {token_path}")
            _print_account_info(token_path)
            return
        if creds.expired and creds.refresh_token:
            creds.refresh(Request())
            with open(token_path, "w") as f:
                f.write(creds.to_json())
            print(f"Token di-refresh dan disimpan ke: {token_path}")
            _print_account_info(token_path)
            return

    # Generate token baru
    if not os.path.exists(credentials_path):
        print(f"ERROR: File credentials tidak ditemukan di: {credentials_path}")
        print()
        print("Cara mendapatkan credentials.json:")
        print("  1. Buka https://console.cloud.google.com/")
        print("  2. Buat project baru atau pilih project yang ada")
        print("  3. Enable Google Drive API")
        print("  4. Buat OAuth 2.0 Client ID (Desktop App)")
        print("  5. Download JSON → simpan sebagai gdrive_credentials.json di folder backend/")
        sys.exit(1)

    flow = InstalledAppFlow.from_client_secrets_file(credentials_path, SCOPES)
    creds = flow.run_local_server(port=0)

    with open(token_path, "w") as f:
        f.write(creds.to_json())

    print(f"\nToken berhasil disimpan ke: {os.path.abspath(token_path)}")
    print()
    print("Tambahkan ke .env:")
    print(f"  GDRIVE_TOKEN_PATH={os.path.abspath(token_path)}")
    _print_account_info(token_path)


def _print_account_info(token_path: str):
    """Print info akun Google yang terhubung."""
    try:
        from google.oauth2.credentials import Credentials
        from google.auth.transport.requests import Request
        from googleapiclient.discovery import build

        creds = Credentials.from_authorized_user_file(token_path, SCOPES)
        if not creds.valid and creds.expired and creds.refresh_token:
            creds.refresh(Request())

        service = build("drive", "v3", credentials=creds)
        about = service.about().get(fields="user,storageQuota").execute()
        user = about.get("user", {})
        quota = about.get("storageQuota", {})
        used_gb = int(quota.get("usage", 0)) / (1024 ** 3)
        limit = quota.get("limit")
        total_str = f"{int(limit) / (1024**3):.1f} GB" if limit else "unlimited"

        print()
        print(f"Akun    : {user.get('emailAddress', '?')}")
        print(f"Storage : {used_gb:.2f} GB / {total_str}")
    except Exception as e:
        print(f"(Tidak bisa ambil info akun: {e})")


if __name__ == "__main__":
    main()
