orbexa 0.0.4

Rust CLI for applying Codexa-generated Notion artifacts to managed Notion data sources and pages.
Documentation
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
use std::{collections::BTreeMap, env, path::PathBuf, process::ExitCode};

use orbexa::{
    artifact::{NotionPageArtifact, load_manifest, load_page_artifact},
    config::{LoadedConfig, RootConfig, load_config, resolve_config_path, resolve_state_dir},
    lock::{clear_root, load_lock, locked_page, resolve_lock_path, upsert_locked_page, write_lock},
    notion::{CreateDocumentPage, NotionClient, UpdateDocumentPage},
    registry::{
        RegistryRoot, WorkspaceRegistry, load_registry, registry_from_workspace_page,
        resolve_registry_path, upsert_root, write_registry,
    },
    render::{
        NotionIdentity, render_notion_markdown, rendered_content_hash, validate_link_targets,
    },
    state::{State, write_state},
};

fn main() -> ExitCode {
    match run(env::args().skip(1).collect()) {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            eprintln!("error: {error}");
            ExitCode::from(1)
        }
    }
}

fn run(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
    match args.as_slice() {
        [] => {
            print_help();
            Ok(())
        }
        [flag] if flag == "--version" || flag == "-V" => {
            println!("orbexa {}", orbexa::VERSION);
            Ok(())
        }
        [flag] if flag == "--help" || flag == "-h" => {
            print_help();
            Ok(())
        }
        [command] if command == "check" => check(None),
        [command, flag, path] if command == "check" && flag == "--config" => {
            check(Some(path.into()))
        }
        [command] if command == "init" => init(None, false),
        [command, flag] if command == "init" && flag == "--dry-run" => init(None, true),
        [command, flag, root] if command == "init" && flag == "--recreate-root" => {
            recreate_root(root, false)
        }
        [command, flag, root, dry]
            if command == "init" && flag == "--recreate-root" && dry == "--dry-run" =>
        {
            recreate_root(root, true)
        }
        [command, flag, path] if command == "init" && flag == "--config" => {
            init(Some(path.into()), false)
        }
        [command, flag, path, dry]
            if command == "init" && flag == "--config" && dry == "--dry-run" =>
        {
            init(Some(path.into()), true)
        }
        [command, input] if command == "apply" => apply(input.into(), false),
        [command, input, flag] if command == "apply" && flag == "--dry-run" => {
            apply(input.into(), true)
        }
        _ => {
            print_help();
            Err("invalid arguments".into())
        }
    }
}

fn check(config_path: Option<PathBuf>) -> Result<(), Box<dyn std::error::Error>> {
    let loaded = load_orbexa_config(config_path)?;
    let client = client(&loaded)?;
    let parent = client.retrieve_page(&loaded.config.notion.parent_page_id)?;
    println!("Orbexa check\n\nConfig:\n  {}", loaded.path.display());
    println!("\nNotion:\n  parent page id: {}", parent.id);
    println!(
        "  parent title:   {}",
        parent.title().unwrap_or_else(|| "<untitled>".into())
    );
    println!("  api version:    {}", loaded.config.notion.api_version);
    println!(
        "\nWorkspace target:\n  page: {}",
        loaded.config.workspace.page_name
    );
    println!("  roots:");
    for (key, root) in &loaded.config.workspace.roots {
        println!(
            "    {key}: {} / {}",
            root.database_name, root.data_source_name
        );
    }
    Ok(())
}

