Spaces:
Sleeping

File size: 4,111 Bytes
3c5146b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
386a178
3c5146b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
"""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)}