dc_figma_import 0.39.2

Figma document serialization toolkit
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
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::{
    component_context::ComponentContext,
    error::Error,
    extended_layout_schema::ExtendedAutoLayout,
    figma_schema,
    image_context::{ImageContext, ImageContextSession},
    proxy_config::ProxyConfig,
    transform_flexbox::create_component_flexbox,
    variable_utils::create_variable,
};
use dc_bundle::definition::EncodedImageMap;
use dc_bundle::definition::NodeQuery;
use dc_bundle::figma_doc::FigmaDocInfo;
use dc_bundle::variable::variable_map::NameIdMap;
use dc_bundle::variable::{Collection, Mode, Variable, VariableMap};
use dc_bundle::view::view_data::{Container, View_data_type};
use dc_bundle::view::{ComponentInfo, ComponentOverrides, View, ViewData};
use dc_bundle::view_style::ViewStyle;
use log::{error, info, warn};
use protobuf::MessageField;
use std::{
    collections::{HashMap, HashSet},
    iter::FromIterator,
    sync::{LazyLock, Mutex},
};

const BASE_FILE_URL: &str = "https://api.figma.com/v1/files/";
const BASE_COMPONENT_URL: &str = "https://api.figma.com/v1/components/";
const BASE_PROJECT_URL: &str = "https://api.figma.com/v1/projects/";

/// Per-document cache for expensive data that doesn't change on text/color edits.
/// Populated on the initial full fetch and reused on subsequent update cycles.
#[derive(Clone)]
struct SmartCacheEntry {
    /// Cached /images API response (image hash → URL)
    image_refs: HashMap<String, Option<String>>,
    /// Cached /variables API response
    variables_responses: HashMap<String, figma_schema::VariablesResponse>,
    /// Cached remote component prefetch results (component key → JSON)
    prefetched_components: HashMap<String, String>,
    /// Cached variant nodes from remote libraries
    variant_nodes: HashMap<String, figma_schema::Node>,
    /// Component keys that previously failed (404, 429, etc.)
    failed_component_keys: HashSet<String>,
}

/// Process-wide smart cache, keyed by Figma document ID.
static SMART_CACHE: LazyLock<Mutex<HashMap<String, SmartCacheEntry>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum HiddenNodePolicy {
    Skip,
    Keep,
}

/// Helper function to deserialize JSON strings while reporting errors mapped with the exact property path.
/// This aids troubleshooting by indicating precisely which JSON node caused failure.
fn deserialize_json_with_path<T: serde::de::DeserializeOwned>(json: &str) -> Result<T, Error> {
    let mut deserializer = serde_json::Deserializer::from_str(json);
    serde_path_to_error::deserialize(&mut deserializer).map_err(Into::into)
}

fn http_fetch(api_key: &str, url: String, proxy_config: &ProxyConfig) -> Result<String, Error> {
    crate::http_client::http_fetch(api_key, url, proxy_config)
}

/// Document update requests return this value to indicate if an update was
/// made or not.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum UpdateStatus {
    Updated,
    NotUpdated,
}

/// Branches alwasy return head of file, i.e. no version returned
fn get_branches(document_root: &figma_schema::FileResponse) -> Vec<FigmaDocInfo> {
    let mut branches = vec![];
    if let Some(doc_branches) = &document_root.branches {
        for hash in doc_branches {
            if let (Some(Some(id)), Some(Some(name))) = (hash.get("key"), hash.get("name")) {
                let figma_doc =
                    FigmaDocInfo { name: name.clone(), id: id.clone(), ..Default::default() };
                branches.push(figma_doc);
            }
        }
    }
    branches
}

fn load_image_hash_to_res_map(
    document_root: &figma_schema::FileResponse,
) -> HashMap<String, String> {
    let root_node = &document_root.document;
    let shared_plugin_data = &root_node.shared_plugin_data;
    if shared_plugin_data.contains_key("designcompose") {
        let plugin_data = shared_plugin_data.get("designcompose");
        if let Some(vsw_data) = plugin_data {
            if let Some(image_hash_to_res_data) = vsw_data.get("image_hash_to_res") {
                let image_hash_to_res_map: Option<HashMap<String, String>> =
                    serde_json::from_str(image_hash_to_res_data.as_str()).ok();
                if let Some(map) = image_hash_to_res_map {
                    return map;
                }
            }
        }
    }
    return HashMap::new();
}

/// Document is used to access and maintain an entire Figma document, including
/// components and image resources. It can be updated if the source document
/// has changed since this structure was created.
pub struct Document {
    api_key: String,
    document_id: String,
    version_id: String,
    proxy_config: ProxyConfig,
    document_root: figma_schema::FileResponse,
    variables_responses: HashMap<String, figma_schema::VariablesResponse>,
    image_context: ImageContext,
    variant_nodes: HashMap<String, figma_schema::Node>,
    component_sets: HashMap<String, String>,
    pub branches: Vec<FigmaDocInfo>,
    key_to_global_id_map: HashMap<String, String>,
    remote_node_responses: HashMap<(String, String), figma_schema::NodesResponse>,
    /// Tracks remote document IDs whose image refs have already been fetched
    /// to avoid redundant API calls within a single fetch cycle.
    fetched_remote_images: HashSet<String>,
    /// Cache of pre-fetched remote component key responses.
    /// Populated by `prefetch_remote_components()` before the main tree walk.
    /// Key: component key, Value: JSON response body.
    prefetched_components: HashMap<String, String>,
    /// Tracks top-level node structure for selective re-fetching.
    node_tracker: crate::node_tracker::NodeTracker,
    /// Content hashes of views from the last conversion, for incremental diffs.
    last_view_hashes: HashMap<String, String>,
    /// Cached mapping of query names (e.g., "#android-stage") to Figma node IDs
    /// (e.g., "12093:22798"). Populated on first node-scoped fetch and reused on
    /// subsequent update() calls to skip the expensive depth=2 structure fetch.
    cached_node_ids: HashMap<String, String>,
    /// Component keys that previously returned errors (404, 429, etc.).
    /// Skipped on subsequent prefetch rounds to avoid wasting API calls.
    failed_component_keys: HashSet<String>,
    /// Whether this Document was created as an update (vs initial load).
    /// On updates, remote component resolution is skipped since library
    /// components don't change on text/color edits.
    is_update: bool,
}

fn parse_document_id(document_id: &str) -> String {
    if document_id.starts_with("http://") || document_id.starts_with("https://") {
        if let Some(pos) = document_id.find("/file/") {
            let rest = &document_id[pos + 6..];
            if let Some(end_pos) = rest.find('/') {
                return rest[..end_pos].to_string();
            } else {
                return rest.to_string();
            }
        } else if let Some(pos) = document_id.find("/design/") {
            let rest = &document_id[pos + 8..];
            if let Some(end_pos) = rest.find('/') {
                return rest[..end_pos].to_string();
            } else {
                return rest.to_string();
            }
        }
    }
    document_id.to_string()
}

impl Document {
    pub fn root_node(&self) -> &figma_schema::Node {
        &self.document_root.document
    }

    /// Discover all top-level frame/component nodes from the document's pages.
    ///
    /// Iterates document → pages → children and returns the names of all
    /// visible top-level nodes. This enables dynamic root node discovery
    /// without requiring compile-time `@DesignComponent` annotations.
    pub fn discover_top_level_nodes(&self) -> Vec<String> {
        let mut names = Vec::new();
        // document.children = pages
        for page in &self.document_root.document.children {
            // page.children = top-level frames, components, etc.
            for node in &page.children {
                if node.visible && !node.name.is_empty() {
                    names.push(node.name.clone());
                }
            }
        }
        names
    }
    /// Fetch a document from Figma and return a Document instance that can be used
    /// to extract toolkit nodes.
    pub fn new(
        api_key: &str,
        document_id: String,
        version_id: String,
        proxy_config: &ProxyConfig,
        image_session: Option<ImageContextSession>,
    ) -> Result<Document, Error> {
        let document_id = parse_document_id(&document_id);

        // Fetch the document...
        let mut document_url = format!(
            "{}{}?plugin_data=shared&geometry=paths&branch_data=true",
            BASE_FILE_URL, document_id,
        );
        if !version_id.is_empty() {
            document_url.push_str("&version=");
            document_url.push_str(&version_id);
        }
        let document_root: figma_schema::FileResponse =
            deserialize_json_with_path(http_fetch(api_key, document_url, proxy_config)?.as_str())?;

        // ...and the mapping from imageRef to URL. It returns images from all versions.
        let image_ref_url = format!("{}{}/images", BASE_FILE_URL, document_id);
        let image_refs: figma_schema::ImageFillResponse =
            deserialize_json_with_path(http_fetch(api_key, image_ref_url, proxy_config)?.as_str())?;

        let image_hash_to_res_map = load_image_hash_to_res_map(&document_root);
        let mut image_context =
            ImageContext::new(image_refs.meta.images, image_hash_to_res_map, proxy_config);
        if let Some(session) = image_session {
            image_context.add_session_info(session);
        }

        let branches = get_branches(&document_root);
        let mut variables_responses = HashMap::new();
        match Self::fetch_variables(api_key, &document_id, proxy_config).map_err(Error::from) {
            Ok(mut it) => {
                let mut resolver = crate::library_resolver::LibraryResolver::new(
                    api_key.to_string(),
                    proxy_config.clone(),
                );
                resolver.discover_component_dependencies(&document_id, &document_root.components);
                resolver.discover_variable_dependencies(&document_id, &it);
                let remote_vars = resolver.fetch_all_library_variables(&document_id);
                for (_, remote_var_response) in remote_vars {
                    it.meta.variables.extend(remote_var_response.meta.variables);
                    it.meta
                        .variable_collections
                        .extend(remote_var_response.meta.variable_collections);
                }
                variables_responses.insert(document_id.clone(), it);
            }
            Err(err) => {
                error!("Failed to fetch variables for doc {} {:?}", document_id, err);
            }
        };

        Ok(Document {
            api_key: api_key.to_string(),
            document_id,
            version_id,
            proxy_config: proxy_config.clone(),
            document_root,
            variables_responses,
            image_context,
            variant_nodes: HashMap::new(),
            component_sets: HashMap::new(),
            branches,
            key_to_global_id_map: HashMap::new(),
            remote_node_responses: HashMap::new(),
            fetched_remote_images: HashSet::new(),
            prefetched_components: HashMap::new(),
            node_tracker: crate::node_tracker::NodeTracker::new(),
            last_view_hashes: HashMap::new(),
            cached_node_ids: HashMap::new(),
            failed_component_keys: HashSet::new(),
            is_update: false,
        })
    }

