zenith-tool 0.0.0-beta.1

The Zenith command-line interface (the `zenith` binary) for the design-document toolchain.
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
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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
//! Document-level inspect logic for `zenith inspect`.
//!
//! The public entry point [`run`] operates entirely on in-memory source text;
//! the caller is responsible for all filesystem I/O.
//!
//! The tree-building pass is decoupled from printing so it can be tested
//! directly: [`build_doc_tree`] / [`find_node_tree`] return [`PageEntry`] /
//! [`NodeEntry`] values that serialise to JSON and render to human-readable
//! format.

use std::collections::BTreeMap;

use zenith_core::{
    Dimension, FrameNode, GroupNode, KdlAdapter, KdlSource, Node, Page, PropertyValue,
    ResolvedToken, ResolvedValue, Unit, resolve_tokens,
};

use crate::commands::serialize_pretty;
use crate::json_types::RecipeInspectJson;

use super::recipes;

// ── Error type ────────────────────────────────────────────────────────────────

/// Error produced by the inspect command.
#[derive(Debug)]
pub struct InspectCmdErr {
    /// Human-readable message.
    pub message: String,
    /// Recommended exit code.
    pub exit_code: u8,
}

impl InspectCmdErr {
    fn new(msg: impl Into<String>, exit_code: u8) -> Self {
        Self {
            message: msg.into(),
            exit_code,
        }
    }
}

// ── Tree representation ───────────────────────────────────────────────────────

/// The geometry summary emitted per node.  Missing fields are `None` when the
/// node kind does not carry that property (e.g. `polygon` has no bbox).
#[derive(Debug, Clone, serde::Serialize)]
pub struct NodeGeometry {
    /// Left edge (px) for bbox nodes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub x: Option<f64>,
    /// Top edge (px) for bbox nodes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub y: Option<f64>,
    /// Width (px) for bbox nodes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub w: Option<f64>,
    /// Height (px) for bbox nodes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub h: Option<f64>,
    /// First endpoint x (px) for `line`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub x1: Option<f64>,
    /// First endpoint y (px) for `line`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub y1: Option<f64>,
    /// Second endpoint x (px) for `line`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub x2: Option<f64>,
    /// Second endpoint y (px) for `line`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub y2: Option<f64>,
    /// Point count for `polygon`/`polyline`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub point_count: Option<usize>,
}

/// A single node in the inspect tree.
#[derive(Debug, Clone, serde::Serialize)]
pub struct NodeEntry {
    pub id: String,
    pub kind: String,
    /// The node's `role` attribute, when authored. Surfacing it lets consumers
    /// group same-role nodes (e.g. every `role="heading"`) and reason about
    /// cross-page consistency without re-parsing the source.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    pub geometry: Option<NodeGeometry>,
    pub visible: Option<bool>,
    pub locked: Option<bool>,
    pub children: Vec<NodeEntry>,
}

/// The resolved token table used to turn `(token)"id"` dimension refs into px
/// values. Built once per `inspect` run from the document's `tokens` block.
type Resolved = BTreeMap<String, ResolvedToken>;

/// A page in the inspect tree.
#[derive(Debug, Clone, serde::Serialize)]
pub struct PageEntry {
    pub id: String,
    pub name: Option<String>,
    pub width: f64,
    pub height: f64,
    pub children: Vec<NodeEntry>,
}

/// The top-level JSON envelope for `inspect`.
#[derive(Debug, serde::Serialize)]
pub struct InspectOutput {
    pub schema: &'static str,
    pub pages: Vec<PageEntry>,
    /// Empty when the document has no `recipes` block.
    pub recipes: Vec<RecipeInspectJson>,
}

/// The subtree rooted at a single found node (used for `--node <ID>`).
#[derive(Debug, serde::Serialize)]
pub struct InspectNodeOutput {
    pub schema: &'static str,
    pub node: NodeEntry,
}

// ── Public entry point ────────────────────────────────────────────────────────

