earthsci-ast 0.6.0

Rust implementation of EarthSciML Abstract Syntax Tree Format
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
//! Graph utilities for analyzing model structure and coupling

use crate::{CouplingEntry, EsmFile};

/// Return a map's keys sorted lexicographically.
///
/// Node and edge order feeds rendered output (`to_dot`/`to_mermaid`/
/// `to_json_graph`), so every component/variable map is iterated in
/// sorted-key order rather than nondeterministic `HashMap` order.
fn sorted_keys<V>(map: &indexmap::IndexMap<String, V>) -> Vec<&String> {
    let mut keys: Vec<&String> = map.keys().collect();
    keys.sort();
    keys
}

/// The scope a target with no owning component reports (esm-libraries-spec
/// §4.8.2). A bare `Model`/`ReactionSystem`/`Equation`/`Reaction`/`Expr` handed
/// straight to [`expression_graph`] has no document position, so its variables
/// are unscoped and belong to the pseudo-system `default`.
const DEFAULT_SYSTEM: &str = "default";

/// `equation_index` for a dependency that no positionally-numbered equation or
/// reaction produced: a `variable_map` folded in by
/// [`ExpressionGraphOptions::merge_coupled`], and the synthetic `expr_result`
/// edges of a bare-expression target.
const NON_EQUATION_INDEX: i64 = -1;

/// Which incident edges a closure query follows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Direction {
    /// Both directions — the undirected neighbourhood.
    Both,
    /// Edges pointing AT the node.
    Incoming,
    /// Edges pointing AWAY from the node.
    Outgoing,
}

/// The neighbours of `node` reachable over `edges` in `direction`, sorted and
/// deduplicated.
///
/// `known` reports whether `node` is a registered graph node: an unknown key
/// resolves to `[]` rather than scanning. A neighbour is NOT required to be a
/// registered node — the guard is on the node being asked about, matching the
/// reference implementation.
fn neighbours<'a, I>(known: bool, edges: I, node: &str, direction: Direction) -> Vec<String>
where
    I: Iterator<Item = (&'a str, &'a str)>,
{
    if !known {
        return Vec::new();
    }
    let mut out = std::collections::BTreeSet::new();
    for (source, target) in edges {
        if direction != Direction::Incoming && source == node {
            out.insert(target.to_string());
        }
        if direction != Direction::Outgoing && target == node {
            out.insert(source.to_string());
        }
    }
    out.into_iter().collect()
}

/// Render a graph as the JSON adjacency-list export of esm-libraries-spec
/// §4.8.3: `{"nodes": [...], "edges": [...], "adjacency": {...}}`.
///
/// Every node object carries an `id` (a component node's `id`, a variable
/// node's `name`) alongside its own serialized fields; every edge is
/// `{source, target, data}`; `adjacency` maps each node key to its UNDIRECTED
/// neighbourhood.
fn render_json_graph<N, E>(
    nodes: &[N],
    node_key: impl Fn(&N) -> String,
    edges: &[E],
    edge_endpoints: impl Fn(&E) -> (String, String),
    adjacency: impl Fn(&str) -> Vec<String>,
) -> String
where
    N: serde::Serialize,
    E: serde::Serialize,
{
    let json_nodes: Vec<serde_json::Value> = nodes
        .iter()
        .map(|node| {
            let key = node_key(node);
            let mut value = serde_json::to_value(node).unwrap_or(serde_json::Value::Null);
            if let Some(object) = value.as_object_mut() {
                object.insert("id".to_string(), serde_json::Value::String(key));
            }
            value
        })
        .collect();

    let json_edges: Vec<serde_json::Value> = edges
        .iter()
        .map(|edge| {
            let (source, target) = edge_endpoints(edge);
            serde_json::json!({
                "source": source,
                "target": target,
                "data": serde_json::to_value(edge).unwrap_or(serde_json::Value::Null),
            })
        })
        .collect();

    let mut json_adjacency = serde_json::Map::new();
    for node in nodes {
        let key = node_key(node);
        let neighbours = adjacency(&key);
        json_adjacency.insert(key, serde_json::to_value(neighbours).unwrap_or_default());
    }

    let graph = serde_json::json!({
        "nodes": json_nodes,
        "edges": json_edges,
        "adjacency": serde_json::Value::Object(json_adjacency),
    });
    serde_json::to_string_pretty(&graph).unwrap_or_else(|_| "{}".to_string())
}

/// Component graph representing model structure
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ComponentGraph {
    /// Nodes in the graph (models, reaction systems)
    pub nodes: Vec<ComponentNode>,
    /// Edges representing coupling relationships
    pub edges: Vec<CouplingEdge>,
}

/// Summary counts a component node carries (esm-libraries-spec §4.8.1).
///
/// A model reports its declared variables and its equations; a reaction system
/// reports its reactions as `eq_count`, its species as `species_count`, and its
/// PARAMETERS as `var_count` — the schema forbids a `variables` field there and
/// `species_count` already carries the species, so `parameters` is the only
/// thing left for §4.8.1's "variable count" to mean, and it is the exact
/// analogue of a model's `variables` (which likewise counts unknowns and
/// parameters together). Subsystems contribute NOTHING — the counts describe
/// the component's own body, matching the reference implementation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub struct ComponentMetadata {
    /// Declared variables (models only)
    pub var_count: usize,
    /// Equations (models) or reactions (reaction systems)
    pub eq_count: usize,
    /// Declared species (reaction systems only)
    pub species_count: usize,
}

/// Node in the component graph
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ComponentNode {
    /// Unique node identifier
    pub id: String,
    /// Type of component
    pub component_type: ComponentType,
    /// Human-readable name
    pub name: Option<String>,
    /// Summary counts (§4.8.1)
    pub metadata: ComponentMetadata,
}

/// Type of component in the graph.
///
/// There is no data-source arm. esm-libraries-spec §4.8.1 is explicit that "a
/// `data_sources` entry is not a component and is NOT a node": from 1.0.0
/// external data reaches a model as a PARAMETER whose `update` names the
/// source, so the dependency is already carried by that parameter's node.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ComponentType {
    /// ODE model
    Model,
    /// Reaction system
    ReactionSystem,
}

/// Kind of coupling relationship represented by an edge
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CouplingEdgeKind {
    /// Operator composition of two named systems
    OperatorCompose,
    /// Direct coupling of two named systems
    Couple,
    /// Variable mapping between two systems
    VariableMap,
}

impl std::fmt::Display for CouplingEdgeKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            CouplingEdgeKind::OperatorCompose => "operator_compose",
            CouplingEdgeKind::Couple => "couple",
            CouplingEdgeKind::VariableMap => "variable_map",
        })
    }
}

/// Edge in the component graph
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CouplingEdge {
    /// Source component ID
    pub from: String,
    /// Target component ID
    pub to: String,
    /// Type of coupling
    pub coupling_type: CouplingEdgeKind,
    /// Human-readable edge label (§4.8.1): `compose` / `couple`, or, for a
    /// `variable_map`, the mapped variable — everything after the FIRST dot of
    /// the `from` reference.
    pub label: String,
    /// Additional coupling data
    pub data: serde_json::Value,
}