    // Fetch and store all the variables, collections, and modes from the Figma document.
    fn fetch_variables(
        api_key: &str,
        document_id: &String,
        proxy_config: &ProxyConfig,
    ) -> Result<figma_schema::VariablesResponse, Error> {
        let variables_url = format!("{}{}/variables/local", BASE_FILE_URL, document_id);
        let var_fetch = http_fetch(api_key, variables_url, proxy_config)?;
        let var_response: figma_schema::VariablesResponse =
            deserialize_json_with_path(var_fetch.as_str())?;
        Ok(var_response)
    }

    /// Fetch a document from Figma only if it has changed since the given last
    /// modified time.
    pub fn new_if_changed(
        api_key: &str,
        document_id: String,
        requested_version_id: String,
        proxy_config: &ProxyConfig,
        last_modified: String,
        last_version: String,
        image_session: Option<ImageContextSession>,
    ) -> Result<Option<Document>, Error> {
        let mut document_head_url = format!("{}{}?depth=1", BASE_FILE_URL, document_id);
        if !requested_version_id.is_empty() {
            document_head_url.push_str("&version=");
            document_head_url.push_str(&requested_version_id);
        }
        let document_head: figma_schema::FileHeadResponse = deserialize_json_with_path(
            http_fetch(api_key, document_head_url, proxy_config)?.as_str(),
        )?;

        if document_head.last_modified == last_modified && document_head.version == last_version {
            return Ok(None);
        }

        Document::new(api_key, document_id, requested_version_id, proxy_config, image_session)
            .map(Some)
    }

    /// Resolve query names (e.g., "#android-stage") to Figma node IDs
    /// by scanning the depth=2 document tree.
    fn resolve_query_node_ids(
        document: &figma_schema::Node,
        query_names: &[String],
    ) -> HashMap<String, String> {
        let mut result = HashMap::new();
        // Build a name → id map from the document tree (depth=2 has pages → top-level nodes)
        fn scan_for_names(node: &figma_schema::Node, name_to_id: &mut HashMap<String, String>) {
            if !node.name.is_empty() {
                name_to_id.insert(node.name.clone(), node.id.clone());
            }
            for child in &node.children {
                scan_for_names(child, name_to_id);
            }
        }

        let mut name_to_id = HashMap::new();
        scan_for_names(document, &mut name_to_id);

        for name in query_names {
            // Strip leading '#' if present (convention for DesignComponent node names)
            let lookup = if name.starts_with('#') { name.as_str() } else { name };
            if let Some(id) = name_to_id.get(lookup) {
                result.insert(name.clone(), id.clone());
            }
        }
        result
    }

    /// Inject fetched node subtrees into a shallow (depth=2) document tree.
    /// Replaces the stub children of matching top-level nodes with the
    /// fully-expanded subtree from the /nodes endpoint response.
    fn inject_fetched_nodes(
        document: &mut figma_schema::Node,
        fetched: &figma_schema::NodesResponse,
    ) -> usize {
        let mut injected_count = 0;
        for page in &mut document.children {
            for top_node in &mut page.children {
                if let Some(node_data) = fetched.nodes.get(&top_node.id) {
                    *top_node = node_data.document.clone();
                    injected_count += 1;
                }
            }
        }
        injected_count
    }

    /// Fetch a document from Figma using node-scoped fetching.
    /// Instead of downloading the entire file (which can be 1+ GB for large docs),
    /// this method:
    /// 1. Fetches depth=2 to get the document structure and top-level node IDs
    ///    (or uses pre_cached_node_ids to skip this step on updates)
    /// 2. Resolves query names to Figma node IDs
    /// 3. Fetches only the requested node subtrees via /nodes?ids=
    /// 4. Injects the fetched subtrees into the depth=2 document
    pub fn new_node_scoped(
        api_key: &str,
        document_id: String,
        version_id: String,
        proxy_config: &ProxyConfig,
        image_session: Option<ImageContextSession>,
        query_names: &[String],
        pre_cached_node_ids: Option<HashMap<String, String>>,
    ) -> Result<Document, Error> {
        let document_id = parse_document_id(&document_id);
        let is_update = pre_cached_node_ids.is_some();

        // Step 1: Get name→ID mapping AND base document tree.
        // depth=2 is needed for inject_fetched_nodes to find parent nodes.
        // On updates with cached IDs, skip discovery but still need depth=2 for injection.
        let (name_to_id, mut document_root) = if let Some(cached) =
            pre_cached_node_ids.filter(|c| !c.is_empty())
        {
            info!(
                "Node-scoped UPDATE: using {} pre-cached node IDs (depth=2 with ids= filter for fast response)",
                cached.len()
            );
            // Fast path: depth=2 but with ids= parameter to filter the response.
            // Figma returns ONLY the requested subtrees, dramatically reducing
            // the response payload and server processing time (~2-5s vs 22-47s).
            let ids_param: String =
                cached.values().map(|s| s.as_str()).collect::<Vec<_>>().join(",");
            let mut base_url = format!(
                "{}{}?depth=2&ids={}&branch_data=true&plugin_data=shared&geometry=paths",
                BASE_FILE_URL, document_id, ids_param,
            );
            if !version_id.is_empty() {
                base_url.push_str("&version=");
                base_url.push_str(&version_id);
            }
            let doc_root: figma_schema::FileResponse =
                deserialize_json_with_path(http_fetch(api_key, base_url, proxy_config)?.as_str())?;
            (cached, doc_root)
        } else {
            // Initial load OR update without cached IDs: fetch depth=2 for both
            // discovery AND as base document.
            let mut discovery_url =
                format!("{}{}?depth=2&branch_data=true", BASE_FILE_URL, document_id,);
            if !version_id.is_empty() {
                discovery_url.push_str("&version=");
                discovery_url.push_str(&version_id);
            }
            info!(
                "Node-scoped {}: depth=2 for name→ID discovery + base ({})",
                if is_update { "UPDATE" } else { "fetch" },
                document_id
            );
            let discovery_root: figma_schema::FileResponse = deserialize_json_with_path(
                http_fetch(api_key, discovery_url, proxy_config)?.as_str(),
            )?;
            let resolved = Self::resolve_query_node_ids(&discovery_root.document, query_names);
            info!(
                "Node-scoped fetch: resolved {}/{} query names to node IDs: {:?}",
                resolved.len(),
                query_names.len(),
                resolved
            );
            (resolved, discovery_root)
        };

        if !name_to_id.is_empty() && !is_update {
            // Step 3: Fetch the specific node subtrees (initial fetch only).
            // On updates, the /files?ids= response already contains the full subtrees.
            let node_ids: Vec<&str> = name_to_id.values().map(|s| s.as_str()).collect();
            let ids_param = node_ids.join(",");
            let nodes_url = format!(
                "{}{}/nodes?ids={}&plugin_data=shared&geometry=paths",
                BASE_FILE_URL, document_id, ids_param
            );
            info!(
                "Node-scoped fetch: fetching {} nodes via /nodes?ids={}",
                node_ids.len(),
                ids_param
            );
            let nodes_response: figma_schema::NodesResponse =
                deserialize_json_with_path(http_fetch(api_key, nodes_url, proxy_config)?.as_str())?;

            // Merge components from nodes response into document_root
            for (_node_id, node_data) in &nodes_response.nodes {
                for (comp_id, comp) in &node_data.components {
                    document_root.components.insert(comp_id.clone(), comp.clone());
                }
            }

            // Step 4: Inject fetched subtrees into the shallow document
            let injected = Self::inject_fetched_nodes(&mut document_root.document, &nodes_response);
            info!("Node-scoped fetch: injected {} node subtrees into document", injected);
        } else if is_update {
            info!(
                "Node-scoped UPDATE: skipping /nodes call (subtrees already in /files?ids= response)"
            );
        }

        // Smart cache: on updates, reuse cached /images and /variables data.
        // On initial load, fetch fresh and store in cache.
        let (image_context, variables_responses) = if is_update {
            let cached = SMART_CACHE.lock().ok().and_then(|c| c.get(&document_id).cloned());
            if let Some(entry) = cached {
                info!("Smart cache HIT: reusing cached /images ({} refs) and /variables ({} responses) for {}",
                    entry.image_refs.len(), entry.variables_responses.len(), document_id);
                let image_hash_to_res_map = load_image_hash_to_res_map(&document_root);
                let mut ctx =
                    ImageContext::new(entry.image_refs, image_hash_to_res_map, proxy_config);
                if let Some(session) = image_session {
                    ctx.add_session_info(session);
                }
                (ctx, entry.variables_responses)
            } else {
                info!("Smart cache MISS on update for {} — doing full fetch", document_id);
                // Fallback to full fetch
                let image_ref_url = format!("{}{}/images", BASE_FILE_URL, document_id);
                let image_refs: figma_schema::ImageFillResponse = deserialize_json_with_path(
                    http_fetch(api_key, image_ref_url, proxy_config)?.as_str(),
                )?;
                let image_hash_to_res_map = load_image_hash_to_res_map(&document_root);
                let mut ctx =
                    ImageContext::new(image_refs.meta.images, image_hash_to_res_map, proxy_config);
                if let Some(session) = image_session {
                    ctx.add_session_info(session);
                }
                let mut vars = HashMap::new();
                match Self::fetch_variables(api_key, &document_id, proxy_config)
                    .map_err(Error::from)
                {
                    Ok(mut it) => {
                        let mut resolver = crate::library_resolver::LibraryResolver::new(
                            api_key.to_string(),
                            proxy_config.clone(),
                        );
                        resolver.discover_component_dependencies(
                            &document_id,
                            &document_root.components,
                        );
                        resolver.discover_variable_dependencies(&document_id, &it);
                        let remote_vars = resolver.fetch_all_library_variables(&document_id);
                        for (_, remote_var_response) in remote_vars {
                            it.meta.variables.extend(remote_var_response.meta.variables);
                            it.meta
                                .variable_collections
                                .extend(remote_var_response.meta.variable_collections);
                        }
                        vars.insert(document_id.clone(), it);
                    }
                    Err(err) => {
                        error!("Failed to fetch variables for doc {} {:?}", document_id, err);
                    }
                };
                (ctx, vars)
            }
        } else {
            // Initial load: full fetch of images and variables
            let image_ref_url = format!("{}{}/images", BASE_FILE_URL, document_id);
            let image_refs: figma_schema::ImageFillResponse = deserialize_json_with_path(
                http_fetch(api_key, image_ref_url, proxy_config)?.as_str(),
            )?;

            let image_hash_to_res_map = load_image_hash_to_res_map(&document_root);
            let mut ctx = ImageContext::new(
                image_refs.meta.images.clone(),
                image_hash_to_res_map,
                proxy_config,
            );
            if let Some(session) = image_session {
                ctx.add_session_info(session);
            }

            let mut vars = HashMap::new();
            match Self::fetch_variables(api_key, &document_id, proxy_config).map_err(Error::from) {
                Ok(mut it) => {
                    let mut resolver = crate::library_resolver::LibraryResolver::new(
                        api_key.to_string(),
                        proxy_config.clone(),
                    );
                    resolver
                        .discover_component_dependencies(&document_id, &document_root.components);
                    resolver.discover_variable_dependencies(&document_id, &it);
                    let remote_vars = resolver.fetch_all_library_variables(&document_id);
                    for (_, remote_var_response) in remote_vars {
                        it.meta.variables.extend(remote_var_response.meta.variables);
                        it.meta
                            .variable_collections
                            .extend(remote_var_response.meta.variable_collections);
                    }
                    vars.insert(document_id.clone(), it);
                }
                Err(err) => {
                    error!("Failed to fetch variables for doc {} {:?}", document_id, err);
                }
            };

            // Store in smart cache for future updates
            if let Ok(mut cache) = SMART_CACHE.lock() {
                cache.insert(
                    document_id.clone(),
                    SmartCacheEntry {
                        image_refs: image_refs.meta.images,
                        variables_responses: vars.clone(),
                        prefetched_components: HashMap::new(), // populated later in nodes()
                        variant_nodes: HashMap::new(),         // populated later in nodes()
                        failed_component_keys: HashSet::new(), // populated later in nodes()
                    },
                );
                info!("Smart cache: stored initial /images and /variables for {}", document_id);
            }

            (ctx, vars)
        };

        let branches = get_branches(&document_root);

        Ok(Document {
            api_key: api_key.to_string(),
            document_id,
            version_id,
            proxy_config: proxy_config.clone(),
            document_root,
            variables_responses,
            image_context,
            variant_nodes: HashMap::new(),
            component_sets: HashMap::new(),
            branches,
            key_to_global_id_map: HashMap::new(),
            remote_node_responses: HashMap::new(),
            fetched_remote_images: HashSet::new(),
            prefetched_components: HashMap::new(),
            node_tracker: crate::node_tracker::NodeTracker::new(),
            last_view_hashes: HashMap::new(),
            cached_node_ids: name_to_id,
            failed_component_keys: HashSet::new(),
            is_update,
        })
    }

