#!/usr/bin/env python3
"""ONE-TIME: authorize the personal 'Jarvis Drive' Google account.

Scope is drive.file ONLY — the app can touch just the files IT creates, never
the rest of your Drive. Run once: it opens your browser, you sign in with your
PERSONAL Google account (the one with spare storage) and approve, and it saves a
reusable token to jarvis_drive_token.json + creates the shared "Jarvis Drive"
folder. Idempotent — re-run anytime; it refreshes a valid token silently.

  .venv/bin/python auth-jarvis-drive.py
"""
from pathlib import Path

HERE = Path(__file__).resolve().parent
CLIENT = HERE / "jarvis_drive_oauth.json"
TOKEN = HERE / "jarvis_drive_token.json"
FOLDER_FILE = HERE / "jarvis_drive_folder.txt"
# Full Drive scope so Jarvis can see files Ahmed uploads MANUALLY into the shared
# folder (drive.file only saw app-created files). The code (drive_control.py) is
# hard-locked to the Jarvis Drive folder, so nothing outside it is ever touched.
SCOPES = ["https://www.googleapis.com/auth/drive"]
FOLDER_NAME = "Jarvis Drive"

from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build


def load_or_auth():
    creds = None
    if TOKEN.exists():
        creds = Credentials.from_authorized_user_file(str(TOKEN), SCOPES)
    if creds and creds.valid:
        return creds
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
        TOKEN.write_text(creds.to_json())
        return creds
    flow = InstalledAppFlow.from_client_secrets_file(str(CLIENT), SCOPES)
    creds = flow.run_local_server(
        port=0, access_type="offline", prompt="consent",
        open_browser=False,  # print the link; Ahmed opens it in INCOGNITO himself
        authorization_prompt_message=(
            "\n============================================================\n"
            ">>> COPY THIS LINK INTO AN INCOGNITO WINDOW <<<\n"
            "Sign in with your PERSONAL account only (akrt9907@gmail.com), NOT "
            "the work one. If you see 'Google hasn't verified this app', click "
            "Advanced -> Go to Jarvis Drive.\n\n{url}\n"
            "============================================================\n"))
    TOKEN.write_text(creds.to_json())
    return creds


def ensure_folder(creds):
    svc = build("drive", "v3", credentials=creds)
    q = ("mimeType='application/vnd.google-apps.folder' and trashed=false and "
         f"name='{FOLDER_NAME}'")
    files = svc.files().list(q=q, spaces="drive",
                             fields="files(id,name)").execute().get("files", [])
    if files:
        fid = files[0]["id"]
    else:
        meta = {"name": FOLDER_NAME,
                "mimeType": "application/vnd.google-apps.folder"}
        fid = svc.files().create(body=meta, fields="id").execute()["id"]
    FOLDER_FILE.write_text(fid)
    return fid, svc


if __name__ == "__main__":
    creds = load_or_auth()
    fid, svc = ensure_folder(creds)
    try:
        who = svc.about().get(
            fields="user(emailAddress)").execute()["user"]["emailAddress"]
        print(f"AUTHORIZED as: {who}")
    except Exception as e:  # noqa: BLE001 — about.get can 403 on drive.file; fine
        print(f"AUTHORIZED (account email hidden by scope: {str(e)[:60]})")
    print(f"Shared folder 'Jarvis Drive' id: {fid}")
    print("Scope: drive (full) — but the code only ever touches the Jarvis Drive "
          "folder. Jarvis now sees files you upload there manually.")
    print("OK")