/// Run `zenith inspect`.
///
/// - `src`      — raw `.zen` source text.
/// - `node_id`  — when `Some`, restrict output to the subtree rooted at that id.
/// - `json`     — emit JSON instead of the human-readable tree.
///
/// Returns a formatted string on success, or an [`InspectCmdErr`] on parse
/// error, not-found error, etc.
pub fn run(src: &str, node_id: Option<&str>, json: bool) -> Result<String, InspectCmdErr> {
    // Parse ─────────────────────────────────────────────────────────────────
    let doc = KdlAdapter
        .parse(src.as_bytes())
        .map_err(|e| InspectCmdErr::new(format!("error[parse.error]: {}", e.message), 2))?;

    let resolved = resolve_tokens(&doc.tokens).resolved;

    if let Some(id) = node_id {
        // --node <ID>: find the subtree rooted at that node.
        let entry = find_node_tree(&doc.body.pages, id, &resolved)
            .ok_or_else(|| InspectCmdErr::new(format!("error: node '{}' not found", id), 2))?;

        let out = if json {
            let output = InspectNodeOutput {
                schema: "zenith-inspect-v1",
                node: entry,
            };
            serialize_pretty(&output)
        } else {
            render_node_human(&entry, 0).trim_end().to_owned()
        };
        Ok(out)
    } else {
        // Whole document.
        let pages = build_doc_tree(&doc.body.pages, &resolved);

        let out = if json {
            let recipe_entries = recipes::build_recipe_entries(&doc.recipes);
            let output = InspectOutput {
                schema: "zenith-inspect-v1",
                pages,
                recipes: recipe_entries,
            };
            serialize_pretty(&output)
        } else {
            let mut text = render_pages_human(&pages);
            let recipe_section = recipes::render_recipes_human(&doc.recipes);
            if !recipe_section.is_empty() {
                text.push('\n');
                text.push('\n');
                text.push_str(&recipe_section);
            }
            text
        };
        Ok(out)
    }
}

// ── Token-efficient summary (MCP) ───────────────────────────────────────────────

/// Build a token-minimal structured summary of a document's node tree.
///
/// This is the shape the MCP `zenith_inspect` tool returns: instead of the full
/// recursive tree with geometry on every node, it returns a *shallow* view.
///
/// - `node`   — when `Some`, summarise only the subtree rooted at that id.
/// - `depth`  — how many node levels below each page (or below `node`) to expand.
///   Deeper children collapse to a `childCount`. `0` shows only the top level.
/// - `detail` — when `true`, re-include `geometry`/`visible`/`locked` per node.
///
/// Returns a [`serde_json::Value`] ready to embed as the tool's structured
/// result; the caller decides inline-vs-offload by serialized size.
pub fn summary(
    src: &str,
    node: Option<&str>,
    depth: usize,
    detail: bool,
) -> Result<serde_json::Value, InspectCmdErr> {
    let doc = KdlAdapter
        .parse(src.as_bytes())
        .map_err(|e| InspectCmdErr::new(format!("error[parse.error]: {}", e.message), 2))?;

    let resolved = resolve_tokens(&doc.tokens).resolved;

    if let Some(id) = node {
        let entry = find_node_tree(&doc.body.pages, id, &resolved)
            .ok_or_else(|| InspectCmdErr::new(format!("error: node '{id}' not found"), 2))?;
        Ok(serde_json::json!({
            "schema": "zenith-inspect-summary-v1",
            "node": trim_node(&entry, depth, detail),
        }))
    } else {
        let pages = build_doc_tree(&doc.body.pages, &resolved);
        let page_values: Vec<serde_json::Value> =
            pages.iter().map(|p| trim_page(p, depth, detail)).collect();
        Ok(serde_json::json!({
            "schema": "zenith-inspect-summary-v1",
            "pages": page_values,
            "recipe_count": doc.recipes.len(),
        }))
    }
}