    /// Fetch a document from Figma only if it has changed since the given last
    /// modified time. Uses node-scoped fetching when query_names are provided.
    /// `cached_node_ids` enables the update fast-path: skips depth=2 discovery,
    /// /images, /variables, and remote component resolution.
    pub fn new_if_changed_scoped(
        api_key: &str,
        document_id: String,
        requested_version_id: String,
        proxy_config: &ProxyConfig,
        last_modified: String,
        last_version: String,
        image_session: Option<ImageContextSession>,
        query_names: &[String],
        cached_node_ids: Option<HashMap<String, String>>,
    ) -> Result<Option<Document>, Error> {
        let parsed_id = parse_document_id(&document_id);
        let mut document_head_url = format!("{}{}?depth=1", BASE_FILE_URL, parsed_id);
        if !requested_version_id.is_empty() {
            document_head_url.push_str("&version=");
            document_head_url.push_str(&requested_version_id);
        }
        let document_head: figma_schema::FileHeadResponse = deserialize_json_with_path(
            http_fetch(api_key, document_head_url, proxy_config)?.as_str(),
        )?;

        if document_head.last_modified == last_modified && document_head.version == last_version {
            return Ok(None);
        }

        if query_names.is_empty() {
            // No queries — fall back to full doc fetch
            Document::new(api_key, document_id, requested_version_id, proxy_config, image_session)
                .map(Some)
        } else {
            // Use node-scoped fetching for efficiency
            Document::new_node_scoped(
                api_key,
                document_id,
                requested_version_id,
                proxy_config,
                image_session,
                query_names,
                cached_node_ids,
            )
            .map(Some)
        }
    }

    /// Ask Figma if an updated document is available, and then fetch the updated document
    /// if so. Uses node-scoped fetching when query_names are provided.
    pub fn update(
        &mut self,
        proxy_config: &ProxyConfig,
        query_names: Option<&[String]>,
    ) -> Result<UpdateStatus, Error> {
        self.proxy_config = proxy_config.clone();

        // Fetch just the top level of the document. (depth=0 causes an internal server error).
        let mut document_head_url = format!("{}{}?depth=1", BASE_FILE_URL, self.document_id);
        if !self.version_id.is_empty() {
            document_head_url.push_str("&version=");
            document_head_url.push_str(&self.version_id);
        }
        let document_head: figma_schema::FileHeadResponse = deserialize_json_with_path(
            http_fetch(self.api_key.as_str(), document_head_url, &self.proxy_config)?.as_str(),
        )?;

        // Now compare the version and modification times and bail out if they're the same.
        if document_head.last_modified == self.document_root.last_modified
            && document_head.version == self.document_root.version
        {
            return Ok(UpdateStatus::NotUpdated);
        }

        // Decide between node-scoped and full-doc fetch
        if let Some(names) = query_names {
            if !names.is_empty() {
                // Try to use cached node IDs from the initial fetch to skip depth=2
                let name_to_id = if !self.cached_node_ids.is_empty() {
                    info!(
                        "Node-scoped update: using {} cached node IDs (skipping depth=2)",
                        self.cached_node_ids.len()
                    );
                    self.cached_node_ids.clone()
                } else {
                    // First update or cache miss — do lightweight depth=2
                    let mut discovery_url =
                        format!("{}{}?depth=2", BASE_FILE_URL, self.document_id,);
                    if !self.version_id.is_empty() {
                        discovery_url.push_str("&version=");
                        discovery_url.push_str(&self.version_id);
                    }
                    info!("Node-scoped update: lightweight depth=2 for name→ID discovery");
                    let discovery_root: figma_schema::FileResponse = deserialize_json_with_path(
                        http_fetch(self.api_key.as_str(), discovery_url, &self.proxy_config)?
                            .as_str(),
                    )?;
                    let resolved = Self::resolve_query_node_ids(&discovery_root.document, names);
                    self.cached_node_ids = resolved.clone();
                    resolved
                };

                info!(
                    "Node-scoped update: using {}/{} query→ID mappings",
                    name_to_id.len(),
                    names.len()
                );

                // Fetch a lightweight depth=1 structure as the base document_root
                // (we need version/lastModified metadata but not the full tree)
                let mut base_url =
                    format!("{}{}?depth=1&branch_data=true", BASE_FILE_URL, self.document_id,);
                if !self.version_id.is_empty() {
                    base_url.push_str("&version=");
                    base_url.push_str(&self.version_id);
                }
                let mut document_root: figma_schema::FileResponse = deserialize_json_with_path(
                    http_fetch(self.api_key.as_str(), base_url, &self.proxy_config)?.as_str(),
                )?;

                if !name_to_id.is_empty() {
                    let ids_param: String =
                        name_to_id.values().map(|s| s.as_str()).collect::<Vec<_>>().join(",");
                    let nodes_url = format!(
                        "{}{}/nodes?ids={}&plugin_data=shared&geometry=paths",
                        BASE_FILE_URL, self.document_id, ids_param
                    );
                    info!("Node-scoped update: fetching /nodes?ids={}", ids_param);
                    let nodes_response: figma_schema::NodesResponse = deserialize_json_with_path(
                        http_fetch(self.api_key.as_str(), nodes_url, &self.proxy_config)?.as_str(),
                    )?;

                    // Merge components
                    for (_node_id, node_data) in &nodes_response.nodes {
                        for (comp_id, comp) in &node_data.components {
                            document_root.components.insert(comp_id.clone(), comp.clone());
                        }
                    }

                    Self::inject_fetched_nodes(&mut document_root.document, &nodes_response);
                }

                // Fetch images
                let image_ref_url = format!("{}{}/images", BASE_FILE_URL, self.document_id);
                let image_refs: figma_schema::ImageFillResponse = deserialize_json_with_path(
                    http_fetch(self.api_key.as_str(), image_ref_url, &self.proxy_config)?.as_str(),
                )?;

                self.branches = get_branches(&document_root);
                self.document_root = document_root;
                self.image_context.update_images(image_refs.meta.images);

                return Ok(UpdateStatus::Updated);
            }
        }

        // Fall back to full document fetch
        let mut document_url = format!(
            "{}{}?plugin_data=shared&geometry=paths&branch_data=true",
            BASE_FILE_URL, self.document_id,
        );
        if !self.version_id.is_empty() {
            document_url.push_str("&version=");
            document_url.push_str(&self.version_id);
        }
        let document_root: figma_schema::FileResponse = deserialize_json_with_path(
            http_fetch(self.api_key.as_str(), document_url, &self.proxy_config)?.as_str(),
        )?;

        // ...and the mapping from imageRef to URL. It returns images from all versions.
        let image_ref_url = format!("{}{}/images", BASE_FILE_URL, self.document_id);
        let image_refs: figma_schema::ImageFillResponse = deserialize_json_with_path(
            http_fetch(self.api_key.as_str(), image_ref_url, &self.proxy_config)?.as_str(),
        )?;

        self.branches = get_branches(&document_root);
        self.document_root = document_root;
        self.image_context.update_images(image_refs.meta.images);

        Ok(UpdateStatus::Updated)
    }

