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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
485f33c
 
ea53751
 
 
 
 
 
 
1df64e9
ea53751
1df64e9
ea53751
 
 
 
 
 
 
63a79f4
 
 
f980c60
63a79f4
f980c60
63a79f4
 
 
 
1df64e9
f980c60
 
 
 
 
 
 
1df64e9
 
 
ea53751
 
 
 
 
 
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
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
# main.py
import os
import json
from datetime import datetime

import httpx
from fastapi import FastAPI, Request

from google.oauth2 import service_account
from googleapiclient.discovery import build

app = FastAPI()

# ===== Notion Config =====
NOTION_SECRET = os.getenv("NOTION_SECRET", "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")
NOTION_VERSION = "2025-09-03"
NOTION_DRIVE_PROP_ID = os.getenv("NOTION_DRIVE_PROP_ID", "H=Fs")  # ID بتاع حقل Google Drive Link

# ===== Google Drive Config =====
GOOGLE_CREDENTIALS = os.getenv("GOOGLE_CREDENTIALS")  # JSON string للـ service account
PARENT_FOLDER_ID = os.getenv(
    "PARENT_FOLDER_ID",
    "1ddMDm2SFnNfmt6pGIMB5-HI54ywd52Jt"  # اللي انت بعتهالي
)


# ========== Notion Template Blocks ==========
def build_content_template_children():
    """نفس التمبلت بالملّي لكن كـ children فقط."""
    return [
        # ===== Assets link =====
        {
            "object": "block",
            "type": "callout",
            "callout": {
                "rich_text": [
                    {
                        "type": "text",
                        "text": {"content": "Assets link - روابط اللقطات الخام"},
                        "annotations": {"bold": True}
                    },
                    {
                        "type": "text",
                        "text": {
                            "content": "\nهنا هنتم وضع روابط لقطات خام يمكن استخدامها في التصميم أو الفيديو"
                        }
                    }
                ],
                "icon": {"emoji": "📁"},
                "color": "brown_background"
            }
        },

        # سطر فاضي
        {
            "object": "block",
            "type": "paragraph",
            "paragraph": {"rich_text": []}
        },

        # ===== Media Buyer =====
        {
            "object": "block",
            "type": "callout",
            "callout": {
                "rich_text": [
                    {
                        "type": "text",
                        "text": {"content": "Media Buyer"},
                        "annotations": {"bold": True}
                    },
                    {
                        "type": "text",
                        "text": {
                            "content": "\nهنا الجزء الخاص بالميديا باير (يتضمن طريقة تسمية الإعلان - الكانڤسر الخاصة بكل منصة - نسخ الكوبي المختلفة للإعلان)"
                        }
                    }
                ],
                "icon": {"emoji": "🎯"},
                "color": "brown_background"
            }
        },

        # Net Name callout منفصل
        {
            "object": "block",
            "type": "callout",
            "callout": {
                "rich_text": [
                    {
                        "type": "text",
                        "text": {
                            "content": "Net Name = Name-(CreatorName/Vo)-(Offer)"
                        },
                        "annotations": {
                            "code": True,
                            "bold": True
                        }
                    }
                ],
                "icon": {"emoji": "🔤"},
                "color": "yellow_background"
            }
        },

        # سطر فاضي
        {
            "object": "block",
            "type": "paragraph",
            "paragraph": {"rich_text": []}
        },

        # ===== Ad Captions =====
        {
            "object": "block",
            "type": "callout",
            "callout": {
                "rich_text": [
                    {
                        "type": "text",
                        "text": {"content": "Ad Captions"},
                        "annotations": {"bold": True}
                    },
                    {
                        "type": "text",
                        "text": {
                            "content": "\nهنا كابشنز المنصات اللي هيستخدمها الميديا باير أثناء إطلاق الإعلان"
                        }
                    }
                ],
                "icon": {"emoji": "✍️"},
                "color": "purple_background"
            }
        },

        # سطر فاضي
        {
            "object": "block",
            "type": "paragraph",
            "paragraph": {"rich_text": []}
        },

        # ===== منصات الكابشنز كـ H3 toggle =====
        {
            "object": "block",
            "type": "heading_3",
            "heading_3": {
                "rich_text": [
                    {"type": "text", "text": {"content": "SNAPCHAT"}}
                ],
                "is_toggleable": True
            }
        },
        {
            "object": "block",
            "type": "heading_3",
            "heading_3": {
                "rich_text": [
                    {"type": "text", "text": {"content": "INSTAGRAM"}}
                ],
                "is_toggleable": True
            }
        },
        {
            "object": "block",
            "type": "heading_3",
            "heading_3": {
                "rich_text": [
                    {"type": "text", "text": {"content": "TIKTOK"}}
                ],
                "is_toggleable": True
            }
        },
        {
            "object": "block",
            "type": "heading_3",
            "heading_3": {
                "rich_text": [
                    {"type": "text", "text": {"content": "Google"}}
                ],
                "is_toggleable": True
            }
        },

        # سطر فاضي
        {
            "object": "block",
            "type": "paragraph",
            "paragraph": {"rich_text": []}
        },

        # ===== Copy Variations =====
        {
            "object": "block",
            "type": "callout",
            "callout": {
                "rich_text": [
                    {
                        "type": "text",
                        "text": {"content": "Copy Variations"},
                        "annotations": {"bold": True}
                    },
                    {
                        "type": "text",
                        "text": {
                            "content": "\nهنا نسخ الكوبي اللي هنتم وضعها أثناء إطلاق الإعلان"
                        }
                    }
                ],
                "icon": {"emoji": "📄"},
                "color": "gray_background"
            }
        },

        # سطر فاضي
        {
            "object": "block",
            "type": "paragraph",
            "paragraph": {"rich_text": []}
        },

        # ===== جدول الكوبيز a / b =====
        {
            "object": "block",
            "type": "table",
            "table": {
                "table_width": 2,
                "has_column_header": True,
                "has_row_header": False,
                "children": [
                    {
                        "object": "block",
                        "type": "table_row",
                        "table_row": {
                            "cells": [
                                [
                                    {
                                        "type": "text",
                                        "text": {"content": "Version"}
                                    }
                                ],
                                [
                                    {
                                        "type": "text",
                                        "text": {"content": "Copy"}
                                    }
                                ]
                            ]
                        }
                    },
                    {
                        "object": "block",
                        "type": "table_row",
                        "table_row": {
                            "cells": [
                                [
                                    {
                                        "type": "text",
                                        "text": {"content": "a"}
                                    }
                                ],
                                [
                                    {
                                        "type": "text",
                                        "text": {"content": ""}
                                    }
                                ]
                            ]
                        }
                    },
                    {
                        "object": "block",
                        "type": "table_row",
                        "table_row": {
                            "cells": [
                                [
                                    {
                                        "type": "text",
                                        "text": {"content": "b"}
                                    }
                                ],
                                [
                                    {
                                        "type": "text",
                                        "text": {"content": ""}
                                    }
                                ]
                            ]
                        }
                    }
                ]
            }
        },

        # سطر فاضي
        {
            "object": "block",
            "type": "paragraph",
            "paragraph": {"rich_text": []}
        },

        # ===== NOTES =====
        {
            "object": "block",
            "type": "callout",
            "callout": {
                "rich_text": [
                    {
                        "type": "text",
                        "text": {"content": "NOTES (References if needed)"},
                        "annotations": {"bold": True}
                    },
                    {
                        "type": "text",
                        "text": {
                            "content": "\nهنا لو في نوتس مهم نشتغل عليها جميعًا سواء كاتب المحتوى، المصمم أو الميديا باير"
                        }
                    }
                ],
                "icon": {"emoji": "📌"},
                "color": "brown_background"
            }
        }
    ]