/// Build a component graph from an ESM file
///
/// # Arguments
///
/// * `esm_file` - The ESM file to analyze
///
/// # Returns
///
/// * Component graph showing structure and coupling
pub fn component_graph(esm_file: &EsmFile) -> ComponentGraph {
    let mut nodes = Vec::new();
    let mut edges = Vec::new();

    // Add model nodes
    if let Some(ref models) = esm_file.models {
        for id in sorted_keys(models) {
            let model = &models[id];
            nodes.push(ComponentNode {
                id: id.clone(),
                component_type: ComponentType::Model,
                name: model.name.clone(),
                metadata: ComponentMetadata {
                    var_count: model.variables.len(),
                    eq_count: model.equations.len(),
                    species_count: 0,
                },
            });
        }
    }

    // Add reaction system nodes
    if let Some(ref reaction_systems) = esm_file.reaction_systems {
        for id in sorted_keys(reaction_systems) {
            let rs = &reaction_systems[id];
            nodes.push(ComponentNode {
                id: id.clone(),
                component_type: ComponentType::ReactionSystem,
                name: None,
                metadata: ComponentMetadata {
                    var_count: rs.parameters.len(),
                    eq_count: rs.reactions.len(),
                    species_count: rs.species.len(),
                },
            });
        }
    }

    // NOTE: `data_sources` contributes NO nodes (esm-libraries-spec §4.8.1). A
    // data source is a document-scoped ingest registry exposing no variables of
    // its own; a model reaches it through a parameter whose `update` names it,
    // so the dependency it creates is already carried by that parameter.

    // Add coupling edges.
    //
    // Coupling edges only connect endpoints that are real component nodes
    // (models, reaction systems). Coupling kinds that do not name two concrete
    // components (operator_apply, callback, event, coupling_import) contribute
    // no edge to the source-level component graph.
    let node_ids: std::collections::HashSet<&str> = nodes.iter().map(|n| n.id.as_str()).collect();

    if let Some(ref coupling_entries) = esm_file.coupling {
        for entry in coupling_entries {
            // Resolve each coupling entry to a (from, to, kind, label) tuple.
            //
            // `operator_compose`/`couple` name two concrete systems;
            // `variable_map` resolves each endpoint to its owning system via the
            // scope prefix and labels the edge with the mapped variable. Kinds
            // that do not name two concrete components (operator_apply,
            // callback, event, coupling_import) contribute no edge.
            let (from, to, kind, label) = match entry {
                CouplingEntry::OperatorCompose { systems, .. } => {
                    if systems.len() >= 2 {
                        (
                            systems[0].clone(),
                            systems[1].clone(),
                            CouplingEdgeKind::OperatorCompose,
                            "compose".to_string(),
                        )
                    } else {
                        continue; // Skip invalid coupling
                    }
                }
                CouplingEntry::Couple { systems, .. } => {
                    if systems.len() == 2 {
                        (
                            systems[0].clone(),
                            systems[1].clone(),
                            CouplingEdgeKind::Couple,
                            "couple".to_string(),
                        )
                    } else {
                        continue; // Skip invalid coupling
                    }
                }
                CouplingEntry::VariableMap { from, to, .. } => {
                    // BOTH endpoints must be SCOPED (`System.variable...`): an
                    // unscoped reference names no component, so it can neither
                    // anchor an edge nor label one. The label is everything
                    // after the FIRST dot of `from`.
                    let (Some((from_system, from_var)), Some((to_system, _))) =
                        (from.split_once('.'), to.split_once('.'))
                    else {
                        continue;
                    };
                    (
                        from_system.to_string(),
                        to_system.to_string(),
                        CouplingEdgeKind::VariableMap,
                        from_var.to_string(),
                    )
                }
                // These coupling kinds do not name two concrete component nodes,
                // so they contribute no edge to the component graph.
                CouplingEntry::OperatorApply { .. }
                | CouplingEntry::Callback { .. }
                | CouplingEntry::Event { .. }
                | CouplingEntry::CouplingImport { .. } => continue,
            };

            // Only emit an edge when both endpoints are real graph nodes.
            if node_ids.contains(from.as_str()) && node_ids.contains(to.as_str()) {
                edges.push(CouplingEdge {
                    from,
                    to,
                    coupling_type: kind,
                    label,
                    data: serde_json::Value::Null,
                });
            }
        }
    }

    ComponentGraph { nodes, edges }
}

/// Check if a component exists in the ESM file
///
/// # Arguments
///
/// * `esm_file` - The ESM file to check
/// * `component_id` - The component ID to look for
///
/// # Returns
///
/// * `true` if the component exists, `false` otherwise
pub fn component_exists(esm_file: &EsmFile, component_id: &str) -> bool {
    get_component_type(esm_file, component_id).is_some()
}

/// Get the type of a component
///
/// A `data_sources` id is NOT a component (esm-libraries-spec §4.8.1) and
/// resolves to `None`.
///
/// # Arguments
///
/// * `esm_file` - The ESM file to check
/// * `component_id` - The component ID to look for
///
/// # Returns
///
/// * `Some(ComponentType)` if the component exists
/// * `None` if the component doesn't exist
pub fn get_component_type(esm_file: &EsmFile, component_id: &str) -> Option<ComponentType> {
    fn contains<V>(map: &Option<indexmap::IndexMap<String, V>>, key: &str) -> bool {
        map.as_ref().is_some_and(|m| m.contains_key(key))
    }

    if contains(&esm_file.models, component_id) {
        Some(ComponentType::Model)
    } else if contains(&esm_file.reaction_systems, component_id) {
        Some(ComponentType::ReactionSystem)
    } else {
        None
    }
}

/// Expression graph representing variable dependencies within expressions
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExpressionGraph {
    /// Nodes representing variables only (no operators or constants)
    pub nodes: Vec<VariableNode>,
    /// Edges representing dependencies between variables
    pub edges: Vec<DependencyEdge>,
}

/// Node representing a variable in an expression graph
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct VariableNode {
    /// Variable name, SCOPED by its owning system (`Transport.temperature`).
    /// A variable of the pseudo-system `default` — a bare target handed
    /// straight to [`expression_graph`] — is unscoped.
    pub name: String,
    /// Variable kind/type
    pub kind: VariableKind,
    /// Physical units (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub units: Option<String>,
    /// Which model/system owns this variable
    pub system: String,
}

/// Type/kind of variable, as the graph renders it.
///
/// These are the esm-spec §6.3.1 DERIVED categories, not declared types — esm
/// 1.0.0 declares only `unknown` and `parameter`. The mapping is fixed by
/// [`variable_kind`].
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VariableKind {
    /// An ODE state — an unknown carrying a time derivative.
    State,
    /// An unknown pinned only by an implicit algebraic constraint. Solved for
    /// like a state, but not differentiated.
    Algebraic,
    /// A constant or sampled parameter.
    Parameter,
    /// An unknown defined by a bare-variable equation — eliminable.
    Observed,
    /// A parameter whose update is `wiener` — any present promotes the model
    /// to an SDE.
    Brownian,
    /// A parameter carrying any other update: piecewise-constant between
    /// refreshes, never differentiated by the solver.
    Discrete,
    /// Chemical species
    Species,
}

/// The graph kind of one variable, derived through [`crate::classification`]
/// (esm-spec §6.3.1) rather than read off a declared type.
fn variable_kind(class: &crate::classification::Classification, name: &str) -> VariableKind {
    if class.is_observed(name) {
        VariableKind::Observed
    } else if class.is_brownian(name) {
        VariableKind::Brownian
    } else if class.is_discrete_parameter(name) {
        VariableKind::Discrete
    } else if class.ode_states.iter().any(|s| s == name) {
        VariableKind::State
    } else if class.algebraic_unknowns.iter().any(|s| s == name) {
        VariableKind::Algebraic
    } else {
        VariableKind::Parameter
    }
}

/// Edge representing dependencies between variables in an expression graph
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DependencyEdge {
    /// Source variable name (influences the target)
    pub source: String,
    /// Target variable name (is influenced by the source)
    pub target: String,
    /// How the dependency arises
    pub relationship: DependencyRelationship,
    /// Which equation/reaction index produced this edge, or `-1` when no
    /// positionally-numbered equation did (a folded `variable_map`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub equation_index: Option<i64>,
    /// The relevant subexpression (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expression: Option<crate::Expr>,
}