/// Trim a [`PageEntry`] to the shallow summary shape.
fn trim_page(p: &PageEntry, depth: usize, detail: bool) -> serde_json::Value {
    let mut obj = serde_json::Map::new();
    obj.insert("id".into(), p.id.clone().into());
    if let Some(name) = &p.name {
        obj.insert("name".into(), name.clone().into());
    }
    obj.insert("width".into(), p.width.into());
    obj.insert("height".into(), p.height.into());
    insert_children(&mut obj, &p.children, depth, detail);
    serde_json::Value::Object(obj)
}

/// Trim a [`NodeEntry`] to the shallow summary shape, recursing `depth` levels.
fn trim_node(n: &NodeEntry, depth: usize, detail: bool) -> serde_json::Value {
    let mut obj = serde_json::Map::new();
    obj.insert("id".into(), n.id.clone().into());
    obj.insert("kind".into(), n.kind.clone().into());
    if detail {
        if let Some(role) = &n.role {
            obj.insert("role".into(), role.clone().into());
        }
        if let Some(g) = &n.geometry {
            obj.insert(
                "geometry".into(),
                serde_json::to_value(g).unwrap_or(serde_json::Value::Null),
            );
        }
        if let Some(v) = n.visible {
            obj.insert("visible".into(), v.into());
        }
        if let Some(l) = n.locked {
            obj.insert("locked".into(), l.into());
        }
    }
    insert_children(&mut obj, &n.children, depth, detail);
    serde_json::Value::Object(obj)
}

/// Insert either an expanded `children` array (when `depth > 0`) or a collapsed
/// `child_count` (when `depth == 0`), omitting both when there are no children.
fn insert_children(
    obj: &mut serde_json::Map<String, serde_json::Value>,
    children: &[NodeEntry],
    depth: usize,
    detail: bool,
) {
    if children.is_empty() {
        return;
    }
    if depth == 0 {
        obj.insert("child_count".into(), children.len().into());
    } else {
        let kids: Vec<serde_json::Value> = children
            .iter()
            .map(|c| trim_node(c, depth - 1, detail))
            .collect();
        obj.insert("children".into(), serde_json::Value::Array(kids));
    }
}

// ── Tree builders ─────────────────────────────────────────────────────────────

/// Build the full page tree for all pages in the document (in order).
///
/// `resolved` is the document's resolved token table; it turns `(token)"id"`
/// dimension refs into px values in each node's geometry.
pub fn build_doc_tree(pages: &[Page], resolved: &Resolved) -> Vec<PageEntry> {
    pages
        .iter()
        .map(|p| build_page_entry(p, resolved))
        .collect()
}

fn build_page_entry(page: &Page, resolved: &Resolved) -> PageEntry {
    PageEntry {
        id: page.id.clone(),
        name: page.name.clone(),
        width: dim_to_f64(&page.width),
        height: dim_to_f64(&page.height),
        children: page
            .children
            .iter()
            .map(|n| build_node_entry(n, resolved))
            .collect(),
    }
}