# ========== Notion Helpers ==========

async def get_page_title(page_id: str) -> str:
    """Fetch page title from Notion."""
    async with httpx.AsyncClient() as client:
        res = await client.get(
            f"https://api.notion.com/v1/pages/{page_id}",
            headers={
                "Authorization": f"Bearer {NOTION_SECRET}",
                "Notion-Version": NOTION_VERSION,
            },
        )

    data = res.json()

    props = data.get("properties", {})
    for prop in props.values():
        if prop.get("type") == "title":
            title_items = prop.get("title", [])
            if len(title_items) > 0:
                return title_items[0].get("plain_text", "")

    return "(No Title)"


async def is_block_archived(page_id: str) -> bool:
    """يرجع True لو البلوك/الصفحة archived."""
    async with httpx.AsyncClient() as client:
        res = await client.get(
            f"https://api.notion.com/v1/blocks/{page_id}",
            headers={
                "Authorization": f"Bearer {NOTION_SECRET}",
                "Notion-Version": NOTION_VERSION,
            },
        )

    if res.status_code != 200:
        print(f"[ARCHIVE CHECK] Failed to fetch block {page_id}, status: {res.status_code}")
        try:
            print("[ARCHIVE CHECK] Response:", res.json())
        except Exception:
            print("[ARCHIVE CHECK] Raw response:", res.text)
        return False  # ما نكسرش الفلو

    data = res.json()
    archived = data.get("archived", False)
    print(f"[ARCHIVE CHECK] Block {page_id} archived = {archived}")
    return archived