fn init(config_path: Option<PathBuf>, dry_run: bool) -> Result<(), Box<dyn std::error::Error>> {
    let loaded = load_orbexa_config(config_path)?;
    let registry_path = resolve_registry_path(&loaded.config)?;
    let client = client(&loaded)?;

    let Some(mut loaded_registry) = load_registry(&registry_path)? else {
        if dry_run {
            println!(
                "Orbexa init plan\n\nWould create workspace page:\n  {}",
                loaded.config.workspace.page_name
            );
            println!("Would write registry:\n  {}", registry_path.display());
            println!("A following init run would create roots:");
            for (key, root) in &loaded.config.workspace.roots {
                println!("  {key}: {}", root.database_name);
            }
            return Ok(());
        }
        let page = client.create_child_page(
            &loaded.config.notion.parent_page_id,
            &loaded.config.workspace.page_name,
            &loaded.config.workspace.appearance.icon,
            &loaded.config.workspace.appearance.cover,
        )?;
        let registry =
            registry_from_workspace_page(&loaded.config, page.id.clone(), page.url.clone());
        let written = write_registry(&registry_path, &registry)?;
        let state = State::workspace_page(
            loaded.config.notion.parent_page_id.clone(),
            page.id.clone(),
            loaded.config.workspace.page_name.clone(),
            page.url.clone(),
        );
        let state_path = write_state(&resolve_state_dir()?, &state)?;
        println!(
            "Orbexa init\n\nCreated workspace page:\n  {} {}",
            loaded.config.workspace.page_name, page.id
        );
        println!(
            "Wrote:\n  {}\n  {}",
            written.display(),
            state_path.display()
        );
        println!("\nNext: run `orbexa init` again to create configured roots.");
        return Ok(());
    };

    let workspace = client.retrieve_page(&loaded_registry.registry.notion.workspace_page_id)?;
    if workspace.in_trash {
        return Err("registered workspace page is in trash".into());
    }

    let mut changed = false;
    println!(
        "Orbexa init\n\nWorkspace:\n  {} {}",
        loaded_registry.registry.notion.workspace_page_name, workspace.id
    );
    println!("\nRoots:");
    for (key, root_config) in &loaded.config.workspace.roots {
        if let Some(root) = loaded_registry.registry.notion.roots.get(key) {
            validate_registered_root(&client, key, root)?;
            let added = if dry_run {
                let data_source = client.retrieve_data_source(&root.data_source_id)?;
                let missing = data_source.missing_managed_properties()?;
                if !missing.is_empty() {
                    println!("  {key}: would add properties {}", missing.join(", "));
                }
                missing
            } else {
                client.ensure_document_schema(&root.data_source_id)?
            };
            if added.is_empty() {
                println!(
                    "  {key}: verified {} {}",
                    root.database_name, root.database_id
                );
            } else if !dry_run {
                println!(
                    "  {key}: repaired {} {} (added {})",
                    root.database_name,
                    root.database_id,
                    added.join(", ")
                );
            }
            continue;
        }
        if dry_run {
            println!(
                "  {key}: would create {} / {}",
                root_config.database_name, root_config.data_source_name
            );
            continue;
        }
        let root = create_root(&client, &loaded_registry.registry, root_config)?;
        println!(
            "  {key}: created {} {}",
            root.database_name, root.database_id
        );
        upsert_root(&mut loaded_registry.registry, key.clone(), root);
        changed = true;
    }
    if changed {
        let path = write_registry(&registry_path, &loaded_registry.registry)?;
        println!("\nUpdated registry:\n  {}", path.display());
    } else if !dry_run {
        println!("\nNo changes made.");
    }
    Ok(())
}