fn build_node_entry(node: &Node, resolved: &Resolved) -> NodeEntry {
    match node {
        Node::Rect(n) => NodeEntry {
            id: n.id.clone(),
            kind: "rect".into(),
            role: n.role.clone(),
            geometry: bbox_geom(
                n.x.as_ref(),
                n.y.as_ref(),
                n.w.as_ref(),
                n.h.as_ref(),
                resolved,
            ),
            visible: n.visible,
            locked: n.locked,
            children: vec![],
        },
        Node::Ellipse(n) => NodeEntry {
            id: n.id.clone(),
            kind: "ellipse".into(),
            role: n.role.clone(),
            geometry: bbox_geom(
                n.x.as_ref(),
                n.y.as_ref(),
                n.w.as_ref(),
                n.h.as_ref(),
                resolved,
            ),
            visible: n.visible,
            locked: n.locked,
            children: vec![],
        },
        Node::Line(n) => NodeEntry {
            id: n.id.clone(),
            kind: "line".into(),
            role: n.role.clone(),
            geometry: Some(NodeGeometry {
                x: None,
                y: None,
                w: None,
                h: None,
                x1: n.x1.as_ref().map(dim_to_f64),
                y1: n.y1.as_ref().map(dim_to_f64),
                x2: n.x2.as_ref().map(dim_to_f64),
                y2: n.y2.as_ref().map(dim_to_f64),
                point_count: None,
            }),
            visible: n.visible,
            locked: n.locked,
            children: vec![],
        },
        Node::Text(n) => NodeEntry {
            id: n.id.clone(),
            kind: "text".into(),
            role: n.role.clone(),
            geometry: bbox_geom(
                n.x.as_ref(),
                n.y.as_ref(),
                n.w.as_ref(),
                n.h.as_ref(),
                resolved,
            ),
            visible: n.visible,
            locked: n.locked,
            children: vec![],
        },
        Node::Code(n) => NodeEntry {
            id: n.id.clone(),
            kind: "code".into(),
            role: n.role.clone(),
            geometry: bbox_geom(
                n.x.as_ref(),
                n.y.as_ref(),
                n.w.as_ref(),
                n.h.as_ref(),
                resolved,
            ),
            visible: n.visible,
            locked: n.locked,
            children: vec![],
        },
        Node::Image(n) => NodeEntry {
            id: n.id.clone(),
            kind: "image".into(),
            role: n.role.clone(),
            geometry: bbox_geom(
                n.x.as_ref(),
                n.y.as_ref(),
                n.w.as_ref(),
                n.h.as_ref(),
                resolved,
            ),
            visible: n.visible,
            locked: n.locked,
            children: vec![],
        },
        Node::Frame(n) => NodeEntry {
            id: n.id.clone(),
            kind: "frame".into(),
            role: n.role.clone(),
            geometry: bbox_geom(
                n.x.as_ref(),
                n.y.as_ref(),
                n.w.as_ref(),
                n.h.as_ref(),
                resolved,
            ),
            visible: n.visible,
            locked: n.locked,
            children: n
                .children
                .iter()
                .map(|c| build_node_entry(c, resolved))
                .collect(),
        },
        Node::Group(n) => NodeEntry {
            id: n.id.clone(),
            kind: "group".into(),
            role: n.role.clone(),
            geometry: bbox_geom(
                n.x.as_ref(),
                n.y.as_ref(),
                n.w.as_ref(),
                n.h.as_ref(),
                resolved,
            ),
            visible: n.visible,
            locked: n.locked,
            children: n
                .children
                .iter()
                .map(|c| build_node_entry(c, resolved))
                .collect(),
        },
        Node::Polygon(n) => NodeEntry {
            id: n.id.clone(),
            kind: "polygon".into(),
            role: n.role.clone(),
            geometry: Some(NodeGeometry {
                x: None,
                y: None,
                w: None,
                h: None,
                x1: None,
                y1: None,
                x2: None,
                y2: None,
                point_count: Some(n.points.len()),
            }),
            visible: n.visible,
            locked: n.locked,
            children: vec![],
        },
        Node::Polyline(n) => NodeEntry {
            id: n.id.clone(),
            kind: "polyline".into(),
            role: n.role.clone(),
            geometry: Some(NodeGeometry {
                x: None,
                y: None,
                w: None,
                h: None,
                x1: None,
                y1: None,
                x2: None,
                y2: None,
                point_count: Some(n.points.len()),
            }),
            visible: n.visible,
            locked: n.locked,
            children: vec![],
        },
        Node::Instance(n) => NodeEntry {
            id: n.id.clone(),
            kind: "instance".into(),
            role: n.role.clone(),
            // An instance carries only an x/y origin (no w/h box); its x/y stay
            // raw `Dimension` (not token-ref geometry), so report them directly.
            geometry: Some(NodeGeometry {
                x: opt_dim_to_f64(n.x.as_ref()),
                y: opt_dim_to_f64(n.y.as_ref()),
                w: None,
                h: None,
                x1: None,
                y1: None,
                x2: None,
                y2: None,
                point_count: None,
            }),
            visible: n.visible,
            locked: n.locked,
            children: vec![],
        },
        Node::Field(n) => NodeEntry {
            id: n.id.clone(),
            kind: "field".into(),
            role: n.role.clone(),
            // A field carries an x/y/w/h box (any of which may be omitted, in
            // which case it defaults to the page live area at compile time).
            geometry: bbox_geom(
                n.x.as_ref(),
                n.y.as_ref(),
                n.w.as_ref(),
                n.h.as_ref(),
                resolved,
            ),
            visible: n.visible,
            locked: n.locked,
            children: vec![],
        },
        Node::Toc(n) => NodeEntry {
            id: n.id.clone(),
            kind: "toc".into(),
            role: n.role.clone(),
            // A toc carries a real x/y/w/h box (it must declare its own
            // geometry for correct positioning).
            geometry: bbox_geom(
                n.x.as_ref(),
                n.y.as_ref(),
                n.w.as_ref(),
                n.h.as_ref(),
                resolved,
            ),
            visible: n.visible,
            locked: n.locked,
            children: vec![],
        },
        Node::Footnote(n) => NodeEntry {
            id: n.id.clone(),
            kind: "footnote".into(),
            role: n.role.clone(),
            // A footnote has NO geometry (the renderer positions it in the
            // bottom zone); report no geometry, visible, or locked.
            geometry: None,
            visible: None,
            locked: None,
            children: vec![],
        },
        Node::Table(n) => NodeEntry {
            id: n.id.clone(),
            kind: "table".into(),
            role: n.role.clone(),
            geometry: bbox_geom(
                n.x.as_ref(),
                n.y.as_ref(),
                n.w.as_ref(),
                n.h.as_ref(),
                resolved,
            ),
            visible: n.visible,
            locked: n.locked,
            // Report each cell's child nodes (flattened in row→cell order) so a
            // table's content is visible in the inspect tree.
            children: n
                .rows
                .iter()
                .flat_map(|row| row.cells.iter())
                .flat_map(|cell| cell.children.iter())
                .map(|c| build_node_entry(c, resolved))
                .collect(),
        },
        Node::Shape(n) => NodeEntry {
            id: n.id.clone(),
            kind: "shape".into(),
            role: n.role.clone(),
            geometry: bbox_geom(
                n.x.as_ref(),
                n.y.as_ref(),
                n.w.as_ref(),
                n.h.as_ref(),
                resolved,
            ),
            visible: n.visible,
            locked: n.locked,
            // A shape owns label spans (TextSpans), not child Nodes, so it has
            // no child entries in the inspect tree.
            children: vec![],
        },
        Node::Connector(n) => NodeEntry {
            id: n.id.clone(),
            kind: "connector".into(),
            role: n.role.clone(),
            // A connector has no authored bbox — its endpoints are derived from
            // its targets' boxes at compile time.
            geometry: None,
            visible: n.visible,
            locked: n.locked,
            children: vec![],
        },
        Node::Pattern(n) => NodeEntry {
            id: n.id.clone(),
            kind: "pattern".into(),
            role: n.role.clone(),
            geometry: bbox_geom(
                n.x.as_ref(),
                n.y.as_ref(),
                n.w.as_ref(),
                n.h.as_ref(),
                resolved,
            ),
            visible: n.visible,
            locked: n.locked,
            children: vec![],
        },
        Node::Chart(n) => NodeEntry {
            id: n.id.clone(),
            kind: "chart".into(),
            role: n.role.clone(),
            geometry: bbox_geom(
                n.x.as_ref(),
                n.y.as_ref(),
                n.w.as_ref(),
                n.h.as_ref(),
                resolved,
            ),
            visible: n.visible,
            locked: n.locked,
            children: vec![],
        },
        Node::Unknown(n) => NodeEntry {
            id: n.id.clone().unwrap_or_default(),
            kind: n.kind.clone(),
            // An unknown (library) node kind carries no typed `role` field.
            role: None,
            geometry: None,
            visible: None,
            locked: None,
            children: n
                .children
                .iter()
                .map(|c| build_node_entry(c, resolved))
                .collect(),
        },
    }
}