/// PROVENANCE of a dependency — which structural site produced it, NOT a
/// classification of the operators involved. An equation edge is always
/// `Additive` (even for `w ~ u * v`) and a definition edge always
/// `Multiplicative` (even for `w ~ u + v`).
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DependencyRelationship {
    /// An RHS variable of an equation → the variable that equation defines.
    Additive,
    /// A free variable of an expression definition or a coupling variable map
    /// → the value it defines.
    Multiplicative,
    /// A reaction-rate variable → a species the reaction consumes or produces.
    Rate,
    /// A substrate species → a product species, via stoichiometry.
    Stoichiometric,
}

/// Settings for [`expression_graph_with_options`].
#[derive(Debug, Clone, Default)]
pub struct ExpressionGraphOptions {
    /// Fold `variable_map` coupling entries into cross-system dependency edges
    /// (esm-libraries-spec §4.8.2, "coupled file-level graph"). Applies to
    /// [`EsmFile`] targets only; every other target carries no coupling list.
    pub merge_coupled: bool,
}

/// Build an expression graph from various ESM components
///
/// # Arguments
///
/// * `input` - Can be an ESM file, model, reaction system, equation, reaction, or expression
///
/// # Returns
///
/// * `ExpressionGraph` - Graph showing variable dependencies
pub fn expression_graph<T>(input: &T) -> ExpressionGraph
where
    T: ExpressionGraphInput,
{
    input.build_expression_graph()
}

/// Build an expression graph with explicit [`ExpressionGraphOptions`].
///
/// # Arguments
///
/// * `input` - Can be an ESM file, model, reaction system, equation, reaction, or expression
/// * `options` - Settings; options that do not apply to `input` are ignored
///
/// # Returns
///
/// * `ExpressionGraph` - Graph showing variable dependencies
pub fn expression_graph_with_options<T>(
    input: &T,
    options: &ExpressionGraphOptions,
) -> ExpressionGraph
where
    T: ExpressionGraphInput,
{
    input.build_expression_graph_with_options(options)
}

/// Trait for types that can build expression graphs
pub trait ExpressionGraphInput {
    /// Build the graph with default options.
    fn build_expression_graph(&self) -> ExpressionGraph;

    /// Build the graph honouring `options`. The default implementation ignores
    /// them: only [`EsmFile`] carries a coupling list for `merge_coupled` to
    /// fold in.
    fn build_expression_graph_with_options(
        &self,
        _options: &ExpressionGraphOptions,
    ) -> ExpressionGraph {
        self.build_expression_graph()
    }
}

/// The growing node/edge lists of one expression-graph build, plus the dedup
/// index that keys nodes by their SCOPED name.
struct ExprGraphBuilder {
    nodes: Vec<VariableNode>,
    edges: Vec<DependencyEdge>,
    seen: std::collections::HashSet<String>,
}

impl ExprGraphBuilder {
    fn new() -> Self {
        ExprGraphBuilder {
            nodes: Vec::new(),
            edges: Vec::new(),
            seen: std::collections::HashSet::new(),
        }
    }

    /// Add a node, deduplicated by its scoped name, and return that name. A
    /// name already present keeps the kind and units it was first added with —
    /// declared variables are added before the equations that mention them, so
    /// a declaration always wins over the `parameter`/`state` fallback an
    /// equation would supply.
    fn add_node(
        &mut self,
        name: &str,
        kind: VariableKind,
        units: Option<String>,
        system: &str,
    ) -> String {
        let scoped = if system == DEFAULT_SYSTEM {
            name.to_string()
        } else {
            format!("{system}.{name}")
        };
        if self.seen.insert(scoped.clone()) {
            self.nodes.push(VariableNode {
                name: scoped.clone(),
                kind,
                units,
                system: system.to_string(),
            });
        }
        scoped
    }

    fn add_dependency(
        &mut self,
        source: String,
        target: String,
        relationship: DependencyRelationship,
        equation_index: i64,
        expression: Option<crate::Expr>,
    ) {
        self.edges.push(DependencyEdge {
            source,
            target,
            relationship,
            equation_index: Some(equation_index),
            expression,
        });
    }

    fn finish(self) -> ExpressionGraph {
        ExpressionGraph {
            nodes: self.nodes,
            edges: self.edges,
        }
    }
}

impl ExpressionGraphInput for crate::EsmFile {
    fn build_expression_graph(&self) -> ExpressionGraph {
        self.build_expression_graph_with_options(&ExpressionGraphOptions::default())
    }

    fn build_expression_graph_with_options(
        &self,
        options: &ExpressionGraphOptions,
    ) -> ExpressionGraph {
        let mut b = ExprGraphBuilder::new();

        // Sorted-key iteration: node/edge order feeds rendered output and
        // must not depend on HashMap ordering.
        if let Some(ref models) = self.models {
            for model_id in sorted_keys(models) {
                process_model_tree(&mut b, &models[model_id], model_id);
            }
        }

        if let Some(ref reaction_systems) = self.reaction_systems {
            for rs_id in sorted_keys(reaction_systems) {
                process_reaction_system_tree(&mut b, &reaction_systems[rs_id], rs_id);
            }
        }

        if options.merge_coupled
            && let Some(ref coupling) = self.coupling
        {
            process_coupling(&mut b, coupling);
        }

        b.finish()
    }
}

impl ExpressionGraphInput for crate::Model {
    fn build_expression_graph(&self) -> ExpressionGraph {
        let mut b = ExprGraphBuilder::new();
        process_model_tree(&mut b, self, DEFAULT_SYSTEM);
        b.finish()
    }
}

impl ExpressionGraphInput for crate::ReactionSystem {
    fn build_expression_graph(&self) -> ExpressionGraph {
        let mut b = ExprGraphBuilder::new();
        process_reaction_system_tree(&mut b, self, DEFAULT_SYSTEM);
        b.finish()
    }
}

impl ExpressionGraphInput for crate::Equation {
    fn build_expression_graph(&self) -> ExpressionGraph {
        // Delegate to the same per-equation extractor used by `process_model`
        // so a standalone equation and a model equation share one
        // `equation_index` policy. A standalone equation has no equation list,
        // hence index 0.
        let mut b = ExprGraphBuilder::new();
        process_equation(&mut b, self, 0, DEFAULT_SYSTEM);
        b.finish()
    }
}

impl ExpressionGraphInput for crate::Reaction {
    fn build_expression_graph(&self) -> ExpressionGraph {
        // Delegate to the same per-reaction extractor used by
        // `process_reaction_system` so a standalone reaction and a reaction in
        // a system share one variable classification (rate variables →
        // parameters) and one `equation_index` policy.
        let mut b = ExprGraphBuilder::new();
        process_reaction(&mut b, self, 0, DEFAULT_SYSTEM);
        b.finish()
    }
}

impl ExpressionGraphInput for crate::Expr {
    fn build_expression_graph(&self) -> ExpressionGraph {
        // esm-libraries-spec §4.8.2: for a bare expression "every variable in
        // the expression becomes a node, and the tree structure is flattened
        // into dependency edges" — so the expression's VALUE is a synthetic
        // observed node every free variable feeds.
        let mut b = ExprGraphBuilder::new();
        // NON_EQUATION_INDEX: a bare expression has no positional equation to
        // index, which is exactly what the sentinel is for. (The Equation and
        // Reaction overloads DO number their single target 0.)
        process_expression(
            &mut b,
            self,
            "expr_result",
            NON_EQUATION_INDEX,
            DEFAULT_SYSTEM,
        );
        b.finish()
    }
}

