notion-cli-tool 0.1.0

A fast and simple Notion CLI written in Rust
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
use anyhow::{bail, Context, Result};
use colored::Colorize;
use std::time::Duration;

use crate::utils::{
    get_api_version, normalize_page_id, DEFAULT_RETRY_DELAY_SECS, MAX_RETRIES, NOTION_API_BASE,
};

#[derive(Debug, Clone, Default)]
pub struct RichTextSegment {
    pub text: String,
    pub link: Option<String>,
    pub bold: bool,
    pub italic: bool,
    pub code: bool,
}

impl RichTextSegment {
    pub fn plain(text: &str) -> Self {
        Self {
            text: text.to_string(),
            ..Default::default()
        }
    }

    pub fn link(text: &str, url: &str) -> Self {
        Self {
            text: text.to_string(),
            link: Some(url.to_string()),
            ..Default::default()
        }
    }

    #[allow(dead_code)]
    pub fn code_inline(text: &str) -> Self {
        Self {
            text: text.to_string(),
            code: true,
            ..Default::default()
        }
    }

    #[allow(dead_code)]
    pub fn bold(text: &str) -> Self {
        Self {
            text: text.to_string(),
            bold: true,
            ..Default::default()
        }
    }
}

pub struct NotionClient {
    api_key: String,
    api_version: String,
    client: reqwest::blocking::Client,
}

impl NotionClient {
    pub fn new(api_key: String, timeout_secs: u64) -> Result<Self> {
        let client = reqwest::blocking::Client::builder()
            .timeout(Duration::from_secs(timeout_secs))
            .build()
            .context("Failed to create HTTP client")?;

        Ok(Self {
            api_key,
            api_version: get_api_version(),
            client,
        })
    }

    /// Execute a request with retry logic for rate limiting (429)
    fn execute_with_retry(
        &self,
        request_builder: impl Fn() -> reqwest::blocking::RequestBuilder,
    ) -> Result<reqwest::blocking::Response> {
        let mut retries = 0;

        loop {
            let response = request_builder()
                .header("Authorization", format!("Bearer {}", self.api_key))
                .header("Notion-Version", &self.api_version)
                .send()
                .context("Failed to send request")?;

            if response.status() == reqwest::StatusCode::TOO_MANY_REQUESTS {
                if retries >= MAX_RETRIES {
                    bail!("Rate limit exceeded after {} retries", MAX_RETRIES);
                }

                let retry_after = response
                    .headers()
                    .get("Retry-After")
                    .and_then(|v| v.to_str().ok())
                    .and_then(|s| s.parse::<u64>().ok())
                    .unwrap_or(DEFAULT_RETRY_DELAY_SECS);

                eprintln!(
                    "{} Rate limited. Waiting {} seconds before retry ({}/{})...",
                    "".yellow(),
                    retry_after,
                    retries + 1,
                    MAX_RETRIES
                );

                std::thread::sleep(Duration::from_secs(retry_after));
                retries += 1;
                continue;
            }

            return response
                .error_for_status()
                .context("Notion API returned an error");
        }
    }

    pub fn search(&self, query: &str, limit: usize) -> Result<Vec<serde_json::Value>> {
        let url = format!("{}/search", NOTION_API_BASE);
        let mut all_results = Vec::new();
        let mut start_cursor: Option<String> = None;

        loop {
            let mut body = serde_json::json!({
                "query": query,
                "page_size": 100.min(limit - all_results.len())
            });

            if let Some(cursor) = &start_cursor {
                body["start_cursor"] = serde_json::json!(cursor);
            }

            let body_clone = body.clone();
            let url_clone = url.clone();
            let response = self.execute_with_retry(|| {
                self.client
                    .post(&url_clone)
                    .header("Content-Type", "application/json")
                    .json(&body_clone)
            })?;

            let result: serde_json::Value = response.json().context("Failed to parse response")?;

            if let Some(results) = result.get("results").and_then(|r| r.as_array()) {
                all_results.extend(results.clone());
            }

            let has_more = result
                .get("has_more")
                .and_then(|h| h.as_bool())
                .unwrap_or(false);
            if !has_more || all_results.len() >= limit {
                break;
            }

            start_cursor = result
                .get("next_cursor")
                .and_then(|c| c.as_str())
                .map(String::from);
            if start_cursor.is_none() {
                break;
            }
        }

        Ok(all_results)
    }

    pub fn get_page(&self, page_id: &str) -> Result<serde_json::Value> {
        let page_id = normalize_page_id(page_id)?;
        let url = format!("{}/pages/{}", NOTION_API_BASE, page_id);

        let response = self.execute_with_retry(|| self.client.get(&url))?;
        let result: serde_json::Value = response.json().context("Failed to parse response")?;
        Ok(result)
    }