fn recreate_root(root_key: &str, dry_run: bool) -> Result<(), Box<dyn std::error::Error>> {
    let loaded = load_orbexa_config(None)?;
    let root_config = loaded
        .config
        .workspace
        .roots
        .get(root_key)
        .ok_or_else(|| format!("unknown configured root `{root_key}`"))?;
    let registry_path = resolve_registry_path(&loaded.config)?;
    let mut loaded_registry = load_registry(&registry_path)?
        .ok_or("workspace registry is missing; run `orbexa init` first")?;
    let client = client(&loaded)?;
    let lock_path = resolve_lock_path(&loaded_registry.registry.name)?;
    let mut lock = load_lock(&lock_path)?;

    println!("Orbexa recreate root\n\nRoot: {root_key}");
    if let Some(current) = loaded_registry.registry.notion.roots.get(root_key) {
        println!(
            "Current database: {} {}",
            current.database_name, current.database_id
        );
    }
    if dry_run {
        println!(
            "Would create: {} / {}",
            root_config.database_name, root_config.data_source_name
        );
        println!(
            "Would clear {} page lock(s).",
            lock.pages.iter().filter(|p| p.root == root_key).count()
        );
        return Ok(());
    }
    let root = create_root(&client, &loaded_registry.registry, root_config)?;
    upsert_root(
        &mut loaded_registry.registry,
        root_key.to_string(),
        root.clone(),
    );
    let cleared = clear_root(&mut lock, root_key);
    write_registry(&registry_path, &loaded_registry.registry)?;
    write_lock(&lock_path, &lock)?;
    println!("Created: {} {}", root.database_name, root.database_id);
    println!("Cleared page locks: {cleared}");
    Ok(())
}

fn apply(input_dir: PathBuf, dry_run: bool) -> Result<(), Box<dyn std::error::Error>> {
    let loaded = load_orbexa_config(None)?;
    let registry_path = resolve_registry_path(&loaded.config)?;
    let loaded_registry = load_registry(&registry_path)?
        .ok_or("workspace registry is missing; run `orbexa init` first")?;
    let manifest = load_manifest(&input_dir)?;
    let client = client(&loaded)?;
    let lock_path = resolve_lock_path(&loaded_registry.registry.name)?;
    let mut lock = load_lock(&lock_path)?;

    let mut roots = BTreeMap::new();
    for (key, root) in &loaded_registry.registry.notion.roots {
        validate_registered_root(&client, key, root)?;
        roots.insert(key.clone(), root.clone());
    }

    let mut artifacts = Vec::new();
    for entry in &manifest.manifest.pages {
        let artifact = load_page_artifact(&input_dir, &entry.path)?.artifact;
        validate_artifact_target(&artifact, &loaded_registry.registry)?;
        if !roots.contains_key(&artifact.target.root) {
            return Err(format!(
                "artifact `{}` targets uninitialized root `{}`",
                artifact.document.id, artifact.target.root
            )
            .into());
        }
        artifacts.push(artifact);
    }
    validate_link_targets(&artifacts)?;

    println!(
        "Orbexa apply\n\nInput:\n  {}\nManifest:\n  {}",
        input_dir.display(),
        manifest.path.display()
    );

    if dry_run {
        return apply_dry_run(
            &client,
            &artifacts,
            &roots,
            &loaded.config.workspace.roots,
            &lock,
        );
    }

    let mut identities = BTreeMap::new();

    // Pass 1: establish every Notion page identity before rendering links.
    for artifact in &artifacts {
        let root = &roots[&artifact.target.root];
        let appearance = &loaded.config.workspace.roots[&artifact.target.root].appearance;

        let (page, identity_changed) = resolve_or_create_identity(
            &client,
            artifact,
            root,
            appearance,
            &loaded.config.sync.on_missing,
            locked_page(&lock, &artifact.document.id).cloned(),
        )?;

        let page_url = page
            .url
            .clone()
            .ok_or_else(|| format!("Notion page `{}` has no URL", page.id))?;
        identities.insert(
            artifact.document.id.clone(),
            NotionIdentity {
                page_id: page.id.clone(),
                page_url: page_url.clone(),
                title: artifact.document.title.clone(),
            },
        );

        if identity_changed {
            upsert_locked_page(&mut lock, artifact, page.id, Some(page_url), "");
        }
    }

    // Pass 2: resolve all logical links and update only changed pages.
    for artifact in &artifacts {
        let identity = &identities[&artifact.document.id];
        let rendered = render_notion_markdown(artifact, &identities)?;
        let appearance = &loaded.config.workspace.roots[&artifact.target.root].appearance;
        let rendered_hash = rendered_content_hash(artifact, &rendered, appearance);
        let existing = locked_page(&lock, &artifact.document.id)
            .cloned()
            .ok_or("page identity disappeared during apply")?;

        if existing.source_content_hash == artifact.source.content_hash
            && existing.rendered_content_hash == rendered_hash
        {
            println!(
                "Skip:\n  {} already synced to {}",
                artifact.document.id, identity.page_id
            );
            continue;
        }

        let appearance = &loaded.config.workspace.roots[&artifact.target.root].appearance;
        client.update_document_page(
            &identity.page_id,
            &UpdateDocumentPage {
                document_id: &artifact.document.id,
                sort_order: artifact.navigation.order,
                title: &artifact.document.title,
                description: &artifact.document.description,
                root: &artifact.navigation.root,
                product: &artifact.navigation.product,
                section: &artifact.navigation.section,
                kind: &artifact.document.kind,
                tags: &artifact.document.tags,
                status: &artifact.document.status,
                visibility: &artifact.document.visibility,
                icon: &appearance.icon,
                cover: &appearance.cover,
            },
        )?;
        client.replace_page_markdown(&identity.page_id, &rendered)?;

        upsert_locked_page(
            &mut lock,
            artifact,
            identity.page_id.clone(),
            Some(identity.page_url.clone()),
            rendered_hash,
        );
        println!("Updated:\n  {} {}", artifact.document.id, identity.page_id);
    }

    write_lock(&lock_path, &lock)?;
    Ok(())
}

