"""Google Drive integration — saves and loads the project plan JSON.""" import asyncio import json import os from core.planner import ERROR_MESSAGES, ProjectPlan, parse_plan_json SCOPES = ["https://www.googleapis.com/auth/drive.file"] FILE_NAME = "projectcraft_plan.json" def _build_service(): """Build Google Drive API service. Return None if credentials unavailable.""" try: from google.oauth2.credentials import Credentials from googleapiclient.discovery import build except ImportError: return None client_id = os.environ.get("GOOGLE_CLIENT_ID") client_secret = os.environ.get("GOOGLE_CLIENT_SECRET") if not client_id or not client_secret: return None try: credentials = Credentials( token=None, client_id=client_id, client_secret=client_secret, scopes=SCOPES, ) return build("drive", "v3", credentials=credentials) except Exception: return None async def save_plan(plan: ProjectPlan) -> dict: """ Save plan JSON to Drive as projectcraft_plan.json. Update existing file if found, create new if not. Returns {"success": bool, "file_id": str | None, "error": str | None} """ service = _build_service() if service is None: return {"success": False, "file_id": None, "error": ERROR_MESSAGES["google_auth"]} try: plan_json = json.dumps(plan.model_dump(exclude_none=True), indent=2) def _save() -> str: from googleapiclient.http import MediaInMemoryUpload media = MediaInMemoryUpload(plan_json.encode("utf-8"), mimetype="application/json") results = ( service.files() .list(q=f"name='{FILE_NAME}' and trashed=false", fields="files(id)") .execute() ) existing = results.get("files", []) if existing: file_id = existing[0]["id"] service.files().update(fileId=file_id, media_body=media).execute() return file_id file_meta = {"name": FILE_NAME, "mimeType": "application/json"} created = service.files().create(body=file_meta, media_body=media, fields="id").execute() return created["id"] file_id = await asyncio.to_thread(_save) return {"success": True, "file_id": file_id, "error": None} except Exception as exc: return {"success": False, "file_id": None, "error": str(exc)} async def load_plan() -> dict: """ Load the most recent projectcraft_plan.json from Drive. Returns {"success": bool, "plan": ProjectPlan | None, "error": str | None} """ service = _build_service() if service is None: return {"success": False, "plan": None, "error": ERROR_MESSAGES["google_auth"]} try: def _load() -> str: import io from googleapiclient.http import MediaIoBaseDownload results = ( service.files() .list( q=f"name='{FILE_NAME}' and trashed=false", orderBy="modifiedTime desc", fields="files(id)", pageSize=1, ) .execute() ) files = results.get("files", []) if not files: return None file_id = files[0]["id"] request = service.files().get_media(fileId=file_id) buffer = io.BytesIO() downloader = MediaIoBaseDownload(buffer, request) done = False while not done: _, done = downloader.next_chunk() return buffer.getvalue().decode("utf-8") raw = await asyncio.to_thread(_load) if raw is None: return {"success": False, "plan": None, "error": f"{FILE_NAME} not found in Drive"} plan = parse_plan_json(raw) return {"success": True, "plan": plan, "error": None} except Exception as exc: return {"success": False, "plan": None, "error": str(exc)}