    pub fn get_blocks(&self, page_id: &str) -> Result<Vec<serde_json::Value>> {
        let page_id = normalize_page_id(page_id)?;
        let base_url = format!("{}/blocks/{}/children", NOTION_API_BASE, page_id);
        let mut all_blocks = Vec::new();
        let mut start_cursor: Option<String> = None;

        loop {
            let request_url = if let Some(cursor) = &start_cursor {
                format!("{}?start_cursor={}", base_url, cursor)
            } else {
                base_url.clone()
            };

            let response = self.execute_with_retry(|| self.client.get(&request_url))?;
            let result: serde_json::Value = response.json().context("Failed to parse response")?;

            if let Some(results) = result.get("results").and_then(|r| r.as_array()) {
                all_blocks.extend(results.clone());
            }

            let has_more = result
                .get("has_more")
                .and_then(|h| h.as_bool())
                .unwrap_or(false);
            if !has_more {
                break;
            }

            start_cursor = result
                .get("next_cursor")
                .and_then(|c| c.as_str())
                .map(String::from);
            if start_cursor.is_none() {
                break;
            }
        }

        Ok(all_blocks)
    }

    pub fn create_page(
        &self,
        parent_id: &str,
        title: &str,
        content: Option<&str>,
    ) -> Result<serde_json::Value> {
        let parent_id = normalize_page_id(parent_id)?;
        let url = format!("{}/pages", NOTION_API_BASE);

        let mut children = vec![];
        if let Some(text) = content {
            children.push(serde_json::json!({
                "object": "block",
                "type": "paragraph",
                "paragraph": {
                    "rich_text": [{
                        "type": "text",
                        "text": { "content": text }
                    }]
                }
            }));
        }

        let body = serde_json::json!({
            "parent": { "page_id": parent_id },
            "properties": {
                "title": {
                    "title": [{
                        "text": { "content": title }
                    }]
                }
            },
            "children": children
        });

        let response = self.execute_with_retry(|| {
            self.client
                .post(&url)
                .header("Content-Type", "application/json")
                .json(&body)
        })?;

        let result: serde_json::Value = response.json().context("Failed to parse response")?;
        Ok(result)
    }

    pub fn append_blocks(&self, page_id: &str, content: &str) -> Result<serde_json::Value> {
        let page_id = normalize_page_id(page_id)?;
        let url = format!("{}/blocks/{}/children", NOTION_API_BASE, page_id);

        let body = serde_json::json!({
            "children": [{
                "object": "block",
                "type": "paragraph",
                "paragraph": {
                    "rich_text": [{
                        "type": "text",
                        "text": { "content": content }
                    }]
                }
            }]
        });

        let response = self.execute_with_retry(|| {
            self.client
                .patch(&url)
                .header("Content-Type", "application/json")
                .json(&body)
        })?;

        let result: serde_json::Value = response.json().context("Failed to parse response")?;
        Ok(result)
    }

    pub fn update_page(
        &self,
        page_id: &str,
        title: Option<&str>,
        icon: Option<&str>,
    ) -> Result<serde_json::Value> {
        let page_id = normalize_page_id(page_id)?;
        let url = format!("{}/pages/{}", NOTION_API_BASE, page_id);

        let mut body = serde_json::json!({});

        if let Some(new_title) = title {
            body["properties"] = serde_json::json!({
                "title": {
                    "title": [{
                        "text": { "content": new_title }
                    }]
                }
            });
        }

        if let Some(emoji) = icon {
            body["icon"] = serde_json::json!({
                "type": "emoji",
                "emoji": emoji
            });
        }

        let response = self.execute_with_retry(|| {
            self.client
                .patch(&url)
                .header("Content-Type", "application/json")
                .json(&body)
        })?;

        let result: serde_json::Value = response.json().context("Failed to parse response")?;
        Ok(result)
    }

    pub fn delete_page(&self, page_id: &str) -> Result<serde_json::Value> {
        let page_id = normalize_page_id(page_id)?;
        let url = format!("{}/pages/{}", NOTION_API_BASE, page_id);

        let body = serde_json::json!({
            "archived": true
        });

        let response = self.execute_with_retry(|| {
            self.client
                .patch(&url)
                .header("Content-Type", "application/json")
                .json(&body)
        })?;

        let result: serde_json::Value = response.json().context("Failed to parse response")?;
        Ok(result)
    }

