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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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
"""
R2 Storage integration for OpenManus
Provides interface to Cloudflare R2 storage operations
"""

import io
from typing import Any, BinaryIO, Dict, List, Optional

from app.logger import logger

from .client import CloudflareClient, CloudflareError


class R2Storage:
    """Cloudflare R2 Storage client"""

    def __init__(
        self,
        client: CloudflareClient,
        storage_bucket: str,
        assets_bucket: Optional[str] = None,
    ):
        self.client = client
        self.storage_bucket = storage_bucket
        self.assets_bucket = assets_bucket or storage_bucket
        self.base_endpoint = f"accounts/{client.account_id}/r2/buckets"

    def _get_bucket_name(self, bucket_type: str = "storage") -> str:
        """Get bucket name based on type"""
        if bucket_type == "assets":
            return self.assets_bucket
        return self.storage_bucket

    async def upload_file(
        self,
        key: str,
        file_data: bytes,
        content_type: str = "application/octet-stream",
        bucket_type: str = "storage",
        metadata: Optional[Dict[str, str]] = None,
        use_worker: bool = True,
    ) -> Dict[str, Any]:
        """Upload a file to R2"""

        bucket_name = self._get_bucket_name(bucket_type)

        try:
            if use_worker:
                # Use worker endpoint for better performance
                form_data = {
                    "file": file_data,
                    "bucket": bucket_type,
                    "key": key,
                    "contentType": content_type,
                }

                if metadata:
                    form_data["metadata"] = metadata

                response = await self.client.post(
                    "api/files", data=form_data, use_worker=True
                )
            else:
                # Use R2 API directly
                headers = {"Content-Type": content_type}

                if metadata:
                    for k, v in metadata.items():
                        headers[f"x-amz-meta-{k}"] = v

                response = await self.client.upload_file(
                    f"{self.base_endpoint}/{bucket_name}/objects/{key}",
                    file_data,
                    content_type,
                    headers,
                )

            return {
                "success": True,
                "key": key,
                "bucket": bucket_type,
                "bucket_name": bucket_name,
                "size": len(file_data),
                "content_type": content_type,
                "url": f"/{bucket_type}/{key}",
                **response,
            }

        except CloudflareError as e:
            logger.error(f"R2 upload failed: {e}")
            raise

    async def upload_file_stream(
        self,
        key: str,
        file_stream: BinaryIO,
        content_type: str = "application/octet-stream",
        bucket_type: str = "storage",
        metadata: Optional[Dict[str, str]] = None,
    ) -> Dict[str, Any]:
        """Upload a file from stream"""

        file_data = file_stream.read()
        return await self.upload_file(
            key, file_data, content_type, bucket_type, metadata
        )

    async def get_file(
        self, key: str, bucket_type: str = "storage", use_worker: bool = True
    ) -> Optional[Dict[str, Any]]:
        """Get a file from R2"""

        bucket_name = self._get_bucket_name(bucket_type)

        try:
            if use_worker:
                response = await self.client.get(
                    f"api/files/{key}?bucket={bucket_type}", use_worker=True
                )

                if response:
                    return {
                        "key": key,
                        "bucket": bucket_type,
                        "bucket_name": bucket_name,
                        "data": response,  # Binary data would be handled by worker
                        "exists": True,
                    }
            else:
                response = await self.client.get(
                    f"{self.base_endpoint}/{bucket_name}/objects/{key}"
                )

                return {
                    "key": key,
                    "bucket": bucket_type,
                    "bucket_name": bucket_name,
                    "data": response,
                    "exists": True,
                }

        except CloudflareError as e:
            if e.status_code == 404:
                return None
            logger.error(f"R2 get file failed: {e}")
            raise

        return None

    async def delete_file(
        self, key: str, bucket_type: str = "storage", use_worker: bool = True
    ) -> Dict[str, Any]:
        """Delete a file from R2"""

        bucket_name = self._get_bucket_name(bucket_type)

        try:
            if use_worker:
                response = await self.client.delete(
                    f"api/files/{key}?bucket={bucket_type}", use_worker=True
                )
            else:
                response = await self.client.delete(
                    f"{self.base_endpoint}/{bucket_name}/objects/{key}"
                )

            return {
                "success": True,
                "key": key,
                "bucket": bucket_type,
                "bucket_name": bucket_name,
                **response,
            }

        except CloudflareError as e:
            logger.error(f"R2 delete failed: {e}")
            raise

    async def list_files(
        self,
        bucket_type: str = "storage",
        prefix: str = "",
        limit: int = 1000,
        use_worker: bool = True,
    ) -> Dict[str, Any]:
        """List files in R2 bucket"""

        bucket_name = self._get_bucket_name(bucket_type)

        try:
            if use_worker:
                params = {"bucket": bucket_type, "prefix": prefix, "limit": limit}

                query_string = "&".join([f"{k}={v}" for k, v in params.items() if v])
                response = await self.client.get(
                    f"api/files/list?{query_string}", use_worker=True
                )
            else:
                params = {"prefix": prefix, "max-keys": limit}

                query_string = "&".join([f"{k}={v}" for k, v in params.items() if v])
                response = await self.client.get(
                    f"{self.base_endpoint}/{bucket_name}/objects?{query_string}"
                )

            return {
                "bucket": bucket_type,
                "bucket_name": bucket_name,
                "prefix": prefix,
                "files": response.get("objects", []),
                "truncated": response.get("truncated", False),
                **response,
            }

        except CloudflareError as e:
            logger.error(f"R2 list files failed: {e}")
            raise

    async def get_file_metadata(
        self, key: str, bucket_type: str = "storage", use_worker: bool = True
    ) -> Optional[Dict[str, Any]]:
        """Get file metadata without downloading content"""

        bucket_name = self._get_bucket_name(bucket_type)

        try:
            if use_worker:
                response = await self.client.get(
                    f"api/files/{key}/metadata?bucket={bucket_type}", use_worker=True
                )
            else:
                # Use HEAD request to get metadata only
                response = await self.client.get(
                    f"{self.base_endpoint}/{bucket_name}/objects/{key}",
                    headers={"Range": "bytes=0-0"},  # Minimal range to get headers
                )

            if response:
                return {
                    "key": key,
                    "bucket": bucket_type,
                    "bucket_name": bucket_name,
                    **response,
                }

        except CloudflareError as e:
            if e.status_code == 404:
                return None
            logger.error(f"R2 get metadata failed: {e}")
            raise

        return None

    async def copy_file(
        self,
        source_key: str,
        destination_key: str,
        source_bucket: str = "storage",
        destination_bucket: str = "storage",
        use_worker: bool = True,
    ) -> Dict[str, Any]:
        """Copy a file within R2 or between buckets"""

        try:
            if use_worker:
                copy_data = {
                    "sourceKey": source_key,
                    "destinationKey": destination_key,
                    "sourceBucket": source_bucket,
                    "destinationBucket": destination_bucket,
                }

                response = await self.client.post(
                    "api/files/copy", data=copy_data, use_worker=True
                )
            else:
                # Get source file first
                source_file = await self.get_file(source_key, source_bucket, False)

                if not source_file:
                    raise CloudflareError(f"Source file {source_key} not found")

                # Upload to destination
                response = await self.upload_file(
                    destination_key,
                    source_file["data"],
                    bucket_type=destination_bucket,
                    use_worker=False,
                )

            return {
                "success": True,
                "source_key": source_key,
                "destination_key": destination_key,
                "source_bucket": source_bucket,
                "destination_bucket": destination_bucket,
                **response,
            }

        except CloudflareError as e:
            logger.error(f"R2 copy failed: {e}")
            raise

    async def move_file(
        self,
        source_key: str,
        destination_key: str,
        source_bucket: str = "storage",
        destination_bucket: str = "storage",
        use_worker: bool = True,
    ) -> Dict[str, Any]:
        """Move a file (copy then delete)"""

        try:
            # Copy file first
            copy_result = await self.copy_file(
                source_key,
                destination_key,
                source_bucket,
                destination_bucket,
                use_worker,
            )

            # Delete source file
            delete_result = await self.delete_file(
                source_key, source_bucket, use_worker
            )

            return {
                "success": True,
                "source_key": source_key,
                "destination_key": destination_key,
                "source_bucket": source_bucket,
                "destination_bucket": destination_bucket,
                "copy_result": copy_result,
                "delete_result": delete_result,
            }

        except CloudflareError as e:
            logger.error(f"R2 move failed: {e}")
            raise

    async def generate_presigned_url(
        self,
        key: str,
        bucket_type: str = "storage",
        expires_in: int = 3600,
        method: str = "GET",
    ) -> Dict[str, Any]:
        """Generate a presigned URL for direct access"""

        # Note: This would typically require additional R2 configuration
        # For now, return a worker endpoint URL

        try:
            url_data = {
                "key": key,
                "bucket": bucket_type,
                "expiresIn": expires_in,
                "method": method,
            }

            response = await self.client.post(
                "api/files/presigned-url", data=url_data, use_worker=True
            )

            return {
                "success": True,
                "key": key,
                "bucket": bucket_type,
                "method": method,
                "expires_in": expires_in,
                **response,
            }

        except CloudflareError as e:
            logger.error(f"R2 presigned URL generation failed: {e}")
            raise

    async def get_storage_stats(self, use_worker: bool = True) -> Dict[str, Any]:
        """Get storage statistics"""

        try:
            if use_worker:
                response = await self.client.get("api/files/stats", use_worker=True)
            else:
                # Get stats for both buckets
                storage_list = await self.list_files("storage", use_worker=False)
                assets_list = await self.list_files("assets", use_worker=False)

                storage_size = sum(
                    file.get("size", 0) for file in storage_list.get("files", [])
                )
                assets_size = sum(
                    file.get("size", 0) for file in assets_list.get("files", [])
                )

                response = {
                    "storage": {
                        "file_count": len(storage_list.get("files", [])),
                        "total_size": storage_size,
                    },
                    "assets": {
                        "file_count": len(assets_list.get("files", [])),
                        "total_size": assets_size,
                    },
                    "total": {
                        "file_count": len(storage_list.get("files", []))
                        + len(assets_list.get("files", [])),
                        "total_size": storage_size + assets_size,
                    },
                }

            return response

        except CloudflareError as e:
            logger.error(f"R2 storage stats failed: {e}")
            raise

    def create_file_stream(self, data: bytes) -> io.BytesIO:
        """Create a file stream from bytes"""
        return io.BytesIO(data)

    def get_public_url(self, key: str, bucket_type: str = "storage") -> str:
        """Get public URL for a file (if bucket is configured for public access)"""
        bucket_name = self._get_bucket_name(bucket_type)

        # This would depend on your R2 custom domain configuration
        # For now, return the worker endpoint
        if self.client.worker_url:
            return f"{self.client.worker_url}/api/files/{key}?bucket={bucket_type}"

        # Default R2 URL format (requires public access configuration)
        return f"https://pub-{bucket_name}.r2.dev/{key}"