fn apply_dry_run(
    client: &NotionClient,
    artifacts: &[NotionPageArtifact],
    roots: &BTreeMap<String, RegistryRoot>,
    root_configs: &BTreeMap<String, orbexa::config::RootConfig>,
    lock: &orbexa::lock::LockFile,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut identities = BTreeMap::new();
    let mut missing = std::collections::BTreeSet::new();
    let mut adopted = std::collections::BTreeSet::new();

    for artifact in artifacts {
        let root = &roots[&artifact.target.root];
        let locked = locked_page(lock, &artifact.document.id);
        if let Some(existing) = locked {
            if existing.root != artifact.target.root {
                return Err(format!(
                    "document `{}` moved from root `{}` to `{}`; explicit move support is not implemented yet",
                    artifact.document.id, existing.root, artifact.target.root
                )
                .into());
            }
            match client.retrieve_page(&existing.notion_page_id) {
                Ok(page) if !page.in_trash => {
                    if let Some(url) = page.url {
                        identities.insert(
                            artifact.document.id.clone(),
                            NotionIdentity {
                                page_id: page.id,
                                page_url: url,
                                title: artifact.document.title.clone(),
                            },
                        );
                        continue;
                    }
                }
                Ok(_) => {}
                Err(error) if error.is_not_found() => {}
                Err(error) => return Err(error.into()),
            }
        }

        let matches =
            client.query_pages_by_document_id(&root.data_source_id, &artifact.document.id)?;
        match matches.as_slice() {
            [page] => {
                let url = page
                    .url
                    .clone()
                    .ok_or_else(|| format!("Notion page `{}` has no URL", page.id))?;
                println!("Would adopt:\n  {} {}", artifact.document.id, page.id);
                adopted.insert(artifact.document.id.clone());
                identities.insert(
                    artifact.document.id.clone(),
                    NotionIdentity {
                        page_id: page.id.clone(),
                        page_url: url,
                        title: artifact.document.title.clone(),
                    },
                );
            }
            [] => {
                missing.insert(artifact.document.id.clone());
                println!(
                    "Would create:\n  {} → {}\n  Root: {}\n  Product: {}",
                    artifact.document.id,
                    root.database_name,
                    artifact.target.root,
                    artifact.navigation.product
                );
            }
            pages => {
                return Err(duplicate_document_id_error(artifact, pages).into());
            }
        }
    }

    for artifact in artifacts {
        if missing.contains(&artifact.document.id) {
            println!(
                "Would render after identity creation:\n  {}",
                artifact.document.id
            );
            continue;
        }
        if adopted.contains(&artifact.document.id) {
            println!("Would update adopted page:\n  {}", artifact.document.id);
            continue;
        }
        if artifact
            .links
            .iter()
            .any(|link| !identities.contains_key(&link.target_id))
        {
            println!(
                "Would refresh links after identity creation:\n  {}",
                artifact.document.id
            );
            continue;
        }

        let rendered = render_notion_markdown(artifact, &identities)?;
        let appearance = &root_configs[&artifact.target.root].appearance;
        let rendered_hash = rendered_content_hash(artifact, &rendered, appearance);
        let existing =
            locked_page(lock, &artifact.document.id).ok_or("dry-run identity has no lock entry")?;
        if existing.source_content_hash == artifact.source.content_hash
            && existing.rendered_content_hash == rendered_hash
        {
            println!(
                "Skip:\n  {} already synced to {}",
                artifact.document.id, existing.notion_page_id
            );
        } else {
            println!(
                "Would update:\n  {} {}",
                artifact.document.id, existing.notion_page_id
            );
        }
    }
    Ok(())
}