    pub fn append_code_block(
        &self,
        page_id: &str,
        code: &str,
        language: &str,
    ) -> Result<serde_json::Value> {
        let page_id = normalize_page_id(page_id)?;
        let url = format!("{}/blocks/{}/children", NOTION_API_BASE, page_id);

        let body = serde_json::json!({
            "children": [{
                "object": "block",
                "type": "code",
                "code": {
                    "rich_text": [{
                        "type": "text",
                        "text": { "content": code }
                    }],
                    "language": language
                }
            }]
        });

        let response = self.execute_with_retry(|| {
            self.client
                .patch(&url)
                .header("Content-Type", "application/json")
                .json(&body)
        })?;

        let result: serde_json::Value = response.json().context("Failed to parse response")?;
        Ok(result)
    }

    pub fn append_bookmark(
        &self,
        page_id: &str,
        url_str: &str,
        caption: Option<&str>,
    ) -> Result<serde_json::Value> {
        let page_id = normalize_page_id(page_id)?;
        let url = format!("{}/blocks/{}/children", NOTION_API_BASE, page_id);

        let bookmark_block = if let Some(cap) = caption {
            serde_json::json!({
                "object": "block",
                "type": "bookmark",
                "bookmark": {
                    "url": url_str,
                    "caption": [{
                        "type": "text",
                        "text": { "content": cap }
                    }]
                }
            })
        } else {
            serde_json::json!({
                "object": "block",
                "type": "bookmark",
                "bookmark": {
                    "url": url_str
                }
            })
        };

        let body = serde_json::json!({
            "children": [bookmark_block]
        });

        let response = self.execute_with_retry(|| {
            self.client
                .patch(&url)
                .header("Content-Type", "application/json")
                .json(&body)
        })?;

        let result: serde_json::Value = response.json().context("Failed to parse response")?;
        Ok(result)
    }

    pub fn delete_block(&self, block_id: &str) -> Result<()> {
        let block_id = normalize_page_id(block_id)?;
        let url = format!("{}/blocks/{}", NOTION_API_BASE, block_id);

        self.execute_with_retry(|| self.client.delete(&url))?;
        Ok(())
    }

    pub fn append_heading(
        &self,
        page_id: &str,
        text: &str,
        level: u8,
    ) -> Result<serde_json::Value> {
        let page_id = normalize_page_id(page_id)?;
        let url = format!("{}/blocks/{}/children", NOTION_API_BASE, page_id);

        let block_type = match level {
            1 => "heading_1",
            2 => "heading_2",
            _ => "heading_3",
        };

        let body = serde_json::json!({
            "children": [{
                "object": "block",
                "type": block_type,
                (block_type): {
                    "rich_text": [{
                        "type": "text",
                        "text": { "content": text }
                    }]
                }
            }]
        });

        let response = self.execute_with_retry(|| {
            self.client
                .patch(&url)
                .header("Content-Type", "application/json")
                .json(&body)
        })?;

        let result: serde_json::Value = response.json().context("Failed to parse response")?;
        Ok(result)
    }

    pub fn append_rich_text(
        &self,
        page_id: &str,
        segments: &[RichTextSegment],
    ) -> Result<serde_json::Value> {
        let page_id = normalize_page_id(page_id)?;
        let url = format!("{}/blocks/{}/children", NOTION_API_BASE, page_id);

        let rich_text: Vec<serde_json::Value> = segments
            .iter()
            .map(|seg| {
                let mut text_obj = serde_json::json!({
                    "content": seg.text
                });
                if let Some(ref link) = seg.link {
                    text_obj["link"] = serde_json::json!({ "url": link });
                }

                let mut annotations = serde_json::json!({});
                if seg.bold {
                    annotations["bold"] = serde_json::json!(true);
                }
                if seg.italic {
                    annotations["italic"] = serde_json::json!(true);
                }
                if seg.code {
                    annotations["code"] = serde_json::json!(true);
                }

                serde_json::json!({
                    "type": "text",
                    "text": text_obj,
                    "annotations": annotations
                })
            })
            .collect();

        let body = serde_json::json!({
            "children": [{
                "object": "block",
                "type": "paragraph",
                "paragraph": {
                    "rich_text": rich_text
                }
            }]
        });

        let response = self.execute_with_retry(|| {
            self.client
                .patch(&url)
                .header("Content-Type", "application/json")
                .json(&body)
        })?;

        let result: serde_json::Value = response.json().context("Failed to parse response")?;
        Ok(result)
    }