    /// Return the last modified time of this document. This seems to update whenever the doc
    /// is changed (but the version number does not).
    pub fn last_modified(&self) -> &String {
        &self.document_root.last_modified
    }

    /// Return the cached node ID mapping (query name → Figma node ID).
    /// Used by the JNI layer to persist across fetch cycles.
    pub fn cached_node_ids(&self) -> &HashMap<String, String> {
        &self.cached_node_ids
    }

    /// Pre-fetch all remote component metadata concurrently.
    ///
    /// Walks the entire node tree to discover component instances whose keys
    /// refer to remote documents. Collects all unique component keys and
    /// batch-fetches them in parallel using `http_fetch_batch`. The results
    /// are stored in a HashMap that `fetch_component_variants` can consult
    /// before making individual HTTP calls.
    ///
    /// This reduces remote component fetch time from O(N) sequential calls
    /// to O(1) concurrent batches.
    fn prefetch_remote_components(
        &self,
        root: &figma_schema::Node,
        component_hash: &HashMap<String, figma_schema::Component>,
        id_index: &HashMap<String, &figma_schema::Node>,
    ) -> HashMap<String, String> {
        use crate::http_client::{http_fetch_batch, BatchRequest};

        // Phase 1: Discover all unique component keys that need fetching
        let mut keys_to_fetch: HashSet<String> = HashSet::new();
        Self::collect_remote_component_keys(root, component_hash, id_index, &mut keys_to_fetch);

        // Phase 1.5: Skip keys we already have cached or that previously failed
        let already_cached =
            keys_to_fetch.iter().filter(|k| self.prefetched_components.contains_key(*k)).count();
        let already_failed =
            keys_to_fetch.iter().filter(|k| self.failed_component_keys.contains(*k)).count();
        keys_to_fetch.retain(|k| {
            !self.prefetched_components.contains_key(k) && !self.failed_component_keys.contains(k)
        });

        if keys_to_fetch.is_empty() {
            if already_cached > 0 || already_failed > 0 {
                log::info!(
                    "prefetch_remote_components: all keys resolved from cache ({} cached, {} skipped-failed)",
                    already_cached,
                    already_failed
                );
            }
            return HashMap::new();
        }

        log::info!(
            "prefetch_remote_components: fetching {} new keys ({} cached, {} skipped-failed)",
            keys_to_fetch.len(),
            already_cached,
            already_failed
        );

        // Phase 2: Build batch requests
        let requests: Vec<BatchRequest> = keys_to_fetch
            .iter()
            .map(|key| BatchRequest {
                id: key.clone(),
                url: format!("{}{}", BASE_COMPONENT_URL, key),
            })
            .collect();

        // Phase 3: Fetch all concurrently
        let responses = http_fetch_batch(&self.api_key, requests, &self.proxy_config);

        // Phase 4: Collect results into a cache
        let mut cache: HashMap<String, String> = HashMap::new();
        for response in responses {
            match response.result {
                Ok(body) => {
                    cache.insert(response.id, body);
                }
                Err(e) => {
                    log::warn!(
                        "prefetch_remote_components: failed to fetch component key {}: {:?}",
                        response.id,
                        e
                    );
                    // Don't insert into cache — will be added to failed_component_keys by caller
                }
            }
        }

        log::info!(
            "prefetch_remote_components: successfully pre-fetched {}/{} component keys",
            cache.len(),
            keys_to_fetch.len()
        );

        cache
    }

    /// Recursively collect all unique component keys from Instance nodes
    /// that are not present in the local id_index (i.e., remote components).
    fn collect_remote_component_keys(
        node: &figma_schema::Node,
        component_hash: &HashMap<String, figma_schema::Component>,
        id_index: &HashMap<String, &figma_schema::Node>,
        keys: &mut HashSet<String>,
    ) {
        if let figma_schema::NodeData::Instance { frame: _, component_id } = &node.data {
            if !id_index.contains_key(component_id) {
                if let Some(component) = component_hash.get(component_id) {
                    keys.insert(component.key.clone());
                }
            }
        }

        for child in &node.children {
            Self::collect_remote_component_keys(child, component_hash, id_index, keys);
        }
    }

    /// Find all nodes whose data is of type NodeData::Instance, which means could be a
    /// component with variants. Find its parent, and if it is of type NodeData::ComponentSet,
    /// then add all of its children to self.variant_nodes. Also fill out node_doc_hash,
    /// which hashes node ids to the document id they come from.
    fn fetch_component_variants(
        &mut self,
        node: &figma_schema::Node,
        node_doc_hash: &mut HashMap<String, String>,
        variant_nodes: &mut HashMap<String, figma_schema::Node>,
        id_index: &HashMap<String, &figma_schema::Node>,
        component_hash: &HashMap<String, figma_schema::Component>,
        parent_tree: &mut Vec<String>,
        error_list: &mut Vec<String>,
        error_hash: &mut HashSet<String>,
        completed_hash: &mut HashSet<String>,
        hidden_node_policy: HiddenNodePolicy,
    ) -> Result<(), Error> {
        // Ignore hidden nodes
        if !node.visible && hidden_node_policy == HiddenNodePolicy::Skip {
            return Ok(());
        }
        fn add_node_doc_hash(
            node: &figma_schema::Node,
            node_doc_hash: &mut HashMap<String, String>,
            doc_id: &String,
        ) {
            // Add the node id, doc id to the hash and recurse on all children
            node_doc_hash.insert(node.id.clone(), doc_id.clone());
            for child in &node.children {
                add_node_doc_hash(child, node_doc_hash, doc_id);
            }
        }

        if let figma_schema::NodeData::Instance { frame: _, component_id } = &node.data {
            // If the component_id is in id_index, we know it's in this document so we don't
            // need to do anything. If it isn't, it's in a different doc, so proceed to
            // download data for it
            if !id_index.contains_key(component_id) {
                // Find the component info for the component_id
                let component = component_hash.get(component_id);
                if let Some(component) = component {
                    // Fetch the component from the figma api given its key
                    let file_key = component.key.clone();
                    // If we already retrieved this component instance but got an error, don't try again
                    if error_hash.contains(&file_key) {
                        return Ok(());
                    }
                    // If we already completed this node, skip
                    if completed_hash.contains(&file_key) {
                        return Ok(());
                    }
                    let component_url = format!("{}{}", BASE_COMPONENT_URL, file_key);
                    // Check the prefetch cache first (populated by prefetch_remote_components)
                    let component_http_response = if let Some(cached) =
                        self.prefetched_components.get(&file_key)
                    {
                        completed_hash.insert(file_key);
                        cached.clone()
                    } else {
                        // Cache miss — fetch individually (handles components discovered
                        // during recursive traversal of remote nodes)
                        match http_fetch(
                            self.api_key.as_str(),
                            component_url.clone(),
                            &self.proxy_config,
                        ) {
                            Ok(str) => {
                                completed_hash.insert(file_key);
                                str
                            }
                            Err(e) => {
                                let fetch_error = if let Error::NetworkError(reqwest_error) = &e {
                                    if let Some(code) = reqwest_error.status() {
                                        format!("HTTP {} at {}", code, component_url)
                                    } else {
                                        reqwest_error.to_string()
                                    }
                                } else {
                                    e.to_string()
                                };
                                let error_string = format!(
                                    "Fetch component error {}: {} -> {}",
                                    fetch_error,
                                    parent_tree.join(" -> "),
                                    node.name
                                );
                                error_hash.insert(file_key);
                                error_list.push(error_string);
                                return Ok(());
                            }
                        }
                    };

                    // Deserialize into a ComponentKeyResponse
                    let component_key_response: figma_schema::ComponentKeyResponse =
                        serde_json::from_str(component_http_response.as_str())?;
                    // If this variant points to a file_key different than this document, fetch it
                    let maybe_parent_node_id = component_key_response.parent_id();
                    if let Some(parent_node_id) = maybe_parent_node_id {
                        let variant_document_id = component_key_response.meta.file_key;
                        if variant_document_id != self.document_id {
                            if let Err(e) = Self::fetch_variables(
                                &self.api_key,
                                &variant_document_id,
                                &self.proxy_config,
                            ) {
                                error!(
                                    "Failed to fetch variables for remote document {}: {:?}",
                                    variant_document_id, e
                                );
                            }
                            if !self.variables_responses.contains_key(&variant_document_id) {
                                match Self::fetch_variables(
                                    self.api_key.as_str(),
                                    &variant_document_id,
                                    &self.proxy_config,
                                ) {
                                    Ok(vars) => {
                                        self.variables_responses
                                            .insert(variant_document_id.clone(), vars);
                                    }
                                    Err(e) => {
                                        error!(
                                            "Failed to fetch variables for doc {}: {:?}",
                                            variant_document_id, e
                                        );
                                    }
                                }
                            }

                            let nodes_response = if let Some(response) = self
                                .remote_node_responses
                                .get(&(variant_document_id.clone(), parent_node_id.clone()))
                            {
                                response.clone()
                            } else {
                                let nodes_url = format!(
                                    "{}{}/nodes?ids={}",
                                    BASE_FILE_URL, variant_document_id, parent_node_id
                                );
                                let http_str = http_fetch(
                                    self.api_key.as_str(),
                                    nodes_url,
                                    &self.proxy_config,
                                )?;
                                let response: figma_schema::NodesResponse =
                                    serde_json::from_str(http_str.as_str())?;
                                self.remote_node_responses.insert(
                                    (variant_document_id.clone(), parent_node_id.clone()),
                                    response.clone(),
                                );
                                response
                            };

                            // Fetch image refs from the remote document so that
                            // image fills in remote components can be resolved.
                            if !self.fetched_remote_images.contains(&variant_document_id) {
                                let remote_image_url =
                                    format!("{}{}/images", BASE_FILE_URL, variant_document_id);
                                match http_fetch(
                                    self.api_key.as_str(),
                                    remote_image_url,
                                    &self.proxy_config,
                                ) {
                                    Ok(body) => {
                                        match serde_json::from_str::<figma_schema::ImageFillResponse>(
                                            body.as_str(),
                                        ) {
                                            Ok(remote_image_refs) => {
                                                self.image_context.merge_remote_images(
                                                    remote_image_refs.meta.images,
                                                );
                                            }
                                            Err(e) => {
                                                warn!(
                                                    "Failed to parse image refs for remote doc {}: {:?}",
                                                    variant_document_id, e
                                                );
                                            }
                                        }
                                    }
                                    Err(e) => {
                                        warn!(
                                            "Failed to fetch images for remote doc {}: {:?}",
                                            variant_document_id, e
                                        );
                                    }
                                }
                                self.fetched_remote_images.insert(variant_document_id.clone());
                            }

                            // The response is a list of nodes, but we only requested one so this loop
                            // should only go through one time
                            for (node_id, node_response_data) in nodes_response.nodes {
                                if node_id != parent_node_id {
                                    continue; // We only care about parent_node_id
                                }
                                // If the parent is a COMPONENT_SET, then we want to get the parent's children
                                // and add them to our list of nodes
                                if let figma_schema::NodeData::ComponentSet { frame: _ } =
                                    node_response_data.document.data
                                {
                                    for node in node_response_data.document.children {
                                        add_node_doc_hash(
                                            &node,
                                            node_doc_hash,
                                            &variant_document_id,
                                        );
                                        // Recurse on all children
                                        for child in &node.children {
                                            parent_tree.push(node.name.clone());
                                            self.fetch_component_variants(
                                                child,
                                                node_doc_hash,
                                                variant_nodes,
                                                id_index,
                                                &node_response_data.components,
                                                parent_tree,
                                                error_list,
                                                error_hash,
                                                completed_hash,
                                                hidden_node_policy,
                                            )?;
                                            parent_tree.pop();
                                        }
                                        variant_nodes.insert(node.id.clone(), node);
                                    }
                                }
                            }
                        }
                    } else {
                        let error_string = format!(
                            "Fetch component unable to find component parent for: {} -> {}",
                            parent_tree.join(" -> "),
                            node.name
                        );
                        error_list.push(error_string);
                        return Ok(());
                    }
                }
            }
        }
        // Recurse on all children
        for child in &node.children {
            parent_tree.push(node.name.clone());
            self.fetch_component_variants(
                child,
                node_doc_hash,
                variant_nodes,
                id_index,
                component_hash,
                parent_tree,
                error_list,
                error_hash,
                completed_hash,
                hidden_node_policy,
            )?;
            parent_tree.pop();
        }
        Ok(())
    }