/// Is this `subsystems` entry an unresolved include stub (`{"ref": …}`) rather
/// than an inline component? A stub's contents are resolved elsewhere, so the
/// graph treats it as an opaque leaf and contributes nothing for it.
fn is_reference_stub(entry: &serde_json::Value) -> bool {
    entry.get("ref").is_some()
}

/// Deserialize a `subsystems` entry as a [`crate::Model`], supplying the
/// defaults a partial component omits (`variables` / `equations`) so a
/// subsystem that declares only one of them still contributes its half.
fn as_model(entry: &serde_json::Value) -> Option<crate::Model> {
    let mut value = entry.clone();
    let object = value.as_object_mut()?;
    object
        .entry("variables")
        .or_insert_with(|| serde_json::json!({}));
    object
        .entry("equations")
        .or_insert_with(|| serde_json::json!([]));
    serde_json::from_value(value).ok()
}

/// Deserialize a `subsystems` entry as a [`crate::ReactionSystem`], supplying
/// the defaults a partial component omits.
fn as_reaction_system(entry: &serde_json::Value) -> Option<crate::ReactionSystem> {
    let mut value = entry.clone();
    let object = value.as_object_mut()?;
    object
        .entry("species")
        .or_insert_with(|| serde_json::json!({}));
    object
        .entry("parameters")
        .or_insert_with(|| serde_json::json!({}));
    object
        .entry("reactions")
        .or_insert_with(|| serde_json::json!([]));
    serde_json::from_value(value).ok()
}

/// The scoped name of a child component of `system_id`. A `default` parent —
/// only reachable when a bare `Model`/`ReactionSystem` is handed straight to
/// [`expression_graph`] — yields a bare child name.
fn child_scope(system_id: &str, child_name: &str) -> String {
    if system_id == DEFAULT_SYSTEM {
        child_name.to_string()
    } else {
        format!("{system_id}.{child_name}")
    }
}

/// Add a model's own variables and equations, then recurse into its inline
/// `subsystems` (esm-libraries-spec §4.8.2). Reference stubs are skipped.
fn process_model_tree(b: &mut ExprGraphBuilder, model: &crate::Model, system_id: &str) {
    process_model(b, model, system_id);

    let Some(ref subsystems) = model.subsystems else {
        return;
    };
    for child_name in sorted_keys(subsystems) {
        let entry = &subsystems[child_name];
        if is_reference_stub(entry) {
            continue;
        }
        if let Some(child) = as_model(entry) {
            process_model_tree(b, &child, &child_scope(system_id, child_name));
        }
    }
}

/// Add a reaction system's own body, then recurse into its inline
/// `subsystems`. Reference stubs are skipped.
fn process_reaction_system_tree(
    b: &mut ExprGraphBuilder,
    rs: &crate::ReactionSystem,
    system_id: &str,
) {
    process_reaction_system(b, rs, system_id);

    let Some(ref subsystems) = rs.subsystems else {
        return;
    };
    for child_name in sorted_keys(subsystems) {
        let entry = &subsystems[child_name];
        if is_reference_stub(entry) {
            continue;
        }
        if let Some(child) = as_reaction_system(entry) {
            process_reaction_system_tree(b, &child, &child_scope(system_id, child_name));
        }
    }
}

/// Add a model's declared variables (with their DERIVED kinds) and the
/// dependency edges of its equations.
fn process_model(b: &mut ExprGraphBuilder, model: &crate::Model, system_id: &str) {
    // The node kind is DERIVED (esm-spec §6.3.1), never read off
    // `variable.type`: the format declares only `unknown` and `parameter`, so
    // classifying here is the only way the graph can distinguish a state from
    // an observed, or a Brownian parameter from a constant.
    let class = crate::classification::Classification::of(model);
    for var_name in sorted_keys(&model.variables) {
        let kind = variable_kind(&class, var_name);
        b.add_node(
            var_name,
            kind,
            model.variables[var_name].units.clone(),
            system_id,
        );
    }

    for (eq_idx, equation) in model.equations.iter().enumerate() {
        process_equation(b, equation, eq_idx as i64, system_id);
    }
}

/// Add a reaction system's species, declared parameters, reactions, and
/// constraint equations.
fn process_reaction_system(b: &mut ExprGraphBuilder, rs: &crate::ReactionSystem, system_id: &str) {
    for species_name in sorted_keys(&rs.species) {
        b.add_node(
            species_name,
            VariableKind::Species,
            rs.species[species_name].units.clone(),
            system_id,
        );
    }

    // Declared parameters are nodes in their own right, so a rate constant
    // keeps the units it was declared with instead of being fabricated
    // unit-less by the reaction that mentions it.
    for param_name in sorted_keys(&rs.parameters) {
        b.add_node(
            param_name,
            VariableKind::Parameter,
            rs.parameters[param_name].units.clone(),
            system_id,
        );
    }

    for (rxn_idx, reaction) in rs.reactions.iter().enumerate() {
        process_reaction(b, reaction, rxn_idx as i64, system_id);
    }

    // Constraint equations are numbered AFTER the reactions.
    if let Some(ref constraints) = rs.constraint_equations {
        for (idx, equation) in constraints.iter().enumerate() {
            process_equation(b, equation, (idx + rs.reactions.len()) as i64, system_id);
        }
    }
}

/// The single variable an equation LHS defines: a bare name, or the name under
/// the derivative / element-index / aggregate-output wrappers (`D(x)`,
/// `index(v, i)`, `aggregate(…, expr: D(index(v, i)))`).
///
/// Deliberately NOT [`crate::classification::lhs_form`]: that helper answers a
/// different question (which §6.3.1 CATEGORY the LHS puts the unknown in) and
/// so refuses a SPATIAL derivative and accepts `faq`/`broadcast` shells.
/// The graph only wants to know WHICH quantity is written, whatever kind of
/// derivative writes it.
fn lhs_target_name(lhs: &crate::Expr) -> Option<String> {
    match lhs {
        crate::Expr::Variable(name) => Some(name.clone()),
        crate::Expr::Operator(node) => match node.op.as_str() {
            "D" | "index" => node.args.first().and_then(lhs_target_name),
            "faq" => node.expr.as_deref().and_then(lhs_target_name),
            _ => None,
        },
        crate::Expr::Number(_) | crate::Expr::Integer(_) => None,
    }
}

/// Add the nodes and edges contributed by a single equation: one edge from
/// every free variable of the RHS to the variable the LHS defines (including
/// self-references such as `D(x)/dt = -x`).
///
/// An LHS that names no single variable — an implicit constraint like
/// `f(x, y) ~ 0` — defines nothing and contributes no edge.
fn process_equation(
    b: &mut ExprGraphBuilder,
    equation: &crate::Equation,
    eq_idx: i64,
    system_id: &str,
) {
    let Some(target_name) = lhs_target_name(&equation.lhs) else {
        return;
    };
    let lhs_var = b.add_node(&target_name, VariableKind::State, None, system_id);

    for rhs_var in extract_variables_from_expr(&equation.rhs) {
        let source = b.add_node(&rhs_var, VariableKind::Parameter, None, system_id);
        b.add_dependency(
            source,
            lhs_var.clone(),
            DependencyRelationship::Additive,
            eq_idx,
            Some(equation.rhs.clone()),
        );
    }
}