    pub fn append_divider(&self, page_id: &str) -> Result<serde_json::Value> {
        let page_id = normalize_page_id(page_id)?;
        let url = format!("{}/blocks/{}/children", NOTION_API_BASE, page_id);

        let body = serde_json::json!({
            "children": [{
                "object": "block",
                "type": "divider",
                "divider": {}
            }]
        });

        let response = self.execute_with_retry(|| {
            self.client
                .patch(&url)
                .header("Content-Type", "application/json")
                .json(&body)
        })?;

        let result: serde_json::Value = response.json().context("Failed to parse response")?;
        Ok(result)
    }

    pub fn append_bulleted_list(
        &self,
        page_id: &str,
        items: &[String],
    ) -> Result<serde_json::Value> {
        let page_id = normalize_page_id(page_id)?;
        let url = format!("{}/blocks/{}/children", NOTION_API_BASE, page_id);

        let children: Vec<serde_json::Value> = items
            .iter()
            .map(|item| {
                serde_json::json!({
                    "object": "block",
                    "type": "bulleted_list_item",
                    "bulleted_list_item": {
                        "rich_text": [{
                            "type": "text",
                            "text": { "content": item }
                        }]
                    }
                })
            })
            .collect();

        let body = serde_json::json!({
            "children": children
        });

        let response = self.execute_with_retry(|| {
            self.client
                .patch(&url)
                .header("Content-Type", "application/json")
                .json(&body)
        })?;

        let result: serde_json::Value = response.json().context("Failed to parse response")?;
        Ok(result)
    }

    pub fn query_database(
        &self,
        database_id: &str,
        filter: Option<&str>,
        sort: Option<&str>,
        direction: &str,
        limit: usize,
    ) -> Result<Vec<serde_json::Value>> {
        if limit == 0 {
            return Ok(Vec::new());
        }

        let database_id = normalize_page_id(database_id)?;
        let url = format!("{}/databases/{}/query", NOTION_API_BASE, database_id);
        let mut all_results = Vec::new();
        let mut start_cursor: Option<String> = None;

        loop {
            let remaining = limit.saturating_sub(all_results.len());
            let page_size = remaining.clamp(1, 100);

            let mut body = serde_json::json!({
                "page_size": page_size
            });

            if let Some(cursor) = &start_cursor {
                body["start_cursor"] = serde_json::json!(cursor);
            }

            if let Some(filter_str) = filter {
                if let Some((prop_part, value)) = filter_str.split_once('=') {
                    let (prop, filter_type) = if let Some((p, t)) = prop_part.split_once(':') {
                        (p.trim(), t.trim())
                    } else {
                        (prop_part.trim(), "rich_text")
                    };

                    let filter_value = match filter_type {
                        "title" => serde_json::json!({
                            "property": prop,
                            "title": { "contains": value.trim() }
                        }),
                        "select" => serde_json::json!({
                            "property": prop,
                            "select": { "equals": value.trim() }
                        }),
                        "checkbox" => serde_json::json!({
                            "property": prop,
                            "checkbox": { "equals": value.trim().to_lowercase() == "true" }
                        }),
                        "number" => {
                            let num: f64 = value.trim().parse().unwrap_or(0.0);
                            serde_json::json!({
                                "property": prop,
                                "number": { "equals": num }
                            })
                        }
                        _ => serde_json::json!({
                            "property": prop,
                            "rich_text": { "contains": value.trim() }
                        }),
                    };
                    body["filter"] = filter_value;
                }
            }

            if let Some(sort_prop) = sort {
                body["sorts"] = serde_json::json!([{
                    "property": sort_prop,
                    "direction": if direction == "asc" { "ascending" } else { "descending" }
                }]);
            }

            let body_clone = body.clone();
            let url_clone = url.clone();
            let response = self.execute_with_retry(|| {
                self.client
                    .post(&url_clone)
                    .header("Content-Type", "application/json")
                    .json(&body_clone)
            })?;

            let result: serde_json::Value = response.json().context("Failed to parse response")?;

            if let Some(results) = result.get("results").and_then(|r| r.as_array()) {
                all_results.extend(results.clone());
            }

            let has_more = result
                .get("has_more")
                .and_then(|h| h.as_bool())
                .unwrap_or(false);
            if !has_more || all_results.len() >= limit {
                break;
            }

            start_cursor = result
                .get("next_cursor")
                .and_then(|c| c.as_str())
                .map(String::from);
            if start_cursor.is_none() {
                break;
            }
        }

        Ok(all_results)
    }