fn resolve_or_create_identity(
    client: &NotionClient,
    artifact: &NotionPageArtifact,
    root: &RegistryRoot,
    appearance: &orbexa::config::WorkspaceAppearance,
    on_missing: &str,
    locked: Option<orbexa::lock::LockedPage>,
) -> Result<(orbexa::notion::Page, bool), Box<dyn std::error::Error>> {
    if let Some(existing) = locked {
        if existing.root != artifact.target.root {
            return Err(format!(
                "document `{}` moved from root `{}` to `{}`; explicit move support is not implemented yet",
                artifact.document.id, existing.root, artifact.target.root
            )
            .into());
        }
        match client.retrieve_page(&existing.notion_page_id) {
            Ok(page) if !page.in_trash => return Ok((page, false)),
            Ok(_) => {
                if on_missing != "recreate" {
                    return Err(format!(
                        "locked page `{}` is in trash and sync.on_missing is `{on_missing}`",
                        existing.notion_page_id
                    )
                    .into());
                }
            }
            Err(error) if error.is_not_found() => {
                if on_missing != "recreate" {
                    return Err(format!(
                        "locked page `{}` is missing and sync.on_missing is `{on_missing}`",
                        existing.notion_page_id
                    )
                    .into());
                }
            }
            Err(error) => return Err(error.into()),
        }
    }

    let matches = client.query_pages_by_document_id(&root.data_source_id, &artifact.document.id)?;
    match matches.as_slice() {
        [page] => {
            println!("Adopted identity:\n  {} {}", artifact.document.id, page.id);
            Ok((page.clone(), true))
        }
        [] => Ok((
            create_placeholder_page(client, artifact, root, appearance)?,
            true,
        )),
        pages => Err(duplicate_document_id_error(artifact, pages).into()),
    }
}

fn duplicate_document_id_error(
    artifact: &NotionPageArtifact,
    pages: &[orbexa::notion::Page],
) -> String {
    let ids = pages
        .iter()
        .map(|page| page.id.as_str())
        .collect::<Vec<_>>()
        .join(", ");
    format!(
        "document `{}` has multiple live Notion pages in root `{}`: {ids}",
        artifact.document.id, artifact.target.root
    )
}