// ── Node finder ───────────────────────────────────────────────────────────────

/// Search all pages (depth-first, in source order) for a node with the given
/// id.  Returns a fully-built [`NodeEntry`] subtree when found.
pub fn find_node_tree(pages: &[Page], id: &str, resolved: &Resolved) -> Option<NodeEntry> {
    for page in pages {
        if let Some(entry) = search_nodes(&page.children, id, resolved) {
            return Some(entry);
        }
    }
    None
}

fn search_nodes(nodes: &[Node], id: &str, resolved: &Resolved) -> Option<NodeEntry> {
    for node in nodes {
        // Check if this node matches.
        let node_id = node_id_str(node);
        if node_id == id {
            return Some(build_node_entry(node, resolved));
        }
        // Recurse into Frame/Group/Unknown children via node_children.
        if let Some(children) = node_children(node)
            && let Some(found) = search_nodes(children, id, resolved)
        {
            return Some(found);
        }
        // Recurse into table cell children (node_children returns None for Table).
        if let Node::Table(t) = node {
            for row in &t.rows {
                for cell in &row.cells {
                    if let Some(found) = search_nodes(&cell.children, id, resolved) {
                        return Some(found);
                    }
                }
            }
        }
    }
    None
}

/// Return the `id` field of a node as a `&str`.
fn node_id_str(node: &Node) -> &str {
    match node {
        Node::Rect(n) => &n.id,
        Node::Ellipse(n) => &n.id,
        Node::Line(n) => &n.id,
        Node::Text(n) => &n.id,
        Node::Code(n) => &n.id,
        Node::Frame(n) => &n.id,
        Node::Group(n) => &n.id,
        Node::Image(n) => &n.id,
        Node::Polygon(n) => &n.id,
        Node::Polyline(n) => &n.id,
        Node::Instance(n) => &n.id,
        Node::Field(n) => &n.id,
        Node::Toc(n) => &n.id,
        Node::Footnote(n) => &n.id,
        Node::Table(n) => &n.id,
        Node::Shape(n) => &n.id,
        Node::Connector(n) => &n.id,
        Node::Pattern(n) => &n.id,
        Node::Chart(n) => &n.id,
        Node::Unknown(n) => n.id.as_deref().unwrap_or(""),
    }
}