    /// Move a page to a new parent by copying content and deleting original
    pub fn move_page(
        &self,
        page_id: &str,
        new_parent_id: &str,
        delete_original: bool,
    ) -> Result<serde_json::Value> {
        let page_id = normalize_page_id(page_id)?;
        let new_parent_id = normalize_page_id(new_parent_id)?;

        // 1. Get original page info (title)
        // Note: For database pages, title property name can vary (e.g., "Name", "Title")
        // So we find the property with type="title" instead of assuming name="title"
        eprintln!("{} Reading original page...", "".blue());
        let page = self.get_page(&page_id)?;
        let title = page
            .get("properties")
            .and_then(|p| p.as_object())
            .and_then(|props| {
                // Find property where type == "title"
                props
                    .values()
                    .find(|v| v.get("type").and_then(|t| t.as_str()) == Some("title"))
            })
            .and_then(|t| t.get("title"))
            .and_then(|t| t.as_array())
            .and_then(|arr| arr.first())
            .and_then(|t| t.get("plain_text"))
            .and_then(|t| t.as_str())
            .unwrap_or("Untitled");

        // 2. Get all blocks from original page
        eprintln!("{} Fetching blocks...", "".blue());
        let blocks = self.get_blocks(&page_id)?;

        // 3. Create new page under new parent
        eprintln!("{} Creating new page under new parent...", "".blue());
        let new_page = self.create_page(&new_parent_id, title, None)?;
        let new_page_id = new_page
            .get("id")
            .and_then(|id| id.as_str())
            .context("Failed to get new page ID")?;

        // 4. Copy blocks to new page
        if !blocks.is_empty() {
            eprintln!("{} Copying {} blocks...", "".blue(), blocks.len());
            self.copy_blocks_to_page(new_page_id, &blocks)?;
        }

        // 5. Optionally delete original page
        if delete_original {
            eprintln!("{} Archiving original page...", "".blue());
            self.delete_page(&page_id)?;
        }

        Ok(new_page)
    }

    /// Copy blocks to a page (handles nested blocks recursively)
    fn copy_blocks_to_page(&self, page_id: &str, blocks: &[serde_json::Value]) -> Result<()> {
        let url = format!("{}/blocks/{}/children", NOTION_API_BASE, page_id);

        // Process blocks in batches of 100 (Notion API limit)
        for chunk in blocks.chunks(100) {
            let converted: Vec<(serde_json::Value, Option<String>)> = chunk
                .iter()
                .filter_map(|block| {
                    let converted = self.convert_block_for_copy(block)?;
                    // Track original block ID if it has children
                    let original_id = if block.get("has_children") == Some(&serde_json::json!(true))
                    {
                        block.get("id").and_then(|id| id.as_str()).map(String::from)
                    } else {
                        None
                    };
                    Some((converted, original_id))
                })
                .collect();

            if converted.is_empty() {
                continue;
            }

            let children: Vec<serde_json::Value> =
                converted.iter().map(|(b, _)| b.clone()).collect();
            let body = serde_json::json!({ "children": children });

            let response = self.execute_with_retry(|| {
                self.client
                    .patch(&url)
                    .header("Content-Type", "application/json")
                    .json(&body)
            })?;

            // Get created block IDs to copy children recursively
            let created: serde_json::Value = response.json().context("Failed to parse response")?;
            if let Some(results) = created.get("results").and_then(|r| r.as_array()) {
                for (i, (_, original_id)) in converted.iter().enumerate() {
                    if let Some(orig_id) = original_id {
                        if let Some(new_block) = results.get(i) {
                            if let Some(new_id) = new_block.get("id").and_then(|id| id.as_str()) {
                                // Recursively copy children
                                let child_blocks = self.get_blocks(orig_id)?;
                                if !child_blocks.is_empty() {
                                    self.copy_blocks_to_page(new_id, &child_blocks)?;
                                }
                            }
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Convert a block for copying (remove IDs, timestamps, etc.)
    fn convert_block_for_copy(&self, block: &serde_json::Value) -> Option<serde_json::Value> {
        let block_type = block.get("type")?.as_str()?;
        let content = block.get(block_type)?;

        // Build new block with just type and content
        let mut new_block = serde_json::json!({
            "object": "block",
            "type": block_type,
        });

        // Copy the type-specific content
        new_block[block_type] = content.clone();

        // Remove fields that shouldn't be copied
        if let Some(obj) = new_block.get_mut(block_type) {
            if let Some(map) = obj.as_object_mut() {
                map.remove("id");
                map.remove("created_time");
                map.remove("last_edited_time");
                map.remove("created_by");
                map.remove("last_edited_by");
                map.remove("has_children");
                map.remove("archived");
                map.remove("in_trash");
            }
        }

        Some(new_block)
    }
}