/// Add the nodes and edges contributed by a single reaction: a `rate` edge
/// from every rate variable to every substrate and product, and a
/// `stoichiometric` edge from every substrate to every product.
fn process_reaction(
    b: &mut ExprGraphBuilder,
    reaction: &crate::Reaction,
    rxn_idx: i64,
    system_id: &str,
) {
    let rate_vars = extract_variables_from_expr(&reaction.rate);

    // Substrates are consumed.
    for substrate in reaction.substrates.iter().flatten() {
        let substrate_var = b.add_node(&substrate.species, VariableKind::Species, None, system_id);
        for rate_var in &rate_vars {
            let param = b.add_node(rate_var, VariableKind::Parameter, None, system_id);
            b.add_dependency(
                param,
                substrate_var.clone(),
                DependencyRelationship::Rate,
                rxn_idx,
                Some(reaction.rate.clone()),
            );
        }
    }

    // Products are produced.
    for product in reaction.products.iter().flatten() {
        let product_var = b.add_node(&product.species, VariableKind::Species, None, system_id);
        for rate_var in &rate_vars {
            let param = b.add_node(rate_var, VariableKind::Parameter, None, system_id);
            b.add_dependency(
                param,
                product_var.clone(),
                DependencyRelationship::Rate,
                rxn_idx,
                Some(reaction.rate.clone()),
            );
        }
        for substrate in reaction.substrates.iter().flatten() {
            let substrate_var =
                b.add_node(&substrate.species, VariableKind::Species, None, system_id);
            b.add_dependency(
                substrate_var,
                product_var.clone(),
                DependencyRelationship::Stoichiometric,
                rxn_idx,
                Some(reaction.rate.clone()),
            );
        }
    }
}

/// Add one expression's free-variable → result dependency edges.
fn process_expression(
    b: &mut ExprGraphBuilder,
    expr: &crate::Expr,
    target_var: &str,
    eq_idx: i64,
    system_id: &str,
) {
    let target = b.add_node(target_var, VariableKind::Observed, None, system_id);
    for free_var in extract_variables_from_expr(expr) {
        let source = b.add_node(&free_var, VariableKind::Parameter, None, system_id);
        b.add_dependency(
            source,
            target.clone(),
            DependencyRelationship::Multiplicative,
            eq_idx,
            Some(expr.clone()),
        );
    }
}

/// Fold `variable_map` coupling entries into cross-system dependency edges
/// (esm-libraries-spec §4.8.2). Both endpoints must be scoped; either is added
/// as a `parameter` node if the components' own bodies did not already declare
/// it.
fn process_coupling(b: &mut ExprGraphBuilder, coupling: &[CouplingEntry]) {
    for entry in coupling {
        let CouplingEntry::VariableMap { from, to, .. } = entry else {
            continue;
        };
        let (Some((from_system, from_var)), Some((to_system, to_var))) =
            (from.split_once('.'), to.split_once('.'))
        else {
            continue;
        };

        let source = b.add_node(from_var, VariableKind::Parameter, None, from_system);
        let target = b.add_node(to_var, VariableKind::Parameter, None, to_system);
        b.add_dependency(
            source,
            target,
            DependencyRelationship::Multiplicative,
            NON_EQUATION_INDEX,
            Some(crate::Expr::Variable(from.clone())),
        );
    }
}

/// Index symbols a node BINDS for its own body: a `faq`'s
/// `ranges` keys and `output_idx` entries, and an `integral`'s `var`.
///
/// Narrower than `structural::bound_index_symbols`, which also treats every bare
/// name in an `index(A, i, j)` position as bound. Those positions are exactly
/// where an aggregate's binders appear, and subtracting them THERE rather than
/// at the binding node would hide a real reference to a declared variable used
/// as an index. The binder itself is caught at its `faq`.
fn graph_bound_index_symbols(node: &crate::types::ExpressionNode) -> Vec<String> {
    let mut bound = Vec::new();
    if let Some(ranges) = &node.ranges {
        bound.extend(ranges.keys().cloned());
    }
    if let Some(idx) = &node.output_idx {
        bound.extend(idx.iter().cloned());
    }
    if let Some(v) = &node.int_var {
        bound.push(v.clone());
    }
    bound
}

/// Accumulate `expr`'s variable references into `out`, subtracting each node's
/// own binders at that node.
fn collect_graph_variables(expr: &crate::Expr, out: &mut std::collections::HashSet<String>) {
    match expr {
        crate::Expr::Variable(name) => {
            out.insert(name.clone());
        }
        crate::Expr::Operator(node) => {
            // Collect this node's subtree into a LOCAL set, subtract the symbols
            // this node binds, and only then promote what is left to the caller.
            let mut local = std::collections::HashSet::new();
            node.for_each_child(&mut |child| collect_graph_variables(child, &mut local));
            for symbol in graph_bound_index_symbols(node) {
                local.remove(&symbol);
            }
            out.extend(local);
        }
        crate::Expr::Number(_) | crate::Expr::Integer(_) => {}
    }
}

/// Extract the variable names an expression REFERENCES, with every locally-bound
/// index symbol removed, sorted and deduplicated for deterministic node/edge
/// ordering — the node set §4.8.2 asks for.
///
/// Walks the full canonical child set
/// ([`crate::types::ExpressionNode::for_each_child`]) so variables inside
/// aggregate bodies, `filter` predicates, integral bounds, makearray `values`,
/// and `table_lookup` axes all contribute graph edges.
///
/// Deliberately NOT [`crate::expression::collect_variables`]. That collector
/// reports every bare name it reaches, so a `faq`'s own range binders
/// (`sum over a of src[a]`) came back looking like model variables and became
/// graph nodes with no declaration, no units and no kind. A binder is introduced
/// by the aggregate's own `ranges` clause and is scoped to it; it is not a
/// variable of the system, so it is not a node. The subtraction is PER NODE, at
/// the binder that introduces the symbol, so a name bound inside one reduction
/// and free outside it is still reported.
///
/// `collect_variables` itself is unchanged: it backs the public `free_variables`
/// and is shared with unit conversion, where "every name the subtree mentions"
/// is the wanted answer.
fn extract_variables_from_expr(expr: &crate::Expr) -> Vec<String> {
    let mut set = std::collections::HashSet::new();
    collect_graph_variables(expr, &mut set);
    let mut vars: Vec<String> = set.into_iter().collect();
    vars.sort();
    vars
}