fn create_placeholder_page(
    client: &NotionClient,
    artifact: &NotionPageArtifact,
    root: &RegistryRoot,
    appearance: &orbexa::config::WorkspaceAppearance,
) -> Result<orbexa::notion::Page, Box<dyn std::error::Error>> {
    let page = client.create_document_page(&CreateDocumentPage {
        data_source_id: &root.data_source_id,
        document_id: &artifact.document.id,
        sort_order: artifact.navigation.order,
        title: &artifact.document.title,
        description: &artifact.document.description,
        root: &artifact.navigation.root,
        product: &artifact.navigation.product,
        section: &artifact.navigation.section,
        kind: &artifact.document.kind,
        tags: &artifact.document.tags,
        status: &artifact.document.status,
        visibility: &artifact.document.visibility,
        markdown: "_Orbexa is preparing this page._",
        icon: &appearance.icon,
        cover: &appearance.cover,
    })?;
    println!("Created identity:\n  {} {}", artifact.document.id, page.id);
    Ok(page)
}

fn create_root(
    client: &NotionClient,
    registry: &WorkspaceRegistry,
    config: &RootConfig,
) -> Result<RegistryRoot, Box<dyn std::error::Error>> {
    let database = client.create_database(
        &registry.notion.workspace_page_id,
        &config.database_name,
        &config.data_source_name,
    )?;
    let data_source_id = database
        .data_source_named(&config.data_source_name)
        .or_else(|| database.data_sources.first())
        .ok_or("created database did not return a data source")?
        .id
        .clone();
    Ok(RegistryRoot {
        database_name: config.database_name.clone(),
        database_id: database.id,
        data_source_name: config.data_source_name.clone(),
        data_source_id,
    })
}

fn validate_registered_root(
    client: &NotionClient,
    key: &str,
    root: &RegistryRoot,
) -> Result<(), Box<dyn std::error::Error>> {
    let database = client.retrieve_database(&root.database_id)?;
    if database.in_trash {
        return Err(format!("registered root `{key}` database `{}` is in trash; run `orbexa init --recreate-root {key}`", root.database_id).into());
    }
    if !database
        .data_sources
        .iter()
        .any(|source| source.id == root.data_source_id)
    {
        return Err(format!(
            "registered root `{key}` data source `{}` is missing",
            root.data_source_id
        )
        .into());
    }
    Ok(())
}

fn validate_artifact_target(
    artifact: &NotionPageArtifact,
    registry: &WorkspaceRegistry,
) -> Result<(), Box<dyn std::error::Error>> {
    if !artifact
        .target
        .workspace
        .eq_ignore_ascii_case(&registry.name)
    {
        return Err(format!(
            "artifact `{}` targets workspace `{}` but registry is `{}`",
            artifact.document.id, artifact.target.workspace, registry.name
        )
        .into());
    }
    if artifact.target.root != artifact.navigation.root {
        return Err(format!(
            "artifact `{}` target root and navigation root disagree",
            artifact.document.id
        )
        .into());
    }
    Ok(())
}

fn client(loaded: &LoadedConfig) -> Result<NotionClient, Box<dyn std::error::Error>> {
    Ok(NotionClient::new(
        notion_token()?,
        loaded.config.notion.api_version.clone(),
    ))
}
fn load_orbexa_config(path: Option<PathBuf>) -> Result<LoadedConfig, Box<dyn std::error::Error>> {
    Ok(load_config(resolve_config_path(path)?)?)
}
fn notion_token() -> Result<String, Box<dyn std::error::Error>> {
    let token = env::var("NOTION_API_KEY")
        .or_else(|_| env::var("NOTION_TOKEN"))
        .map_err(|_| "neither NOTION_API_KEY nor NOTION_TOKEN is set")?;
    if token.trim().is_empty() {
        return Err("Notion API token is empty".into());
    }
    Ok(token)
}
fn print_help() {
    println!(
        "Orbexa {}\n\nUSAGE:\n    orbexa check [--config <PATH>]\n    orbexa init [--dry-run] [--config <PATH>]\n    orbexa init --recreate-root <ROOT> [--dry-run]\n    orbexa apply <ARTIFACT_DIR> [--dry-run]\n",
        orbexa::VERSION
    );
}