/// Return a reference to a container node's children slice, or `None` for leaf
/// nodes.
fn node_children(node: &Node) -> Option<&[Node]> {
    match node {
        Node::Frame(FrameNode { children, .. }) | Node::Group(GroupNode { children, .. }) => {
            Some(children)
        }
        Node::Unknown(n) => Some(&n.children),
        Node::Rect(_)
        | Node::Ellipse(_)
        | Node::Line(_)
        | Node::Text(_)
        | Node::Code(_)
        | Node::Image(_)
        | Node::Polygon(_)
        | Node::Polyline(_)
        | Node::Instance(_)
        | Node::Field(_)
        | Node::Footnote(_)
        | Node::Toc(_)
        | Node::Table(_)
        | Node::Shape(_)
        | Node::Connector(_)
        | Node::Pattern(_)
        | Node::Chart(_) => None,
    }
}

// ── Geometry helpers ──────────────────────────────────────────────────────────

fn dim_to_f64(d: &Dimension) -> f64 {
    match d.unit {
        Unit::Pt => d.value * 96.0 / 72.0,
        Unit::Px | Unit::Pct | Unit::Deg | Unit::Unknown(_) => d.value,
    }
}

fn opt_dim_to_f64(d: Option<&Dimension>) -> Option<f64> {
    d.map(dim_to_f64)
}

/// A geometry property is `(px)N` literal OR `(token)"id"` dimension ref.
/// Inspect reports the resolved px value: a literal yields its own value; a
/// token ref is resolved against the document's token table. A ref that is
/// missing, cyclic, or not a dimension token has no px value, so it shows as
/// `None` (the field is omitted from the JSON).
fn opt_pv_to_f64(pv: Option<&PropertyValue>, resolved: &Resolved) -> Option<f64> {
    match pv? {
        PropertyValue::Dimension(d) => Some(dim_to_f64(d)),
        PropertyValue::TokenRef(id) => match resolved.get(id).map(|t| &t.value) {
            Some(ResolvedValue::Dimension(d)) => Some(dim_to_f64(d)),
            _ => None,
        },
        PropertyValue::Literal(_) | PropertyValue::DataRef(_) => None,
    }
}