async def apply_template_to_page(page_id: str):
    """Append التمبلت دي لجسم الصفحة (الـ body) باستخدام blocks API."""
    children = build_content_template_children()

    print(f"[TEMPLATE] Applying template to page: {page_id}")

    async with httpx.AsyncClient() as client:
        res = await client.patch(
            f"https://api.notion.com/v1/blocks/{page_id}/children",
            headers={
                "Authorization": f"Bearer {NOTION_SECRET}",
                "Notion-Version": NOTION_VERSION,
                "Content-Type": "application/json",
            },
            json={"children": children},
        )

    print(f"[TEMPLATE] Status: {res.status_code}")
    try:
        print("[TEMPLATE] Response:", res.json())
    except Exception:
        print("[TEMPLATE] Raw Response:", res.text)


async def update_page_drive_link(page_id: str, drive_link: str):
    """يحدث حقل URL في الصفحة برابط Google Drive."""
    print(f"[NOTION] Updating drive link for page {page_id} -> {drive_link}")

    async with httpx.AsyncClient() as client:
        res = await client.patch(
            f"https://api.notion.com/v1/pages/{page_id}",
            headers={
                "Authorization": f"Bearer {NOTION_SECRET}",
                "Notion-Version": NOTION_VERSION,
                "Content-Type": "application/json",
            },
            json={
                "properties": {
                    NOTION_DRIVE_PROP_ID: {
                        "url": drive_link
                    }
                }
            },
        )

    print(f"[NOTION] Drive link update status: {res.status_code}")
    try:
        print("[NOTION] Drive link response:", res.json())
    except Exception:
        print("[NOTION] Drive link raw response:", res.text)


# ========== Google Drive Helpers ==========

def get_drive_service():
    if not GOOGLE_CREDENTIALS:
        raise RuntimeError("GOOGLE_CREDENTIALS env var is missing")

    creds_info = json.loads(GOOGLE_CREDENTIALS)
    creds = service_account.Credentials.from_service_account_info(
        creds_info,
        scopes=["https://www.googleapis.com/auth/drive"]
    )
    service = build("drive", "v3", credentials=creds)
    return service


def search_folder(name: str, parent_id: str, drive_service):
    query = (
        f"name = '{name}' and "
        f"'{parent_id}' in parents and "
        "mimeType = 'application/vnd.google-apps.folder' and trashed = false"
    )
    results = drive_service.files().list(
        q=query,
        fields="files(id, name)"
    ).execute()
    files = results.get("files", [])
    return files[0] if files else None