    /// Find all of the Component Instance views and see which style and text properties are
    /// overridden in the instance compared to the reference component. If we then render a
    /// different variant of the component (due to an interaction) we can apply these delta
    /// styles to get the correct output.
    fn compute_component_overrides(nodes: &mut HashMap<NodeQuery, View>) {
        // XXX: Would be nice to avoid cloning here. Do we need to? We need to mutate the
        //      instance views in place. And we can't hold a ref and a mutable ref to nodes
        //      at the same time.
        let reference_components = nodes.clone();

        // This function finds all of the Component Instances (views with a populated
        // component_info field) in the given view tree, and looks up which component
        // they are an instance of. If the component is found, then the "action" function
        // is run with a mutable reference to the Component Instance view and a reference
        // to the component.
        //
        // These two pieces of information (the instance and the component) can then be
        // used to figure out which properties of the component have been customized in
        // the instance. Then we can be sure to apply those customized properties to other
        // variants (where Figma just gives us the variant definition, but not filled out
        // instance with overrides applied).
        fn for_each_component_instance(
            reference_components: &HashMap<NodeQuery, View>,
            view: &mut View,
            parent_component_info: Option<&mut ComponentInfo>,
            parent_reference_component: Option<&View>,
            action: &impl Fn(
                MessageField<ViewStyle>,
                MessageField<ViewData>,
                String,
                String,
                &mut ComponentInfo,
                Option<&View>,
                bool,
            ),
        ) {
            match (view.component_info.as_mut(), parent_component_info) {
                (Some(parent_info), Some(_)) => {
                    // This matches a component instance within a component instance.
                    // The style and data overrides are written to a hash map keyed by the view name
                    // in the component info of the instance.
                    action(
                        view.style.clone(),
                        view.data.clone(),
                        view.id.clone(),
                        view.name.clone(),
                        parent_info,
                        parent_reference_component,
                        false,
                    );
                    if let Some(data) = view.data.as_mut() {
                        if let Some(View_data_type::Container { 0: Container { children, .. } }) =
                            data.view_data_type.as_mut()
                        {
                            for child in children {
                                for_each_component_instance(
                                    reference_components,
                                    child,
                                    Some(parent_info),
                                    parent_reference_component,
                                    action,
                                );
                            }
                        }
                    }
                }
                (Some(info), _) => {
                    // This is the root node of a component instance.
                    // Compute its style and data overrides and write to its component info whose
                    // key is the component_set_name.

                    // See if we can find the target component. If not then don't look up
                    // references. Try searching by id, name, and variant
                    let queries = [
                        NodeQuery::NodeId(info.id.clone()),
                        NodeQuery::NodeName(info.name.clone()),
                        NodeQuery::NodeVariant(info.name.clone(), info.component_set_name.clone()),
                    ];

                    let reference_component_option =
                        queries.iter().find_map(|query| reference_components.get(query));

                    if reference_component_option.is_some() {
                        action(
                            view.style.clone(),
                            view.data.clone(),
                            view.id.clone(),
                            info.name.clone(),
                            info,
                            reference_component_option,
                            true,
                        );
                    }

                    if let Some(data) = view.data.as_mut() {
                        if let Some(View_data_type::Container { 0: Container { children, .. } }) =
                            data.view_data_type.as_mut()
                        {
                            for child in children {
                                for_each_component_instance(
                                    reference_components,
                                    child,
                                    Some(info),
                                    reference_component_option,
                                    action,
                                );
                            }
                        }
                    }
                }
                (None, Some(parent_info)) => {
                    // This matches a descendent view of a component instance.
                    // The style and data overrides are written to hash map keyed by the view name
                    // in the component info of the instance.
                    action(
                        view.style.clone(),
                        view.data.clone(),
                        view.id.clone(),
                        view.name.clone(),
                        parent_info,
                        parent_reference_component,
                        false,
                    );
                    if let Some(data) = view.data.as_mut() {
                        if let Some(View_data_type::Container { 0: Container { children, .. } }) =
                            data.view_data_type.as_mut()
                        {
                            for child in children {
                                for_each_component_instance(
                                    reference_components,
                                    child,
                                    Some(parent_info),
                                    parent_reference_component,
                                    action,
                                );
                            }
                        }
                    }
                }

                (None, None) => {
                    // This matches the nodes from the root node of the view tree until it
                    // meets a component instance.
                    if let Some(data) = view.data.as_mut() {
                        if let Some(View_data_type::Container { 0: Container { children, .. } }) =
                            data.view_data_type.as_mut()
                        {
                            for child in children {
                                for_each_component_instance(
                                    reference_components,
                                    child,
                                    None,
                                    None,
                                    action,
                                );
                            }
                        }
                    }
                }
            }
        }

        for view in nodes.values_mut() {
            for_each_component_instance(
                &reference_components,
                view,
                None,
                None,
                &|view_style,
                  view_data,
                  view_id,
                  // overrides_table_key will either be the component_set_name or view_name.
                  // This only works if the view name is identical.
                  overrides_table_key,
                  component_info,
                  component,
                  is_component_root| {
                    if let Some(reference_component) = component {
                        let template_view_option = if is_component_root {
                            Some(reference_component)
                        } else {
                            reference_component.find_view_by_id(&view_id)
                        };
                        if let Some(template_view) = template_view_option {
                            let mut override_view_style = if view_style == template_view.style {
                                MessageField::none()
                            } else if let Some(view_style_ref) = view_style.as_ref() {
                                let diff: Option<ViewStyle> =
                                    Some(template_view.style().difference(view_style_ref));
                                diff.into()
                            } else {
                                error!("ViewStyle is required.");
                                MessageField::none()
                            };

                            let anim_over = view_style.as_ref().and_then(|v| {
                                v.node_style().animation_override.clone().into_option()
                            });

                            let template_anim_over = template_view.style.as_ref().and_then(|s| {
                                s.node_style().animation_override.clone().into_option()
                            });

                            if let Some(anim_over) = anim_over {
                                if Some(&anim_over) != template_anim_over.as_ref() {
                                    if override_view_style.is_none() {
                                        let mut new_style = ViewStyle::new_default();
                                        new_style.node_style_mut().animation_override =
                                            Some(anim_over).into();
                                        override_view_style = Some(new_style).into();
                                    } else {
                                        override_view_style
                                            .mut_or_insert_default()
                                            .node_style_mut()
                                            .animation_override = Some(anim_over).into();
                                    }
                                }
                            }

                            let override_view_data =
                                if let Some(reference_view_data) = template_view.data.as_ref() {
                                    if let Some(data) = view_data.as_ref() {
                                        reference_view_data.difference(data).into()
                                    } else {
                                        MessageField::none()
                                    }
                                } else {
                                    MessageField::none()
                                };

                            if override_view_style.is_some() || override_view_data.is_some() {
                                component_info.overrides_table.insert(
                                    overrides_table_key,
                                    ComponentOverrides {
                                        style: override_view_style,
                                        view_data: override_view_data,
                                        ..Default::default()
                                    },
                                );
                            }
                        }
                    }
                },
            );
        }
    }