/// Escape a string for use inside a DOT double-quoted id/label.
///
/// DOT quoted strings tolerate spaces, dots, and parens verbatim; only
/// backslashes and double quotes must be escaped. Ids/labels are always emitted
/// double-quoted by the callers, so simple ids remain unchanged.
fn escape_dot(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

/// Render a mermaid label, quoting it only when it contains characters that
/// would break unquoted mermaid text (double quotes, the shape delimiters
/// `()[]{}`, angle brackets, or the edge-label pipe).
///
/// Simple identifiers and plain names with spaces (e.g. `Test Model`) are
/// emitted verbatim so existing simple output — and the tests that assert it —
/// is unchanged; only labels with structural characters are wrapped in quotes,
/// with embedded double quotes replaced by the mermaid `#quot;` entity. (Node
/// ids themselves are emitted as-is: mermaid ids cannot be quoted, so ids with
/// structural characters remain a rendering limitation.)
fn mermaid_label(s: &str) -> String {
    if s.contains(['"', '(', ')', '[', ']', '{', '}', '<', '>', '|']) {
        format!("\"{}\"", s.replace('"', "#quot;"))
    } else {
        s.to_string()
    }
}

impl ComponentGraph {
    /// Is `id` a registered node of this graph?
    fn has_node(&self, id: &str) -> bool {
        self.nodes.iter().any(|n| n.id == id)
    }

    /// Iterate this graph's edges as `(source, target)` id pairs.
    fn endpoints(&self) -> impl Iterator<Item = (&str, &str)> {
        self.edges.iter().map(|e| (e.from.as_str(), e.to.as_str()))
    }

    /// The UNDIRECTED neighbourhood of `id` — its predecessors together with
    /// its successors (esm-libraries-spec §4.8.3), sorted. An unknown id
    /// resolves to `[]`.
    pub fn adjacency(&self, id: &str) -> Vec<String> {
        neighbours(self.has_node(id), self.endpoints(), id, Direction::Both)
    }

    /// The nodes with an edge pointing AT `id`, sorted.
    pub fn predecessors(&self, id: &str) -> Vec<String> {
        neighbours(self.has_node(id), self.endpoints(), id, Direction::Incoming)
    }

    /// The nodes `id` points at, sorted.
    pub fn successors(&self, id: &str) -> Vec<String> {
        neighbours(self.has_node(id), self.endpoints(), id, Direction::Outgoing)
    }

    /// Export graph to DOT format for Graphviz
    ///
    /// # Returns
    ///
    /// * `String` - DOT representation of the graph
    pub fn to_dot(&self) -> String {
        let mut dot = String::from("digraph ComponentGraph {\n");
        dot.push_str("  rankdir=LR;\n");
        dot.push_str("  node [shape=box];\n\n");

        // Add nodes
        for node in &self.nodes {
            let shape = match node.component_type {
                ComponentType::Model => "ellipse",
                ComponentType::ReactionSystem => "box",
            };

            let label = node.name.as_ref().unwrap_or(&node.id);
            dot.push_str(&format!(
                "  \"{}\" [label=\"{}\" shape={}];\n",
                escape_dot(&node.id),
                escape_dot(label),
                shape
            ));
        }

        dot.push('\n');

        // Add edges
        for edge in &self.edges {
            dot.push_str(&format!(
                "  \"{}\" -> \"{}\" [label=\"{}\"];\n",
                escape_dot(&edge.from),
                escape_dot(&edge.to),
                escape_dot(&edge.coupling_type.to_string())
            ));
        }

        dot.push_str("}\n");
        dot
    }

    /// Export graph to Mermaid format
    ///
    /// # Returns
    ///
    /// * `String` - Mermaid representation of the graph
    pub fn to_mermaid(&self) -> String {
        // `graph TD`, not `graph LR`. §4.8.3 requires a Mermaid export and
        // specifies no syntax for it, so the cross-binding tie-break is the
        // majority, applied to the keyword and the direction independently:
        // `graph` beats `flowchart` 4-1 (this binding, Python, Go and Julia
        // against TypeScript) and `TD` beats `LR` 3-2 (TypeScript, Python and
        // Julia against Go and this binding). The EXPRESSION graph below
        // already wrote `graph TD`. tests/conformance/graph/cases.json pins it.
        let mut mermaid = String::from("graph TD\n");

        // Add nodes with types
        for node in &self.nodes {
            let shape = match node.component_type {
                ComponentType::Model => ("(", ")"),
                ComponentType::ReactionSystem => ("[", "]"),
            };

            let label = node.name.as_ref().unwrap_or(&node.id);
            mermaid.push_str(&format!(
                "  {}{}{}{}\n",
                node.id,
                shape.0,
                mermaid_label(label),
                shape.1
            ));
        }

        // Add edges
        for edge in &self.edges {
            mermaid.push_str(&format!(
                "  {} -->|{}| {}\n",
                edge.from,
                mermaid_label(&edge.coupling_type.to_string()),
                edge.to
            ));
        }

        mermaid
    }

    /// Export graph as the JSON adjacency list of esm-libraries-spec §4.8.3.
    ///
    /// # Returns
    ///
    /// * `String` - `{"nodes": […], "edges": […], "adjacency": {…}}`
    pub fn to_json_graph(&self) -> String {
        render_json_graph(
            &self.nodes,
            |node| node.id.clone(),
            &self.edges,
            |edge| (edge.from.clone(), edge.to.clone()),
            |id| self.adjacency(id),
        )
    }
}

impl ExpressionGraph {
    /// Is `name` a registered node of this graph?
    fn has_node(&self, name: &str) -> bool {
        self.nodes.iter().any(|n| n.name == name)
    }

    /// Iterate this graph's edges as `(source, target)` name pairs.
    fn endpoints(&self) -> impl Iterator<Item = (&str, &str)> {
        self.edges
            .iter()
            .map(|e| (e.source.as_str(), e.target.as_str()))
    }

    /// The UNDIRECTED neighbourhood of `name` — its predecessors together with
    /// its successors (esm-libraries-spec §4.8.3), sorted. An unknown name
    /// resolves to `[]`.
    pub fn adjacency(&self, name: &str) -> Vec<String> {
        neighbours(self.has_node(name), self.endpoints(), name, Direction::Both)
    }

    /// The variables an edge points FROM into `name`, sorted.
    pub fn predecessors(&self, name: &str) -> Vec<String> {
        neighbours(
            self.has_node(name),
            self.endpoints(),
            name,
            Direction::Incoming,
        )
    }

    /// The variables `name` points at, sorted.
    pub fn successors(&self, name: &str) -> Vec<String> {
        neighbours(
            self.has_node(name),
            self.endpoints(),
            name,
            Direction::Outgoing,
        )
    }

    /// Export graph to DOT format for Graphviz
    ///
    /// # Returns
    ///
    /// * `String` - DOT representation of the expression graph
    pub fn to_dot(&self) -> String {
        let mut dot = String::from("digraph ExpressionGraph {\n");
        dot.push_str("  rankdir=TB;\n");
        dot.push_str("  node [shape=ellipse];\n\n");

        // Add nodes (all variables). An `algebraic` unknown renders like a
        // state: it is solved for, and it was classified `state` before the
        // kind vocabulary gained its own arm.
        for node in &self.nodes {
            let shape = match node.kind {
                VariableKind::State | VariableKind::Algebraic => "ellipse",
                VariableKind::Parameter => "box",
                VariableKind::Observed => "diamond",
                VariableKind::Brownian => "doubleoctagon",
                VariableKind::Discrete => "hexagon",
                VariableKind::Species => "circle",
            };

            dot.push_str(&format!(
                "  \"{}\" [label=\"{}\" shape={}];\n",
                escape_dot(&node.name),
                escape_dot(&node.name),
                shape
            ));
        }

        dot.push('\n');

        // Add edges
        for edge in &self.edges {
            let label = match edge.relationship {
                DependencyRelationship::Additive => "additive",
                DependencyRelationship::Multiplicative => "mult",
                DependencyRelationship::Rate => "rate",
                DependencyRelationship::Stoichiometric => "stoich",
            };
            dot.push_str(&format!(
                "  \"{}\" -> \"{}\" [label=\"{}\"];\n",
                escape_dot(&edge.source),
                escape_dot(&edge.target),
                label
            ));
        }

        dot.push_str("}\n");
        dot
    }

    /// Export graph to Mermaid format
    ///
    /// # Returns
    ///
    /// * `String` - Mermaid representation of the expression graph
    pub fn to_mermaid(&self) -> String {
        let mut mermaid = String::from("graph TD\n");

        // Add nodes with appropriate shapes
        for node in &self.nodes {
            let (shape_start, shape_end) = match node.kind {
                VariableKind::State | VariableKind::Algebraic => ("(", ")"),
                VariableKind::Parameter => ("[", "]"),
                VariableKind::Observed => ("{", "}"),
                VariableKind::Brownian => ("{{", "}}"),
                VariableKind::Discrete => ("[/", "/]"),
                VariableKind::Species => ("((", "))"),
            };

            mermaid.push_str(&format!(
                "  {}{}{}{}\n",
                node.name,
                shape_start,
                mermaid_label(&node.name),
                shape_end
            ));
        }

        // Add edges
        for edge in &self.edges {
            mermaid.push_str(&format!("  {} --> {}\n", edge.source, edge.target));
        }

        mermaid
    }

    /// Export graph as the JSON adjacency list of esm-libraries-spec §4.8.3.
    ///
    /// # Returns
    ///
    /// * `String` - `{"nodes": […], "edges": […], "adjacency": {…}}`
    pub fn to_json_graph(&self) -> String {
        render_json_graph(
            &self.nodes,
            |node| node.name.clone(),
            &self.edges,
            |edge| (edge.source.clone(), edge.target.clone()),
            |name| self.adjacency(name),
        )
    }
}

/// The graph kinds the esm-libraries-spec §4.8.3 text exporters render.
///
/// API_SPEC.md §8 item 8 rules the canonical renderer trio to be
/// [`to_dot`] / [`to_mermaid`] / [`to_json_graph`], one free function each,
/// dispatching on the graph kind — the spelling TypeScript, Python and Julia
/// already share. This trait is that dispatch: it is implemented by
/// [`ComponentGraph`] and [`ExpressionGraph`] and by nothing else, and each
/// method forwards to the graph's own inherent renderer, so the rendered
/// bytes are unchanged (they are pinned by `tests/conformance/graph`).
///
/// It is deliberately NOT re-exported from the crate root: §8 item 8 adds
/// three functions to the surface, not a fourth name.
pub trait Graph {
    /// This graph rendered as Graphviz DOT.
    fn render_dot(&self) -> String;
    /// This graph rendered as Mermaid.
    fn render_mermaid(&self) -> String;
    /// This graph rendered as a JSON adjacency-list document.
    fn render_json_graph(&self) -> String;
}

impl Graph for ComponentGraph {
    fn render_dot(&self) -> String {
        ComponentGraph::to_dot(self)
    }
    fn render_mermaid(&self) -> String {
        ComponentGraph::to_mermaid(self)
    }
    fn render_json_graph(&self) -> String {
        ComponentGraph::to_json_graph(self)
    }
}

impl Graph for ExpressionGraph {
    fn render_dot(&self) -> String {
        ExpressionGraph::to_dot(self)
    }
    fn render_mermaid(&self) -> String {
        ExpressionGraph::to_mermaid(self)
    }
    fn render_json_graph(&self) -> String {
        ExpressionGraph::to_json_graph(self)
    }
}

/// Render `graph` as Graphviz DOT (esm-libraries-spec §4.8.3).
///
/// The canonical free-function spelling (API_SPEC.md §8 item 8). Equivalent to
/// the graph's own `to_dot` method; the byte-level output is pinned by
/// `tests/conformance/graph/cases.json`.
pub fn to_dot<G: Graph>(graph: &G) -> String {
    graph.render_dot()
}

/// Render `graph` as Mermaid (esm-libraries-spec §4.8.3). See [`to_dot`].
pub fn to_mermaid<G: Graph>(graph: &G) -> String {
    graph.render_mermaid()
}

/// Render `graph` as a JSON adjacency-list document (esm-libraries-spec
/// §4.8.3). Named `to_json_graph`, not `to_json`, because `to_json` is the
/// DOCUMENT serializer (API_SPEC.md §8 item 2). See [`to_dot`].
pub fn to_json_graph<G: Graph>(graph: &G) -> String {
    graph.render_json_graph()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::test_file;
    use crate::{Expr, ExpressionNode as ExprNode, Model, ReactionSystem};
    use indexmap::IndexMap;

    /// An empty model carrying only a display name.
    fn test_model(name: &str) -> Model {
        Model {
            name: Some(name.to_string()),
            ..Default::default()
        }
    }

    #[test]
    fn test_component_graph_empty() {
        let esm_file = test_file();

        let graph = component_graph(&esm_file);
        assert_eq!(graph.nodes.len(), 0);
        assert_eq!(graph.edges.len(), 0);
    }

    #[test]
    fn test_component_graph_with_models() {
        let mut models = IndexMap::new();
        models.insert("model1".to_string(), test_model("Test Model 1"));
        models.insert("model2".to_string(), test_model("Test Model 2"));

        let esm_file = EsmFile {
            models: Some(models),
            ..test_file()
        };

        let graph = component_graph(&esm_file);
        assert_eq!(graph.nodes.len(), 2);

        let node1 = graph.nodes.iter().find(|n| n.id == "model1").unwrap();
        assert_eq!(node1.component_type, ComponentType::Model);
        assert_eq!(node1.name, Some("Test Model 1".to_string()));

        let node2 = graph.nodes.iter().find(|n| n.id == "model2").unwrap();
        assert_eq!(node2.component_type, ComponentType::Model);
        assert_eq!(node2.name, Some("Test Model 2".to_string()));
    }

    #[test]
    fn test_component_exists() {
        let mut models = IndexMap::new();
        models.insert("test_model".to_string(), test_model("Test Model"));

        let esm_file = EsmFile {
            models: Some(models),
            ..test_file()
        };

        assert!(component_exists(&esm_file, "test_model"));
        assert!(!component_exists(&esm_file, "nonexistent"));
    }

    #[test]
    fn test_get_component_type() {
        let mut models = IndexMap::new();
        models.insert("test_model".to_string(), test_model("Test Model"));

        let mut reaction_systems = IndexMap::new();
        reaction_systems.insert("test_rs".to_string(), ReactionSystem::default());

        let esm_file = EsmFile {
            models: Some(models),
            reaction_systems: Some(reaction_systems),
            ..test_file()
        };

        assert_eq!(
            get_component_type(&esm_file, "test_model"),
            Some(ComponentType::Model)
        );
        assert_eq!(
            get_component_type(&esm_file, "test_rs"),
            Some(ComponentType::ReactionSystem)
        );
        assert_eq!(get_component_type(&esm_file, "nonexistent"), None);
    }

    #[test]
    fn test_expression_graph() {
        let expr = Expr::operator(ExprNode {
            op: "+".to_string(),
            args: vec![Expr::Variable("x".to_string()), Expr::Number(1.0)],
            wrt: None,
            dim: None,
            ..Default::default()
        });

        let graph = expression_graph(&expr);
        // Variable dependency graph: only variables as nodes, no operators or
        // constants — plus the synthetic node standing for the expression's own
        // value (esm-libraries-spec §4.8.2), which every free variable feeds.
        assert_eq!(graph.nodes.len(), 2);
        assert_eq!(graph.edges.len(), 1);

        let result = graph
            .nodes
            .iter()
            .find(|n| n.name == "expr_result")
            .expect("synthetic result node");
        assert_eq!(result.kind, VariableKind::Observed);
        assert_eq!(result.system, "default");

        let x = graph
            .nodes
            .iter()
            .find(|n| n.name == "x")
            .expect("free variable node");
        assert_eq!(x.kind, VariableKind::Parameter);

        assert_eq!(graph.edges[0].source, "x");
        assert_eq!(graph.edges[0].target, "expr_result");
        assert_eq!(
            graph.edges[0].relationship,
            DependencyRelationship::Multiplicative
        );
        // A bare expression has no positional equation to index, so its
        // `expr_result` edges carry NON_EQUATION_INDEX.
        assert_eq!(graph.edges[0].equation_index, Some(NON_EQUATION_INDEX));
    }

    #[test]
    fn test_component_graph_to_dot() {
        let graph = ComponentGraph {
            nodes: vec![ComponentNode {
                id: "model1".to_string(),
                component_type: ComponentType::Model,
                name: Some("Test Model".to_string()),
                metadata: ComponentMetadata::default(),
            }],
            edges: vec![],
        };

        let dot = graph.to_dot();
        assert!(dot.contains("digraph ComponentGraph"));
        assert!(dot.contains("model1"));
        assert!(dot.contains("Test Model"));
    }

    #[test]
    fn test_component_graph_to_mermaid() {
        let graph = ComponentGraph {
            nodes: vec![ComponentNode {
                id: "model1".to_string(),
                component_type: ComponentType::Model,
                name: Some("Test Model".to_string()),
                metadata: ComponentMetadata::default(),
            }],
            edges: vec![],
        };

        let mermaid = graph.to_mermaid();
        assert!(mermaid.contains("graph TD"));
        assert!(mermaid.contains("model1(Test Model)"));
    }

    #[test]
    fn test_expression_graph_to_mermaid() {
        let expr = Expr::operator(ExprNode {
            op: "+".to_string(),
            args: vec![Expr::Variable("x".to_string()), Expr::Number(1.0)],
            wrt: None,
            dim: None,
            ..Default::default()
        });

        let graph = expression_graph(&expr);
        let mermaid = graph.to_mermaid();

        assert!(mermaid.contains("graph TD"));
        assert!(mermaid.contains("x[x]")); // Parameter variable node (square brackets)
        // No constants or operators in variable dependency graph
        assert!(!mermaid.contains("const_")); // No constant nodes
        assert!(!mermaid.contains("{+}")); // No operator nodes
        // The free variable feeds the expression's synthetic result node.
        assert!(mermaid.contains("expr_result{expr_result}"));
        assert!(mermaid.contains("x --> expr_result"));
    }

    #[test]
    fn test_component_graph_variable_map_edge_extraction() {
        let mut models = IndexMap::new();
        models.insert("source".to_string(), test_model("Source System"));
        models.insert("target".to_string(), test_model("Target System"));

        let coupling_entries = vec![crate::CouplingEntry::VariableMap {
            from: "source.var".to_string(),
            to: "target.param".to_string(),
            transform: crate::types::VariableMapTransform::Named("identity".to_string()),
            factor: None,
            lifting: None,
            description: None,
        }];

        let esm_file = EsmFile {
            models: Some(models),
            coupling: Some(coupling_entries),
            ..test_file()
        };

        let graph = component_graph(&esm_file);

        // Should have 2 nodes (source and target systems)
        assert_eq!(graph.nodes.len(), 2);

        // Should have 1 edge for the variable mapping
        assert_eq!(graph.edges.len(), 1);

        let edge = &graph.edges[0];

        // Edge should connect system names, not full scoped references
        assert_eq!(edge.from, "source"); // Not "source.var"
        assert_eq!(edge.to, "target"); // Not "target.param"
        assert_eq!(edge.coupling_type, CouplingEdgeKind::VariableMap);
        // The label is everything after the FIRST dot of `from`.
        assert_eq!(edge.label, "var");
    }

    /// A `variable_map` whose endpoints are not SCOPED names the no component,
    /// so it anchors no edge (esm-libraries-spec §4.8.1).
    #[test]
    fn test_component_graph_variable_map_requires_scoped_endpoints() {
        let mut models = IndexMap::new();
        for id in ["source", "target"] {
            models.insert(id.to_string(), test_model(id));
        }

        let esm_file = EsmFile {
            coupling: Some(vec![crate::CouplingEntry::VariableMap {
                from: "source".to_string(),
                to: "target".to_string(),
                transform: crate::types::VariableMapTransform::Named("identity".to_string()),
                factor: None,
                lifting: None,
                description: None,
            }]),
            models: Some(models),
            ..test_file()
        };

        let graph = component_graph(&esm_file);
        assert_eq!(graph.nodes.len(), 2);
        assert!(graph.edges.is_empty());
    }

    /// esm-libraries-spec §4.8.1: "A `data_sources` entry is not a component
    /// and is NOT a node."
    #[test]
    fn test_data_sources_contribute_no_nodes() {
        let json = r#"{
            "esm": "1.0.0",
            "metadata": { "name": "ds" },
            "data_sources": {
                "GEOSFP": {
                    "kind": "grid",
                    "source": { "url_template": "file:///data/GEOSFP/{date:%Y%m%d_%H%M}.nc" }
                }
            }
        }"#;
        let esm_file: EsmFile = serde_json::from_str(json).expect("parses");

        let graph = component_graph(&esm_file);
        assert!(graph.nodes.is_empty());
        assert!(graph.edges.is_empty());
        assert_eq!(get_component_type(&esm_file, "GEOSFP"), None);
        assert!(!component_exists(&esm_file, "GEOSFP"));
    }

    /// The §4.8.3 closure lookups, on a two-node one-edge graph.
    #[test]
    fn test_component_graph_closure() {
        let mut models = IndexMap::new();
        for id in ["source", "target"] {
            models.insert(id.to_string(), test_model(id));
        }

        let esm_file = EsmFile {
            coupling: Some(vec![crate::CouplingEntry::VariableMap {
                from: "source.var".to_string(),
                to: "target.param".to_string(),
                transform: crate::types::VariableMapTransform::Named("identity".to_string()),
                factor: None,
                lifting: None,
                description: None,
            }]),
            models: Some(models),
            ..test_file()
        };

        let graph = component_graph(&esm_file);
        assert_eq!(graph.adjacency("source"), vec!["target".to_string()]);
        assert_eq!(graph.successors("source"), vec!["target".to_string()]);
        assert!(graph.predecessors("source").is_empty());
        assert_eq!(graph.adjacency("target"), vec!["source".to_string()]);
        assert_eq!(graph.predecessors("target"), vec!["source".to_string()]);
        assert!(graph.successors("target").is_empty());
        // An unknown key resolves to [] rather than panicking.
        assert!(graph.adjacency("nonexistent").is_empty());
    }

    /// The §4.8.3 JSON adjacency-list export: three top-level keys, an `id` on
    /// every node, `{source, target, data}` edges, and an adjacency map.
    #[test]
    fn test_to_json_graph_is_an_adjacency_list() {
        let mut models = IndexMap::new();
        for id in ["source", "target"] {
            models.insert(id.to_string(), test_model(id));
        }

        let esm_file = EsmFile {
            coupling: Some(vec![crate::CouplingEntry::VariableMap {
                from: "source.var".to_string(),
                to: "target.param".to_string(),
                transform: crate::types::VariableMapTransform::Named("identity".to_string()),
                factor: None,
                lifting: None,
                description: None,
            }]),
            models: Some(models),
            ..test_file()
        };

        let json: serde_json::Value =
            serde_json::from_str(&component_graph(&esm_file).to_json_graph()).expect("valid JSON");

        let mut keys: Vec<&String> = json.as_object().expect("object").keys().collect();
        keys.sort();
        assert_eq!(keys, vec!["adjacency", "edges", "nodes"]);

        let nodes = json["nodes"].as_array().expect("nodes array");
        assert_eq!(nodes[0]["id"], "source");
        let edges = json["edges"].as_array().expect("edges array");
        assert_eq!(edges[0]["source"], "source");
        assert_eq!(edges[0]["target"], "target");
        assert_eq!(edges[0]["data"]["coupling_type"], "variable_map");
        assert_eq!(json["adjacency"]["source"][0], "target");
        assert_eq!(json["adjacency"]["target"][0], "source");
    }

    /// API_SPEC.md §8 item 8: the canonical free-function trio dispatches on
    /// the graph kind and must render EXACTLY what the inherent methods do —
    /// the output is pinned by `tests/conformance/graph/cases.json`.
    #[test]
    fn canonical_renderers_match_the_inherent_methods() {
        let esm_file = EsmFile {
            models: Some(IndexMap::from([("m".to_string(), test_model("M"))])),
            ..test_file()
        };

        let cg = component_graph(&esm_file);
        assert_eq!(super::to_dot(&cg), cg.to_dot());
        assert_eq!(super::to_mermaid(&cg), cg.to_mermaid());
        assert_eq!(super::to_json_graph(&cg), cg.to_json_graph());

        let eg = expression_graph(&esm_file);
        assert_eq!(super::to_dot(&eg), eg.to_dot());
        assert_eq!(super::to_mermaid(&eg), eg.to_mermaid());
        assert_eq!(super::to_json_graph(&eg), eg.to_json_graph());
    }
}