def create_folder(name: str, parent_id: str, drive_service):
    metadata = {
        "name": name,
        "mimeType": "application/vnd.google-apps.folder",
        "parents": [parent_id],
    }
    folder = drive_service.files().create(
        body=metadata,
        fields="id, name"
    ).execute()
    return folder


def ensure_drive_folder_for_page(page_title: str) -> str:
    """
    - جوه PARENT_FOLDER_ID
      - فولدر شهر (Dec 2025 مثلاً)
      - جوه فولدر باسم الـ page_title
    وترجع Google Drive folder link.
    """
    drive_service = get_drive_service()

    # لو العنوان فاضي، استخدم page_id أو اسم fallback من برّه
    safe_title = page_title.strip() if page_title and page_title.strip() else "Untitled Task"

    # من الأفضل نشيل Slash عشان ما يكسرش الاسم
    safe_title = safe_title.replace("/", "-")

    month_name = datetime.now().strftime("%b %Y")  # مثال: "Dec 2025"

    print(f"[DRIVE] Ensuring month folder '{month_name}' under parent {PARENT_FOLDER_ID}")
    month_folder = search_folder(month_name, PARENT_FOLDER_ID, drive_service)
    if not month_folder:
        month_folder = create_folder(month_name, PARENT_FOLDER_ID, drive_service)
        print(f"[DRIVE] Created month folder: {month_folder['id']} - {month_folder['name']}")
    else:
        print(f"[DRIVE] Found month folder: {month_folder['id']} - {month_folder['name']}")

    month_folder_id = month_folder["id"]

    print(f"[DRIVE] Ensuring page folder '{safe_title}' under month folder {month_folder_id}")
    page_folder = search_folder(safe_title, month_folder_id, drive_service)
    if not page_folder:
        page_folder = create_folder(safe_title, month_folder_id, drive_service)
        print(f"[DRIVE] Created page folder: {page_folder['id']} - {page_folder['name']}")
    else:
        print(f"[DRIVE] Found page folder: {page_folder['id']} - {page_folder['name']}")

    folder_id = page_folder["id"]
    drive_link = f"https://drive.google.com/drive/folders/{folder_id}"
    print(f"[DRIVE] Final folder link: {drive_link}")
    return drive_link


# ========== Webhook ==========

@app.post("/webhook")
async def webhook(request: Request):
    body = await request.json()

    event_type = body.get("type")
    page_id = body.get("entity", {}).get("id")
    timestamp = body.get("timestamp")

    print("\n===== NEW WEBHOOK EVENT =====")
    print("Raw body:", body)

    if event_type == "page.created":
        title = await get_page_title(page_id)

        print(f"Event Type : {event_type}")
        print(f"Page Title : {title}")
        print(f"Page ID    : {page_id}")
        print(f"Timestamp  : {timestamp}")

        # تشيك الأول: هل الصفحة دي Archived (زي لما تدوس Escape على placeholder)؟
        archived = await is_block_archived(page_id)
        if archived:
            print(f"[TEMPLATE] Page {page_id} is archived right after creation. Skipping template & drive.")
        else:
            # 1) نطبّق التمبلت
            try:
                await apply_template_to_page(page_id)
            except Exception as e:
                print("[ERROR] While applying template:", e)

            # 2) ننشئ فولدر على الدرايف باسم الصفحة ونحط اللينك في النوشن
            try:
                drive_link = ensure_drive_folder_for_page(title or page_id)
                await update_page_drive_link(page_id, drive_link)
            except Exception as e:
                print("[ERROR] While creating drive folder or updating Notion URL:", e)

    elif event_type == "page.deleted":
        print(f"Page deleted. ID: {page_id}, Timestamp: {timestamp}")

    else:
        print("Event received but ignored:", event_type)

    print("================================\n")

    return {"status": "ok"}