fn bbox_geom(
    x: Option<&PropertyValue>,
    y: Option<&PropertyValue>,
    w: Option<&PropertyValue>,
    h: Option<&PropertyValue>,
    resolved: &Resolved,
) -> Option<NodeGeometry> {
    Some(NodeGeometry {
        x: opt_pv_to_f64(x, resolved),
        y: opt_pv_to_f64(y, resolved),
        w: opt_pv_to_f64(w, resolved),
        h: opt_pv_to_f64(h, resolved),
        x1: None,
        y1: None,
        x2: None,
        y2: None,
        point_count: None,
    })
}

// ── Human rendering ───────────────────────────────────────────────────────────

fn render_pages_human(pages: &[PageEntry]) -> String {
    let mut out = String::new();
    for page in pages {
        let name_part = page
            .name
            .as_deref()
            .map(|n| format!(" \"{}\"", n))
            .unwrap_or_default();
        out.push_str(&format!(
            "page {}{} ({}x{})\n",
            page.id, name_part, page.width, page.height
        ));
        for child in &page.children {
            out.push_str(&render_node_human(child, 1));
        }
    }
    out.trim_end().to_owned()
}

/// Render a single node (and its subtree) at the given indent depth.
/// Called by both the whole-document path and the `--node` subtree path.
fn render_node_human(node: &NodeEntry, depth: usize) -> String {
    let indent = "  ".repeat(depth);
    let geom = render_geom_summary(node);
    let flags = render_flags(node);
    let suffix = [geom, flags]
        .into_iter()
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join(" ");
    let suffix_part = if suffix.is_empty() {
        String::new()
    } else {
        format!("  {}", suffix)
    };

    let mut out = format!("{}{} {}{}\n", indent, node.kind, node.id, suffix_part);
    for child in &node.children {
        out.push_str(&render_node_human(child, depth + 1));
    }
    out
}

fn render_geom_summary(node: &NodeEntry) -> String {
    let Some(ref g) = node.geometry else {
        return String::new();
    };

    // bbox summary: x,y WxH
    if g.x.is_some() || g.y.is_some() || g.w.is_some() || g.h.is_some() {
        let x = g.x.unwrap_or(0.0);
        let y = g.y.unwrap_or(0.0);
        let w = g.w.unwrap_or(0.0);
        let h = g.h.unwrap_or(0.0);
        return format!(
            "{},{} {}x{}",
            fmt_f64(x),
            fmt_f64(y),
            fmt_f64(w),
            fmt_f64(h)
        );
    }

    // line endpoint summary
    if g.x1.is_some() || g.y1.is_some() || g.x2.is_some() || g.y2.is_some() {
        let x1 = g.x1.unwrap_or(0.0);
        let y1 = g.y1.unwrap_or(0.0);
        let x2 = g.x2.unwrap_or(0.0);
        let y2 = g.y2.unwrap_or(0.0);
        return format!(
            "({},{})→({},{})",
            fmt_f64(x1),
            fmt_f64(y1),
            fmt_f64(x2),
            fmt_f64(y2)
        );
    }

    // poly point count
    if let Some(count) = g.point_count {
        return format!("{} pts", count);
    }

    String::new()
}

fn render_flags(node: &NodeEntry) -> String {
    let mut flags = Vec::new();
    if node.visible == Some(false) {
        flags.push("[hidden]");
    }
    if node.locked == Some(true) {
        flags.push("[locked]");
    }
    flags.join(" ")
}

/// Format an `f64` without a trailing `.0` when the value is whole.
fn fmt_f64(v: f64) -> String {
    if v.fract() == 0.0 {
        (v as i64).to_string()
    } else {
        v.to_string()
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
#[path = "document_tests.rs"]
mod tests;