    /// Convert the nodes with the given names to a structure that's closer to a toolkit
    /// View. This method doesn't use the toolkit itself.
    pub fn nodes(
        &mut self,
        node_names: &Vec<NodeQuery>,
        ignored_images: &Vec<(NodeQuery, Vec<String>)>,
        error_list: &mut Vec<String>,
        hidden_node_policy: HiddenNodePolicy,
    ) -> Result<HashMap<NodeQuery, View>, Error> {
        // First we gather all of nodes that we're going to convert and find all of the
        // child nodes that can't be rendered. Then we ask Figma to do a batch render on
        // them. Finally we convert and return the set of toolkit nodes.
        fn index_node<'a>(
            node: &'a figma_schema::Node,
            parent_node: Option<&'a figma_schema::Node>,
            name_index: &mut HashMap<String, &'a figma_schema::Node>,
            id_index: &mut HashMap<String, &'a figma_schema::Node>,
            variant_index: &mut HashMap<(String, String), &'a figma_schema::Node>,
            component_set_name_index: &mut HashMap<String, &'a figma_schema::Node>,
            component_id_index: &mut HashMap<String, &'a figma_schema::Node>,
            hidden_node_policy: HiddenNodePolicy,
        ) {
            // Ignore hidden nodes
            if !node.visible && hidden_node_policy == HiddenNodePolicy::Skip {
                return;
            }

            // If we have a parent that is a component set, add to the variant index
            let mut is_variant = false;
            if let Some(parent) = parent_node {
                if let figma_schema::NodeData::ComponentSet { .. } = parent.data {
                    is_variant = true;
                    variant_index.insert((node.name.clone(), parent.name.clone()), node);
                }
            }

            if !is_variant {
                // If there's already a node with the same name, then only replace it if
                // we're a component.
                if name_index.get(&node.name).is_some() {
                    if let figma_schema::NodeData::Component { .. } = node.data {
                        name_index.insert(node.name.clone(), node);
                    }
                } else {
                    name_index.insert(node.name.clone(), node);
                }
            }
            id_index.insert(node.id.clone(), node);
            for child in &node.children {
                index_node(
                    child,
                    Some(node),
                    name_index,
                    id_index,
                    variant_index,
                    component_set_name_index,
                    component_id_index,
                    hidden_node_policy,
                );
            }
            if let figma_schema::NodeData::ComponentSet { .. } = node.data {
                component_set_name_index.insert(node.name.clone(), node);
                for child in &node.children {
                    component_id_index.insert(child.id.clone(), node);
                }
            }
        }

        // For each node in nodes or an ancestor of a node in nodes, if it is a component
        // instance, add the component set associated with the instance into node_name_hash.
        fn find_component_sets(
            nodes: &Vec<&figma_schema::Node>,
            component_set_index: &HashMap<String, &figma_schema::Node>,
            node_name_hash: &mut HashSet<NodeQuery>,
        ) {
            for node in nodes {
                if let figma_schema::NodeData::Instance { frame: _, component_id } = &node.data {
                    let component_set = component_set_index.get(component_id);
                    if let Some(cs) = component_set {
                        node_name_hash.insert(NodeQuery::NodeComponentSet(cs.name.clone()));

                        // Recurse on the children of the component set since variants can change
                        // to any of them at runtime
                        let cs_children: Vec<&figma_schema::Node> = cs.children.iter().collect();
                        find_component_sets(&cs_children, component_set_index, node_name_hash);
                    }
                }

                let children: Vec<&figma_schema::Node> = node.children.iter().collect();
                find_component_sets(&children, component_set_index, node_name_hash);
            }
        }

        // For each node that is a component set, add all of its children (which are variants)
        // into the node name hash so that we retrieve those nodes. Also add them to the
        // component_set_hash, which hashes a component set node name to all of its children.
        fn add_variant_node_names(
            node: &figma_schema::Node,
            node_name_hash: &mut HashSet<NodeQuery>,
            component_set_hash: &mut HashMap<String, Vec<String>>,
        ) {
            if let figma_schema::NodeData::ComponentSet { .. } = &node.data {
                // Add the component set's children to node_name_has if either the component set itself
                // is in the node_name_hash, or one of the child variants is in node_name_hash
                let mut add_children = node_name_hash
                    .contains(&NodeQuery::NodeName(node.name.clone()))
                    || node_name_hash.contains(&NodeQuery::NodeComponentSet(node.name.clone()));
                if !add_children {
                    'outer: for child in &node.children {
                        let child_name_parts = child.name.split(',');
                        for variant_name in child_name_parts {
                            let variant_name = variant_name.to_string();
                            let variant_parts: Vec<&str> = variant_name.split('=').collect();
                            if variant_parts.len() == 2 {
                                // Format is property_name=value, so check if the property_name is in node_name_hash
                                if node_name_hash
                                    .contains(&NodeQuery::NodeName(variant_parts[0].to_string()))
                                {
                                    add_children = true;
                                    break 'outer;
                                }
                            }
                        }
                    }
                }
                if add_children {
                    for child in &node.children {
                        let child_node_query =
                            NodeQuery::NodeVariant(child.name.clone(), node.name.clone());
                        if !node_name_hash.contains(&child_node_query) {
                            node_name_hash.insert(child_node_query);
                        }
                    }
                }
                let mut variant_list: Vec<String> = vec![];
                for child in &node.children {
                    variant_list.push(child.name.clone());
                }
                component_set_hash.insert(node.name.clone(), variant_list);
            }
            // Recurse on all children
            for child in &node.children {
                add_variant_node_names(child, node_name_hash, component_set_hash);
            }
        }

        // Search the node hierarchy for nodes that have plugin data that specifies an overflow
        // node. Add these nodes to node_name_hash so that we fetch them.
        fn add_overflow_nodes(node: &figma_schema::Node, node_name_hash: &mut HashSet<NodeQuery>) {
            if node.shared_plugin_data.contains_key("designcompose") {
                let plugin_data = node.shared_plugin_data.get("designcompose");
                if let Some(vsw_data) = plugin_data {
                    if let Some(plugin_layout) = vsw_data.get("vsw-extended-auto-layout") {
                        let extended_auto_layout: Option<ExtendedAutoLayout> =
                            serde_json::from_str(plugin_layout.as_str()).ok();
                        if let Some(extended_auto_layout) = extended_auto_layout {
                            if extended_auto_layout.limit_content {
                                let lcd = extended_auto_layout.limit_content_data;
                                node_name_hash.insert(NodeQuery::NodeId(lcd.overflow_node_id));
                            }
                        }
                    }
                }
            }

            // Recurse on all children
            for child in &node.children {
                add_overflow_nodes(child, node_name_hash);
            }
        }

        let mut name_index = HashMap::new();
        let mut id_index = HashMap::new();
        let mut variant_index = HashMap::new();
        let mut component_set_name_index = HashMap::new();
        // If a component belongs to a component set (there are "variants" in the Figma UI)
        // then we want to know which component set it belongs to so that if the component
        // set has bindings then we can use them for the instance.
        //
        // (For example, we might encounter an instance of a PRNDL component; the component
        // itself has no bindings, but the component set binds to the "vehicle gear" signal
        // and selects a different variant/component based on the gear; in the Figma JSON we
        // will find a component instance, like "Gear=P", and then need to find the component
        // set "PRNDL", and then look at its bindings. If we find the component set and find
        // the bindings then we know we should replace the instance with special node that
        // knows to subscribe to the Gear signal).
        //
        // This map goes from "component id" -> "component set node", so there will be one
        // entry for each component in a component set.
        let mut component_id_index = HashMap::new();
        let root_node = self.document_root.document.clone();
        index_node(
            &root_node,
            None,
            &mut name_index,
            &mut id_index,
            &mut variant_index,
            &mut component_set_name_index,
            &mut component_id_index,
            hidden_node_policy,
        );

        // Fetch component variant nodes
        // doc_nodes is a hash that that hashes document_id -> list of node IDs from that
        // document that we need, so that we can retrieve images from the correct document
        let mut node_doc_hash: HashMap<String, String> = HashMap::new();
        let mut variant_nodes: HashMap<String, figma_schema::Node> = HashMap::new();
        let mut parent_tree: Vec<String> = vec![];
        let mut error_hash: HashSet<String> = HashSet::new();
        let mut completed_hash: HashSet<String> = HashSet::new();
        let components = self.document_root.components.clone();

        // Smart cache: on updates, inject cached remote component data instead of re-fetching.
        // On initial load, do the full prefetch + variant resolution and store results.
        if !self.is_update {
            // INITIAL LOAD: Full remote component resolution
            let new_components =
                self.prefetch_remote_components(&root_node, &components, &id_index);

            let mut all_discovered_keys: HashSet<String> = HashSet::new();
            Self::collect_remote_component_keys(
                &root_node,
                &components,
                &id_index,
                &mut all_discovered_keys,
            );
            for key in &all_discovered_keys {
                if !new_components.contains_key(key)
                    && !self.prefetched_components.contains_key(key)
                {
                    self.failed_component_keys.insert(key.clone());
                }
            }
            for (k, v) in new_components {
                self.prefetched_components.insert(k, v);
            }

            // Full variant resolution
            self.fetch_component_variants(
                &root_node,
                &mut node_doc_hash,
                &mut variant_nodes,
                &id_index,
                &components,
                &mut parent_tree,
                error_list,
                &mut error_hash,
                &mut completed_hash,
                hidden_node_policy,
            )?;
            self.variant_nodes = variant_nodes;

            // Index variant nodes
            for (_, node) in &self.variant_nodes {
                index_node(
                    node,
                    None,
                    &mut name_index,
                    &mut id_index,
                    &mut variant_index,
                    &mut component_set_name_index,
                    &mut component_id_index,
                    hidden_node_policy,
                );
            }

            // Store in smart cache for future updates
            if let Ok(mut cache) = SMART_CACHE.lock() {
                if let Some(entry) = cache.get_mut(&self.document_id) {
                    entry.prefetched_components = self.prefetched_components.clone();
                    entry.variant_nodes = self.variant_nodes.clone();
                    entry.failed_component_keys = self.failed_component_keys.clone();
                    info!(
                        "Smart cache: stored {} remote components and {} variant nodes for {}",
                        entry.prefetched_components.len(),
                        entry.variant_nodes.len(),
                        self.document_id
                    );
                }
            }
        } else {
            // UPDATE: Inject cached remote component data
            let cached = SMART_CACHE.lock().ok().and_then(|c| c.get(&self.document_id).cloned());
            if let Some(entry) = cached {
                info!(
                    "Smart cache HIT: injecting {} remote components and {} variant nodes for {}",
                    entry.prefetched_components.len(),
                    entry.variant_nodes.len(),
                    self.document_id
                );
                self.prefetched_components = entry.prefetched_components;
                self.failed_component_keys = entry.failed_component_keys;
                self.variant_nodes = entry.variant_nodes;

                // Re-index the cached variant nodes
                for (_, node) in &self.variant_nodes {
                    index_node(
                        node,
                        None,
                        &mut name_index,
                        &mut id_index,
                        &mut variant_index,
                        &mut component_set_name_index,
                        &mut component_id_index,
                        hidden_node_policy,
                    );
                }
            } else {
                info!(
                    "Smart cache MISS on update for {} — doing full remote resolution",
                    self.document_id
                );
                // Fallback: full resolution
                let new_components =
                    self.prefetch_remote_components(&root_node, &components, &id_index);
                let mut all_discovered_keys: HashSet<String> = HashSet::new();
                Self::collect_remote_component_keys(
                    &root_node,
                    &components,
                    &id_index,
                    &mut all_discovered_keys,
                );
                for key in &all_discovered_keys {
                    if !new_components.contains_key(key)
                        && !self.prefetched_components.contains_key(key)
                    {
                        self.failed_component_keys.insert(key.clone());
                    }
                }
                for (k, v) in new_components {
                    self.prefetched_components.insert(k, v);
                }
                self.fetch_component_variants(
                    &root_node,
                    &mut node_doc_hash,
                    &mut variant_nodes,
                    &id_index,
                    &components,
                    &mut parent_tree,
                    error_list,
                    &mut error_hash,
                    &mut completed_hash,
                    hidden_node_policy,
                )?;
                self.variant_nodes = variant_nodes;
                for (_, node) in &self.variant_nodes {
                    index_node(
                        node,
                        None,
                        &mut name_index,
                        &mut id_index,
                        &mut variant_index,
                        &mut component_set_name_index,
                        &mut component_id_index,
                        hidden_node_policy,
                    );
                }
            }
        }

        // Convert node_names into a HashSet. Then, for any node names that are a component set,
        // add all of its children (which are variants) into the node name hash.
        // Also add all component sets to component_set_hash, mapping the component set name to
        // a list of all their variant children.
        let mut node_name_hash: HashSet<NodeQuery> = HashSet::from_iter(node_names.iter().cloned());
        // Convert node_names into a list of nodes. We'll use this list in find_component_sets to
        // add any component sets whose instances are in the tree of any nodes in query_nodes. This
        // ensures that we have access to other component variants.
        let query_nodes: Vec<&figma_schema::Node> = node_names
            .iter()
            .map(|name| {
                // Look up the node if it's defined.
                let maybe_node = match &name {
                    NodeQuery::NodeId(id) => id_index.get(id),
                    NodeQuery::NodeName(node_name) => name_index.get(node_name),
                    NodeQuery::NodeComponentSet(node_name) => name_index.get(node_name),
                    NodeQuery::NodeVariant(node_name, parent_name) => {
                        variant_index.get(&(node_name.clone(), parent_name.clone()))
                    }
                };
                maybe_node
            })
            .filter(|maybe_node| maybe_node.is_some())
            .map(|node| *node.unwrap()) // safe to unwrap
            .collect();
        find_component_sets(&query_nodes, &component_id_index, &mut node_name_hash);
        let mut component_set_hash: HashMap<String, Vec<String>> = HashMap::new();
        add_variant_node_names(
            &self.document_root.document,
            &mut node_name_hash,
            &mut component_set_hash,
        );

        // Some nodes may have additional plugin data that specifies an overflow node. Look for these
        // and add them to node_name_hash
        add_overflow_nodes(&self.document_root.document, &mut node_name_hash);

        // Find the initial list of nodes we want to convert. This list excludes nodes that are hidden
        let mut nodes: Vec<(NodeQuery, &figma_schema::Node)> = node_name_hash
            .into_iter()
            .map(|name| {
                // Look up the node if it's defined.
                let maybe_node = match &name {
                    NodeQuery::NodeId(id) => id_index.get(id),
                    NodeQuery::NodeName(node_name) => name_index.get(node_name),
                    NodeQuery::NodeComponentSet(node_name) => {
                        component_set_name_index.get(node_name)
                    }
                    NodeQuery::NodeVariant(node_name, parent_name) => {
                        variant_index.get(&(node_name.clone(), parent_name.clone()))
                    }
                };

                // Yield up both the query and the node so that we can return the
                // query with the converted node.
                (name, maybe_node)
            })
            .filter(|(_, maybe_node)| maybe_node.is_some())
            .map(|(k, node)| (k, *node.unwrap())) // safe to unwrap
            .collect();

        // We use ComponentContext to track all of the nodes that need to be converted to
        // satisfy reactions.
        let mut component_context = ComponentContext::new(&nodes);
        let mut views = HashMap::new();

        loop {
            // XXX: Very silly cloning here; why doesn't DocumentKey do this once?

            // Add the ignored images into a hash map for easier access
            let mut ignored_image_hash: HashMap<NodeQuery, HashSet<String>> = HashMap::new();
            for (node_name, node_images) in ignored_images {
                let mut img_set: HashSet<String> = HashSet::new();
                for img in node_images {
                    img_set.insert(img.to_string());
                }
                ignored_image_hash.insert(node_name.clone(), img_set);

                // If node_name is a component set, all its variant children use the same set of ignored images
                if let NodeQuery::NodeName(name) = node_name {
                    let variant_list = component_set_hash.get(name);
                    if let Some(variant_list) = variant_list {
                        for variant_name in variant_list {
                            let mut img_set: HashSet<String> = HashSet::new();
                            for img in node_images {
                                img_set.insert(img.to_string());
                            }
                            ignored_image_hash.insert(NodeQuery::name(variant_name), img_set);
                        }
                    }
                }
            }
            // Now we can transform from the Figma schema to the toolkit schema.
            for (query, node) in nodes {
                // Set the set of images to ignore for this node
                let ignored_image_set = ignored_image_hash.get(&NodeQuery::name(node.name.clone()));
                self.image_context.set_ignored_images(ignored_image_set);

                views.insert(
                    query,
                    create_component_flexbox(
                        node,
                        &self.document_root.components,
                        &self.document_root.component_sets,
                        &mut component_context,
                        &mut self.image_context,
                        hidden_node_policy,
                        &mut self.key_to_global_id_map,
                    )?,
                );
            }

            // If we have no more nodes then we can break out.
            nodes = component_context.referenced_list(&id_index);

            // We use a hashset inside of ComponentContext to ensure that we don't request the same
            // nodes over and over.
            if nodes.is_empty() {
                break;
            }
        }

        // Populate the override data for components.
        Self::compute_component_overrides(&mut views);

        // Update our mapping from instance to component set.
        self.component_sets = component_id_index
            .iter()
            .map(|(component_id, component_set_node)| {
                (component_id.clone(), component_set_node.id.clone())
            })
            .collect();

        // If there are nodes that were referenced that we weren't able to convert then we can report them
        // here. Ideally we'd log this so that a customer could see it and figure out what's going on and
        // why an action isn't working.
        let missing_nodes = component_context.missing_nodes();
        if !missing_nodes.is_empty() {
            warn!("Figma: Unable to find nodes referenced by interactions: {:?}", missing_nodes);
            warn!("       These interactions won't work.");
        }
        Ok(views)
    }

    // Parse through all the variables collected and store them into hash tables for easy access
    pub fn build_variable_map(&self) -> VariableMap {
        let mut collections_by_id: HashMap<String, Collection> = HashMap::new();
        let mut collection_ids_by_name: HashMap<String, String> = HashMap::new();
        let mut variables_by_id: HashMap<String, Variable> = HashMap::new();
        let mut variable_name_id_maps_by_cid: HashMap<String, NameIdMap> = HashMap::new();

        for variables_response in self.variables_responses.values() {
            for (_, c) in variables_response.meta.variable_collections.iter() {
                let mut mode_name_hash: HashMap<String, String> = HashMap::new();
                let mut mode_id_hash: HashMap<String, Mode> = HashMap::new();
                for m in &c.modes {
                    let mode =
                        Mode { id: m.mode_id.clone(), name: m.name.clone(), ..Default::default() };
                    mode_name_hash.insert(mode.name.clone(), mode.id.clone());
                    mode_id_hash.insert(mode.id.clone(), mode);
                }
                let collection = Collection {
                    id: c.id.clone(),
                    name: c.name.clone(),
                    default_mode_id: c.default_mode_id.clone(),
                    mode_name_hash,
                    mode_id_hash,
                    ..Default::default()
                };
                collections_by_id.insert(collection.id.clone(), collection);
                collection_ids_by_name.insert(c.name.clone(), c.id.clone());
            }

            for (id, v) in variables_response.meta.variables.iter() {
                let var = create_variable(v);
                // If we have a global ID for this variable's key, use it. Otherwise, use the local ID.
                let map_key =
                    self.key_to_global_id_map.get(&var.key).cloned().unwrap_or_else(|| id.clone());

                let maybe_name_map =
                    variable_name_id_maps_by_cid.get_mut(&var.variable_collection_id);
                if let Some(name_map) = maybe_name_map {
                    name_map.m.insert(var.name.clone(), map_key.clone());
                } else {
                    let mut name_to_id = HashMap::new();
                    name_to_id.insert(var.name.clone(), map_key.clone());
                    variable_name_id_maps_by_cid.insert(
                        var.variable_collection_id.clone(),
                        NameIdMap { m: name_to_id, ..Default::default() },
                    );
                }
                variables_by_id.insert(map_key, var);
            }
        }

        let var_map = VariableMap {
            collections_by_id,
            collection_ids_by_name,
            variables_by_id,
            variable_name_id_maps_by_cid,
            ..Default::default()
        };

        // Post-process: detect unresolved variable aliases.
        // An alias is unresolved when its target variable ID is not present in the
        // merged variable map. This typically happens when the alias target lives
        // in a library doc that wasn't fetched through component dependencies.
        let mut unresolved_count = 0;
        for (var_id, var) in &var_map.variables_by_id {
            if let Some(ref values_by_mode) = var.values_by_mode.as_ref() {
                for (mode_id, value) in &values_by_mode.values_by_mode {
                    if let Some(dc_bundle::variable::variable_value::Value::Alias(alias_id)) =
                        &value.Value
                    {
                        if !var_map.variables_by_id.contains_key(alias_id) {
                            warn!(
                                "Unresolved variable alias: variable '{}' (id={}) in mode '{}' \
                                 aliases '{}' which is not in the variable map. \
                                 The aliased variable's library may not have been fetched.",
                                var.name, var_id, mode_id, alias_id
                            );
                            unresolved_count += 1;
                        }
                    }
                }
            }
        }
        if unresolved_count > 0 {
            warn!(
                "build_variable_map: {} unresolved variable alias(es) detected. \
                 These variables will fall back to default values at runtime.",
                unresolved_count
            );
        }

        var_map
    }

    /// Return the EncodedImageMap containing the mapping from ImageKey references in Nodes returned by this document
    /// to encoded image bytes. EncodedImageMap can be serialized and deserialized, and transformed into an ImageMap.
    pub fn encoded_image_map(&self) -> EncodedImageMap {
        self.image_context.encoded_image_map()
    }

    /// Return the ImageContextSession so that subsequent requests can avoid fetching the same images. We also return
    /// the list of all images referenced by this document, so that a client knows which images to copy from the old
    /// document (if it requested an incremental update).
    pub fn image_session(&self) -> ImageContextSession {
        self.image_context.as_session()
    }

    /// Return the mapping from Component node ID to Component Set node ID.
    pub fn component_sets(&self) -> &HashMap<String, String> {
        &self.component_sets
    }

    /// Get all the Figma documents in the given project ID
    pub fn get_projects(&self, project_id: &str) -> Result<Vec<FigmaDocInfo>, Error> {
        let url = format!("{}{}/files", BASE_PROJECT_URL, project_id);
        let project_files: figma_schema::ProjectFilesResponse = serde_json::from_str(
            http_fetch(self.api_key.as_str(), url, &self.proxy_config)?.as_str(),
        )?;

        let mut figma_docs: Vec<FigmaDocInfo> = vec![];
        for file_hash in &project_files.files {
            if let Some(doc_id) = file_hash.get("key") {
                if let Some(name) = file_hash.get("name") {
                    let figma_doc = FigmaDocInfo {
                        name: name.clone(),
                        id: doc_id.clone(),
                        ..Default::default()
                    };
                    // Getting project files return head version of the files.
                    figma_docs.push(figma_doc);
                }
            }
        }

        Ok(figma_docs)
    }

    /// Get the name of the document
    pub fn get_name(&self) -> String {
        self.document_root.name.clone()
    }

    /// Get the document ID of the document
    pub fn get_document_id(&self) -> String {
        self.document_id.clone()
    }

    /// Get the version string in the document's file response
    pub fn get_version(&self) -> String {
        self.document_root.version.clone()
    }

    pub fn cache(&self) -> HashMap<String, String> {
        self.image_context.cache()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_document_id_formats() {
        assert_eq!(parse_document_id("ABC"), "ABC");
        assert_eq!(parse_document_id("https://www.figma.com/file/XYZ"), "XYZ");
        assert_eq!(parse_document_id("https://www.figma.com/file/XYZ/node-id"), "XYZ");
        assert_eq!(parse_document_id("https://www.figma.com/design/123"), "123");
        assert_eq!(parse_document_id("https://www.figma.com/design/123/node-id"), "123");
    }

    #[derive(serde::Deserialize, Debug)]
    struct DummyStruct {
        field: String,
    }

    #[derive(serde::Deserialize, Debug)]
    struct DummyParent {
        child: DummyStruct,
    }

    #[test]
    fn test_deserialize_json_with_path_errors() {
        let bad_json = r#"{"child": {"field": 123}}"#;
        let result: Result<DummyParent, Error> = deserialize_json_with_path(bad_json);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("Json Path Serialization Error"));
        assert!(err_msg.contains("child.field"));
    }

    #[test]
    fn test_deserialize_json_with_path_success() {
        let good_json = r#"{"child": {"field": "value"}}"#;
        let result: Result<DummyParent, Error> = deserialize_json_with_path(good_json);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().child.field, "value");
    }

    #[test]
    fn test_compute_component_overrides_coverage() {
        use dc_bundle::positioning::ScrollInfo;
        use dc_bundle::view::view::RenderMethod;
        use dc_bundle::view_shape::ViewShape;
        use std::collections::HashMap;

        let mut views = HashMap::new();

        // 1. Reference Component
        let ref_id = "ref_id".to_string();
        let ref_view = View::new_rect(
            &ref_id,
            &"RefComponent".to_string(),
            ViewShape::default(),
            ViewStyle::new_default(),
            None,
            None,
            ScrollInfo::new_default(),
            None,
            None,
            RenderMethod::RENDER_METHOD_NONE,
            HashMap::new(),
        );
        views.insert(NodeQuery::NodeId(ref_id.clone()), ref_view.clone());
        views.insert(NodeQuery::NodeVariant("RefComponent".to_string(), "".to_string()), ref_view);

        // 2. Instance 1 (Root of instance)
        let mut comp_info1 = ComponentInfo::default();
        comp_info1.id = ref_id.clone();
        comp_info1.name = "RefComponent".to_string();

        let inst1_id = "inst1_id".to_string();
        let mut inst1 = View::new_rect(
            &inst1_id,
            &"Instance1".to_string(),
            ViewShape::default(),
            ViewStyle::new_default(),
            Some(comp_info1),
            None,
            ScrollInfo::new_default(),
            None,
            None,
            RenderMethod::RENDER_METHOD_NONE,
            HashMap::new(),
        );

        // 3. Child 1 (Descendant of instance 1)
        let child1_id = "child1_id".to_string();
        let child1 = View::new_rect(
            &child1_id,
            &"Child1".to_string(),
            ViewShape::default(),
            ViewStyle::new_default(),
            None,
            None,
            ScrollInfo::new_default(),
            None,
            None,
            RenderMethod::RENDER_METHOD_NONE,
            HashMap::new(),
        );

        // 4. Instance 2 (Nested Instance)
        let mut comp_info2 = ComponentInfo::default();
        comp_info2.id = ref_id.clone();
        comp_info2.name = "RefComponent".to_string();

        let inst2_id = "inst2_id".to_string();
        let inst2 = View::new_rect(
            &inst2_id,
            &"Instance2".to_string(),
            ViewShape::default(),
            ViewStyle::new_default(),
            Some(comp_info2),
            None,
            ScrollInfo::new_default(),
            None,
            None,
            RenderMethod::RENDER_METHOD_NONE,
            HashMap::new(),
        );

        // Assemble the tree: inst1 -> [child1, inst2]
        inst1.add_child(child1);
        inst1.add_child(inst2);

        views.insert(NodeQuery::NodeId(inst1_id), inst1);

        // Call the method
        Document::compute_component_overrides(&mut views);

        // Assert that we completed execution without panic
        assert!(true);
    }
}