gsim-py 0.6.1

PyO3 bindings exposing gsim-core to Python: build a schematic from code, validate it and compile it to a netlist.
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
//! PyO3 bindings for `gsim-core`.
//!
//! # Interface design
//!
//! Every function here is **stateless and JSON-in/JSON-out**: it takes Python `str` (JSON text),
//! parses it with `serde_json`, calls straight into `gsim-core`, and returns Python `str` (JSON
//! text) or raises a `ValueError` carrying the real Rust error's `Display` message. There is no
//! stateful Rust object (e.g. `ModelBuilder`) exposed across the FFI boundary — a caller builds a
//! `Model` up incrementally by round-tripping its JSON through successive calls
//! (`new_model` -> `add_block` -> `connect` -> ... -> `save_document`). This matches `gsim-core`'s
//! own internal philosophy of JSON as the interchange format everywhere, avoids needing GC/
//! lifetime integration for a wrapped Rust object living inside Python's object model, and keeps
//! this crate a thin wrapper rather than a second place schema/validation/layout logic could
//! drift. `crates/gsim-wasm` exposes the same JSON contracts to JavaScript.
//!
//! No function here reimplements schema, validation, or layout logic — see `AGENTS.md`'s "one
//! implementation, thin bindings" rule. A couple of small additive helpers were added to
//! `gsim-core` itself to support this thin-wrapper shape without duplicating shape definitions in
//! this crate: `Deserialize` on `document::NewBlockSpec`/`document::ConnectOptions`, `Serialize`
//! on `contract::ValidationFailure`, and `Serialize`/`Deserialize` on `layout::Rect` — see each
//! item's doc comment in `gsim-core` for why.

use gsim_core::compile::{compile as compile_model, CompileError};
use gsim_core::contract::{self, ComponentContract, ContractRegistry};
use gsim_core::document::{
    BuilderError, CompatFailure, ConnectOptions, Endpoint, GsimSchDocument, Model, ModelBuilder,
    NewBlockSpec, NewSubcktInstanceSpec, SubcktDef, SubcktError,
};
use gsim_core::layout::{self, Axis, LayoutInput, Rect};
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::collections::HashMap;

/// Converts any `Display`-able error into a Python `ValueError` carrying its real message —
/// never an opaque panic, and never a generic message that swallows which specific error variant
/// occurred.
fn to_py_err<E: std::fmt::Display>(e: E) -> PyErr {
    PyErr::new::<PyValueError, _>(e.to_string())
}

/// Like [`to_py_err`], but for `BuilderError` specifically: prefixes the real `Display` message
/// with the variant's canonical keyword ("duplicate", "dangling", "cross-paradigm", ...) so a
/// caller can reliably match on *which* case occurred from the message text alone, even though
/// `BuilderError`'s own `Display` impl phrases some variants (`CrossParadigm`, `DanglingWire`)
/// descriptively rather than using that exact word. The full underlying message always follows,
/// unmodified — this never swallows detail, only adds a stable keyword in front of it.
fn builder_err_to_py(e: BuilderError) -> PyErr {
    let keyword = match &e {
        BuilderError::DuplicateId(_) => "duplicate",
        BuilderError::DanglingWire { .. } => "dangling",
        BuilderError::CrossParadigm { .. } => "cross-paradigm",
        // One keyword per `port-compat.ts` reason rather than a single "port-incompatible":
        // the three cases need different fixes (drop a v3-reserved kind / correct the wire kind
        // / remove the second driver), so a caller branching on them is the expected use. Same
        // sub-matching precedent as `Subckt(CyclicDefReference)` below.
        BuilderError::PortIncompatible(inc) => match &inc.failure {
            CompatFailure::ReservedKind { .. } => "port-reserved-kind",
            CompatFailure::KindMismatch { .. } => "port-kind-mismatch",
            CompatFailure::FanInOnSignal { .. } => "port-fan-in-on-signal",
            CompatFailure::DimMismatch { .. } => "port-dim-mismatch",
        },
        BuilderError::UnknownBlock(_) => "unknown-block",
        BuilderError::Block(_) => "invalid-block",
        BuilderError::UnknownSubcktDef(_) => "unknown-subckt-def",
        BuilderError::Subckt(SubcktError::CyclicDefReference { .. }) => "cyclic-subckt-def",
        BuilderError::Subckt(_) => "invalid-subckt",
    };
    PyErr::new::<PyValueError, _>(format!("{keyword}: {e}"))
}

/// Same stable-keyword-prefix idea as [`builder_err_to_py`], for the compiler's errors.
fn compile_err_to_py(e: CompileError) -> PyErr {
    let keyword = match &e {
        CompileError::UnknownType { .. } => "unknown-type",
        CompileError::UnknownTarget(_) => "unknown-target",
        CompileError::FloatingPort { .. } => "floating-port",
        CompileError::UnconnectedRef { .. } => "unconnected-ref",
        CompileError::MissingParam { .. } => "missing-param",
        CompileError::UnknownSubcktDef { .. } => "unknown-subckt-def",
        CompileError::UnconnectedSubcktPort { .. } => "unconnected-subckt-port",
        CompileError::UnknownVariant { .. } => "unknown-variant",
        CompileError::VectorOutputPort { .. } => "vector-output-port",
        CompileError::IndexedRefArity { .. } => "indexed-ref-arity",
        CompileError::UnresolvedFromTag { .. } => "unresolved-from-tag",
        CompileError::AmbiguousFromTag { .. } => "ambiguous-from-tag",
        CompileError::CyclicFromTag { .. } => "cyclic-from-tag",
        CompileError::RoutingKindUnsupported { .. } => "routing-kind-unsupported",
        CompileError::RefNotAnOutput { .. } => "ref-not-an-output",
        CompileError::DuplicateName(_) => "duplicate-name",
        CompileError::DuplicateNet(_) => "duplicate-net",
        CompileError::BadRating { .. } => "bad-rating",
    };
    PyErr::new::<PyValueError, _>(format!("{keyword}: {e}"))
}

fn parse_json<T: for<'de> Deserialize<'de>>(text: &str, what: &str) -> PyResult<T> {
    serde_json::from_str(text).map_err(|e| to_py_err(format!("invalid {what} JSON: {e}")))
}

fn to_json<T: Serialize>(value: &T) -> PyResult<String> {
    serde_json::to_string(value).map_err(to_py_err)
}

#[pyfunction]
fn version() -> &'static str {
    gsim_core::version()
}

/// Parses `contract_json` as a `ComponentContract` and `params_json` as a JSON object of
/// parameter values, evaluates it (GSF v2), and returns the resulting `EvaluatedSymbol`
/// (`{"bbox": [w, h], "ports": [...], "primitives": [...]}`) as JSON.
/// What this engine can compile, as JSON — see `gsim_core::compile::capabilities`.
///
/// The front end renders this instead of keeping its own list of supported types and their
/// parameters. That list used to exist and had drifted to the point where none of the 143
/// catalogue types matched it, so every block reported "not supported by the simulator".
#[pyfunction]
fn capabilities() -> String {
    gsim_core::compile::capabilities::capabilities_json()
}

/// The component library: everything a front end needs to show a palette, plus whether this
/// engine can compile each component.
///
/// The front end used to keep its own catalogue of components beside this -- labels, port
/// geometry, parameter names and defaults -- and the two drifted until a switch's parameters
/// disagreed about whether they were resistances or conductances. There is one description
/// now, and it is this one.
#[pyfunction]
fn catalog() -> String {
    gsim_core::compile::library::catalog_json()
}

#[pyfunction]
fn evaluate_component(contract_json: &str, params_json: &str) -> PyResult<String> {
    let contract: ComponentContract = parse_json(contract_json, "contract")?;
    let params: Map<String, Value> = parse_json(params_json, "params")?;
    let evaluated = contract::evaluate_component(&contract, &params).map_err(to_py_err)?;
    to_json(&evaluated)
}

/// Returns a JSON array of `{"parameter": ..., "message": ...}` failures (empty array `"[]"`
/// means every validated parameter passed). Never raises for validation failures themselves —
/// only for malformed input JSON.
#[pyfunction]
fn validate_parameters(contract_json: &str, params_json: &str) -> PyResult<String> {
    let contract: ComponentContract = parse_json(contract_json, "contract")?;
    let params: Map<String, Value> = parse_json(params_json, "params")?;
    let failures = contract::validate_parameters(&contract, &params);
    to_json(&failures)
}

/// Returns a fresh, empty `Model` as JSON.
#[pyfunction]
fn new_model(id: &str, name: &str, grid: i64) -> PyResult<String> {
    to_json(&Model::new(id, name, grid))
}

#[derive(Serialize)]
struct AddBlockResult {
    model: Model,
    block_id: String,
}

/// `spec_json` matches `NewBlockSpec`'s JSON shape (`type`, `paradigm`, `domain`, `fidelity?`,
/// `position`, `rotation`, `mirror?`, `params?`, `ic?`, `ratings?`, `label?`,
/// `comment_before?`, `comment_after?`, `id?`). `ratings` carries datasheet limits on the
/// component — `{"i_max": 60, "on_violation": "stop"}` — emitted as trailing fields on its
/// device line; they are a sibling of `params` so that changing a component's fidelity tier
/// cannot strip them, and `compile` refuses one the engine would (a current limit on a device
/// with no branch current, a modifier with no limit beside it).
/// `comment_before`/`comment_after` are lists of comment lines (a
/// single string containing newlines is split too) emitted as `*`-prefixed SPICE comment lines
/// immediately above/below this block's card(s) by `compile`. Returns
/// `{"model": <updated Model JSON>, "block_id": "<assigned id>"}`. Raises with the real
/// `BuilderError`/`BlockError` message (duplicate id, invalid id/type pattern, invalid rotation)
/// on failure.
#[pyfunction]
fn add_block(model_json: &str, spec_json: &str) -> PyResult<String> {
    let model: Model = parse_json(model_json, "model")?;
    let spec: NewBlockSpec = parse_json(spec_json, "block spec")?;
    let mut builder = ModelBuilder::from_model(model);
    let block_id = builder.add_block(spec).map_err(builder_err_to_py)?;
    to_json(&AddBlockResult {
        model: builder.into_model(),
        block_id,
    })
}

#[derive(Serialize)]
struct AddSubcktDefResult {
    model: Model,
    def_id: String,
}

/// Adds a reusable SPICE `.SUBCKT` definition to the model.
///
/// **Shared JSON contract** (identical in `gsim-wasm`'s `addSubcktDef`):
/// `def_json` is a `SubcktDef` — `{"id", "name", "ports": [{"id", "kind"}], "params"?,
/// "blocks"?, "wires"?, "instances"? : [{"id", "def_ref", "connections"?, "params"?}]}`.
/// Returns `{"model": <updated Model JSON>, "def_id": "<id>"}`, mirroring `add_block`'s
/// `{"model", "block_id"}` shape. Raises on an invalid id pattern (`invalid-subckt: ...`), an
/// invalid port kind (`invalid-subckt: ...`), a duplicate def id (`duplicate: ...`), or a
/// cyclic `def_ref` graph (`cyclic-subckt-def: Cyclic SubcktDef reference: a -> b -> a`).
#[pyfunction]
fn add_subckt_def(model_json: &str, def_json: &str) -> PyResult<String> {
    let model: Model = parse_json(model_json, "model")?;
    let def: SubcktDef = parse_json(def_json, "subckt def")?;
    let mut builder = ModelBuilder::from_model(model);
    let def_id = builder.add_subckt_def(def).map_err(builder_err_to_py)?;
    to_json(&AddSubcktDefResult {
        model: builder.into_model(),
        def_id,
    })
}

/// Instantiates an existing `SubcktDef` as a top-level `spice-subckt` block.
///
/// **Shared JSON contract** (identical in `gsim-wasm`'s `instantiateSubckt`): `spec_json`
/// matches `NewSubcktInstanceSpec` — `{"def_ref", "position": [x, y], "rotation"?, "domain"?,
/// "fidelity"?, "mirror"?, "params"?, "label"?, "comment_before"?, "comment_after"?, "id"?}`.
/// Returns
/// `{"model": <updated Model JSON>, "block_id": "<assigned id>"}`, the same shape `add_block`
/// returns. The created block's wireable ports are exactly the referenced def's `ports[].id`
/// list — wire them with ordinary `connect` calls. Raises `unknown-subckt-def: ...` if
/// `def_ref` names no def, `duplicate: ...` on a colliding block id.
#[pyfunction]
fn instantiate_subckt(model_json: &str, spec_json: &str) -> PyResult<String> {
    let model: Model = parse_json(model_json, "model")?;
    let spec: NewSubcktInstanceSpec = parse_json(spec_json, "subckt instance spec")?;
    let mut builder = ModelBuilder::from_model(model);
    let block_id = builder
        .instantiate_subckt(spec)
        .map_err(builder_err_to_py)?;
    to_json(&AddBlockResult {
        model: builder.into_model(),
        block_id,
    })
}

#[derive(Serialize)]
struct CompileResult {
    netlist: String,
    notes: Vec<String>,
    /// The document-to-netlist map — see `gsim_core::compile::provenance`. Carried across the
    /// boundary rather than re-derived, because a consumer cannot re-derive it: the device
    /// letter is prefixed onto a block id only when the id does not already start with it, so
    /// `load` and `Rload` both compile to `Rload`.
    provenance: gsim_core::compile::Provenance,
}

/// Compiles a `Model` into netlist text for `target` (currently only `"general-simulator"`).
///
/// **Shared JSON contract** (identical in `gsim-wasm`'s `compile`): returns
/// `{"netlist": "<text>", "notes": ["<info-level compiler decision>", ...], "provenance":
/// {"elements": [{"element": "<netlist name>", "blocks": ["<block id>", ...], "role":
/// "element"|"block"|"element_and_block"|"part"|"instance", "suffix"?, "def"?}, ...],
/// "nets": [{"net": "<node name>", "ports": [{"blocks": [...], "port": "<port id>"}, ...]},
/// ...]}}`. Raises a
/// `ValueError` whose message is keyword-prefixed the same way the builder errors are
/// (`duplicate-name:`, `duplicate-net:`, `unknown-type:`, `unknown-target:`, `floating-port:`, `unconnected-ref:`,
/// `missing-param:`, `unknown-subckt-def:`, `unconnected-subckt-port:`, `unknown-variant:`, `vector-output-port:`,
/// `indexed-ref-arity:`, `unresolved-from-tag:`, `ambiguous-from-tag:`, `cyclic-from-tag:`,
/// `routing-kind-unsupported:`),
/// with the real underlying message following unmodified.
#[pyfunction]
fn compile(model_json: &str, target: &str) -> PyResult<String> {
    let model: Model = parse_json(model_json, "model")?;
    let out = compile_model(&model, target).map_err(compile_err_to_py)?;
    to_json(&CompileResult {
        netlist: out.netlist,
        notes: out.notes,
        provenance: out.provenance,
    })
}

/// Removes a block and cascades to every wire touching it. Returns the updated `Model` JSON.
#[pyfunction]
fn remove_block(model_json: &str, block_id: &str) -> PyResult<String> {
    let model: Model = parse_json(model_json, "model")?;
    let mut builder = ModelBuilder::from_model(model);
    builder.remove_block(block_id);
    to_json(&builder.into_model())
}

/// Sets one parameter on one block. Returns the updated `Model` JSON. Raises if `block_id`
/// doesn't exist.
#[pyfunction]
fn set_param(model_json: &str, block_id: &str, name: &str, value_json: &str) -> PyResult<String> {
    let model: Model = parse_json(model_json, "model")?;
    let value: Value = parse_json(value_json, "value")?;
    let mut builder = ModelBuilder::from_model(model);
    builder
        .set_param(block_id, name, value)
        .map_err(builder_err_to_py)?;
    to_json(&builder.into_model())
}

/// Adds a model-level (schematic-wide) parameter. Returns the updated `Model` JSON. Raises on a
/// duplicate parameter name.
#[pyfunction]
fn add_model_param(model_json: &str, name: &str, value_json: &str) -> PyResult<String> {
    let model: Model = parse_json(model_json, "model")?;
    let value: Value = parse_json(value_json, "value")?;
    let mut builder = ModelBuilder::from_model(model);
    builder
        .add_model_param(name, value)
        .map_err(builder_err_to_py)?;
    to_json(&builder.into_model())
}

#[derive(Serialize)]
struct ConnectResult {
    model: Model,
    wire_id: String,
}

/// `from_json`/`to_json` are `{"block": "...", "port": "..."}` endpoints; `opts_json` matches
/// `ConnectOptions` (`waypoints?`, `net?`, `id?`, `pinned?`, `label?`, all optional -- `"{}"` is a
/// valid payload). Returns `{"model": <updated Model JSON>, "wire_id": "<assigned id>"}`. Raises
/// with the real `BuilderError` message on failure -- the message text always names the specific
/// case ("dangling", "cross-paradigm", "duplicate") rather than a generic "connect failed", since
/// `BuilderError`'s `Display` impl already does this and this wrapper does not paper over it.
///
/// Beyond the block-level cross-paradigm boundary, the per-port §8.1/§8.2 rules in
/// `gsim_core::document::port_compat` also apply, raising with the keyword
/// `port-reserved-kind`, `port-kind-mismatch`, `port-fan-in-on-signal` or `port-dim-mismatch`.
///
/// `contracts_json` is optional and defaults to none. When supplied it is a
/// `{"<block type>": <ComponentContract>, ...}` object -- the same contract shape
/// `evaluate_component` takes, one entry per block `type` used in the model. Supplying it lets
/// the per-port check resolve each endpoint's real `kind` and `dim` from the block's own
/// `params` instead of approximating from the block's `domain`, which is what makes
/// `port-kind-mismatch` exact for ordinary components and makes `port-dim-mismatch` possible at
/// all. **Omitting it changes nothing that used to work**: an unregistered type keeps the
/// coarser `domain`-based check.
///
/// It is passed per call rather than registered once because every function in this module is
/// stateless JSON-in/JSON-out -- there is no session object to hold a registry, and putting one
/// in the `Model` would write a caller's component library into the saved document. A Python
/// caller builds the dict once and passes it to each `connect`.
#[pyfunction]
#[pyo3(signature = (model_json, from_json, to_json_, kind, opts_json, contracts_json=None))]
fn connect(
    model_json: &str,
    from_json: &str,
    to_json_: &str,
    kind: &str,
    opts_json: &str,
    contracts_json: Option<&str>,
) -> PyResult<String> {
    let model: Model = parse_json(model_json, "model")?;
    let from: Endpoint = parse_json(from_json, "from endpoint")?;
    let to: Endpoint = parse_json(to_json_, "to endpoint")?;
    let opts: ConnectOptions = parse_json(opts_json, "connect options")?;
    let contracts: ContractRegistry = match contracts_json {
        Some(text) => parse_json(text, "contract registry")?,
        None => ContractRegistry::new(),
    };
    let mut builder = ModelBuilder::from_model(model).with_contracts(contracts);
    let wire_id = builder
        .connect(from, to, kind, opts)
        .map_err(builder_err_to_py)?
        .to_string();
    to_json(&ConnectResult {
        model: builder.into_model(),
        wire_id,
    })
}

/// `bbox_map_json` is `{"<block_id>": [w, h], ...}` for each block in the model -- the caller is
/// expected to have already evaluated each block's GSF v2 contract to get its bbox (this
/// function does not itself know about contracts, matching `ModelBuilder::auto_arrange`'s
/// decoupled `bbox_of` design). If a block id is missing from the map, `(0, 0)` is used as its
/// size rather than raising. Returns the updated `Model` JSON with positions rewritten.
#[pyfunction]
fn auto_arrange(
    model_json: &str,
    bbox_map_json: &str,
    column_gap: i64,
    row_gap: i64,
) -> PyResult<String> {
    let model: Model = parse_json(model_json, "model")?;
    let bbox_map: HashMap<String, (i64, i64)> = parse_json(bbox_map_json, "bbox map")?;
    let mut builder = ModelBuilder::from_model(model);
    builder.auto_arrange(
        |b| bbox_map.get(&b.id).copied().unwrap_or((0, 0)),
        column_gap,
        row_gap,
    );
    to_json(&builder.into_model())
}

/// Parses `json` as a full `.gsim_sch` document (rejects a non-v2 `schema_version` with a clear
/// message), and returns the canonical re-serialized JSON -- proving round-trip validity.
#[pyfunction]
fn load_document(json: &str) -> PyResult<String> {
    let doc = GsimSchDocument::from_json(json).map_err(to_py_err)?;
    to_json(&doc)
}

/// Wraps a `Model` JSON into a full `{"schema_version": 2, "model": ...}` document, pretty-
/// printed.
#[pyfunction]
fn save_document(model_json: &str) -> PyResult<String> {
    let model: Model = parse_json(model_json, "model")?;
    GsimSchDocument::new(model)
        .to_json_pretty()
        .map_err(to_py_err)
}

/// `existing_json` is a JSON array of `{"x":.., "y":.., "w":.., "h":..}` rectangles; `axis` is
/// `"horizontal"` or `"vertical"`. Returns `[x, y]` as a JSON array.
#[pyfunction]
#[allow(clippy::too_many_arguments)]
fn place_without_overlap(
    existing_json: &str,
    w: i64,
    h: i64,
    desired_x: i64,
    desired_y: i64,
    axis: &str,
    margin: i64,
    grid: i64,
) -> PyResult<String> {
    let existing: Vec<Rect> = parse_json(existing_json, "existing rects")?;
    let axis = match axis {
        "horizontal" => Axis::Horizontal,
        "vertical" => Axis::Vertical,
        other => {
            return Err(to_py_err(format!(
                "invalid axis '{other}' (must be \"horizontal\" or \"vertical\")"
            )))
        }
    };
    let (x, y) = layout::place_without_overlap(
        &existing,
        (w, h),
        (desired_x, desired_y),
        axis,
        margin,
        grid,
    );
    to_json(&(x, y))
}

#[derive(Deserialize)]
struct LayoutBlockSpec {
    id: String,
    w: i64,
    h: i64,
}

/// `blocks_json` is `[{"id": "...", "w": .., "h": ..}, ...]`, `edges_json` is
/// `[["from_id","to_id"], ...]`. Returns `{"<block_id>": [x, y], ...}`.
#[pyfunction]
fn layered_layout(
    blocks_json: &str,
    edges_json: &str,
    column_gap: i64,
    row_gap: i64,
    grid: i64,
) -> PyResult<String> {
    let block_specs: Vec<LayoutBlockSpec> = parse_json(blocks_json, "blocks")?;
    let edge_specs: Vec<(String, String)> = parse_json(edges_json, "edges")?;

    let inputs: Vec<LayoutInput> = block_specs
        .iter()
        .map(|b| LayoutInput {
            id: &b.id,
            size: (b.w, b.h),
        })
        .collect();
    let edges: Vec<(&str, &str)> = edge_specs
        .iter()
        .map(|(from, to)| (from.as_str(), to.as_str()))
        .collect();

    let positions = layout::layered_layout(&inputs, &edges, column_gap, row_gap, grid);
    to_json(&positions)
}

#[pymodule]
fn gsim_py(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(version, m)?)?;
    m.add_function(wrap_pyfunction!(capabilities, m)?)?;
    m.add_function(wrap_pyfunction!(catalog, m)?)?;
    m.add_function(wrap_pyfunction!(evaluate_component, m)?)?;
    m.add_function(wrap_pyfunction!(validate_parameters, m)?)?;
    m.add_function(wrap_pyfunction!(new_model, m)?)?;
    m.add_function(wrap_pyfunction!(add_block, m)?)?;
    m.add_function(wrap_pyfunction!(compile, m)?)?;
    m.add_function(wrap_pyfunction!(add_subckt_def, m)?)?;
    m.add_function(wrap_pyfunction!(instantiate_subckt, m)?)?;
    m.add_function(wrap_pyfunction!(remove_block, m)?)?;
    m.add_function(wrap_pyfunction!(set_param, m)?)?;
    m.add_function(wrap_pyfunction!(add_model_param, m)?)?;
    m.add_function(wrap_pyfunction!(connect, m)?)?;
    m.add_function(wrap_pyfunction!(auto_arrange, m)?)?;
    m.add_function(wrap_pyfunction!(load_document, m)?)?;
    m.add_function(wrap_pyfunction!(save_document, m)?)?;
    m.add_function(wrap_pyfunction!(place_without_overlap, m)?)?;
    m.add_function(wrap_pyfunction!(layered_layout, m)?)?;
    Ok(())
}

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

    #[test]
    fn full_flow_new_model_add_blocks_connect_auto_arrange_save_load_round_trips() {
        let model = new_model("m1", "My Model", 10).unwrap();

        let spec1 = r#"{"type":"signal.step","paradigm":"signal-flow","domain":"control","position":[0,0],"rotation":0,"id":"src1"}"#;
        let add1: Value = serde_json::from_str(&add_block(&model, spec1).unwrap()).unwrap();
        let model = add1["model"].to_string();
        assert_eq!(add1["block_id"], "src1");

        let spec2 = r#"{"type":"control.gain","paradigm":"signal-flow","domain":"control","position":[0,0],"rotation":0,"id":"gain1"}"#;
        let add2: Value = serde_json::from_str(&add_block(&model, spec2).unwrap()).unwrap();
        let model = add2["model"].to_string();
        assert_eq!(add2["block_id"], "gain1");

        let from = r#"{"block":"src1","port":"out"}"#;
        let to = r#"{"block":"gain1","port":"in"}"#;
        let conn: Value =
            serde_json::from_str(&connect(&model, from, to, "signal", "{}", None).unwrap())
                .unwrap();
        let model = conn["model"].to_string();
        assert_eq!(conn["wire_id"], "wire1");

        let bbox_map = r#"{"src1": [40, 20], "gain1": [40, 20]}"#;
        let model = auto_arrange(&model, bbox_map, 20, 10).unwrap();

        let saved = save_document(&model).unwrap();
        assert!(saved.contains("\"schema_version\": 2"));

        let reloaded = load_document(&saved).unwrap();
        let reloaded_val: Value = serde_json::from_str(&reloaded).unwrap();
        assert_eq!(reloaded_val["model"]["id"], "m1");
        assert_eq!(reloaded_val["model"]["blocks"].as_array().unwrap().len(), 2);
        assert_eq!(reloaded_val["model"]["wires"].as_array().unwrap().len(), 1);

        // auto_arrange actually moved src1 before gain1.
        let model_val: Value = serde_json::from_str(&model).unwrap();
        let blocks = model_val["blocks"].as_array().unwrap();
        let src_x = blocks.iter().find(|b| b["id"] == "src1").unwrap()["position"][0]
            .as_i64()
            .unwrap();
        let gain_x = blocks.iter().find(|b| b["id"] == "gain1").unwrap()["position"][0]
            .as_i64()
            .unwrap();
        assert!(src_x < gain_x);
    }

    #[test]
    fn remove_block_cascades_wire_removal() {
        let model = new_model("m1", "M", 10).unwrap();
        let spec1 = r#"{"type":"passive.resistor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"r1"}"#;
        let add1: Value = serde_json::from_str(&add_block(&model, spec1).unwrap()).unwrap();
        let model = add1["model"].to_string();
        let spec2 = r#"{"type":"passive.capacitor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"c1"}"#;
        let add2: Value = serde_json::from_str(&add_block(&model, spec2).unwrap()).unwrap();
        let model = add2["model"].to_string();

        let from = r#"{"block":"r1","port":"n"}"#;
        let to = r#"{"block":"c1","port":"p"}"#;
        let conn: Value = serde_json::from_str(
            &connect(&model, from, to, "physical-electrical", "{}", None).unwrap(),
        )
        .unwrap();
        let model = conn["model"].to_string();

        let after_remove: Value =
            serde_json::from_str(&remove_block(&model, "r1").unwrap()).unwrap();
        assert_eq!(after_remove["blocks"].as_array().unwrap().len(), 1);
        assert_eq!(after_remove["wires"].as_array().unwrap().len(), 0);
    }

    #[test]
    fn set_param_and_add_model_param_round_trip() {
        let model = new_model("m1", "M", 10).unwrap();
        let spec = r#"{"type":"passive.resistor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"r1"}"#;
        let add: Value = serde_json::from_str(&add_block(&model, spec).unwrap()).unwrap();
        let model = add["model"].to_string();

        let model = set_param(&model, "r1", "R", "1000").unwrap();
        let model_val: Value = serde_json::from_str(&model).unwrap();
        assert_eq!(model_val["blocks"][0]["params"]["R"], 1000);

        let model = add_model_param(&model, "vcc", "5.0").unwrap();
        let model_val: Value = serde_json::from_str(&model).unwrap();
        assert_eq!(model_val["params"][0]["name"], "vcc");
        assert_eq!(model_val["params"][0]["value"], 5.0);
    }

    #[test]
    fn set_param_on_unknown_block_raises_with_real_message() {
        let model = new_model("m1", "M", 10).unwrap();
        let err = set_param(&model, "ghost", "R", "1000").unwrap_err();
        Python::attach(|py| {
            let msg = err.value(py).to_string();
            assert!(msg.contains("no block with id 'ghost'"), "got: {msg}");
        });
    }

    #[test]
    fn connect_dangling_endpoint_raises_with_dangling_in_message() {
        let model = new_model("m1", "M", 10).unwrap();
        let spec = r#"{"type":"passive.resistor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"r1"}"#;
        let add: Value = serde_json::from_str(&add_block(&model, spec).unwrap()).unwrap();
        let model = add["model"].to_string();

        let from = r#"{"block":"r1","port":"p"}"#;
        let to = r#"{"block":"ghost","port":"p"}"#;
        let err = connect(&model, from, to, "physical-electrical", "{}", None).unwrap_err();
        Python::attach(|py| {
            let msg = err.value(py).to_string();
            assert!(
                msg.to_lowercase().contains("unknown block")
                    || msg.to_lowercase().contains("dangling")
                    || msg.contains("ghost"),
                "got: {msg}"
            );
        });
    }

    #[test]
    fn connect_cross_paradigm_raises_with_cross_paradigm_in_message() {
        let model = new_model("m1", "M", 10).unwrap();
        let spec1 = r#"{"type":"passive.resistor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"r1"}"#;
        let add1: Value = serde_json::from_str(&add_block(&model, spec1).unwrap()).unwrap();
        let model = add1["model"].to_string();
        let spec2 = r#"{"type":"control.gain","paradigm":"signal-flow","domain":"control","position":[0,0],"rotation":0,"id":"gain1"}"#;
        let add2: Value = serde_json::from_str(&add_block(&model, spec2).unwrap()).unwrap();
        let model = add2["model"].to_string();

        let from = r#"{"block":"r1","port":"p"}"#;
        let to = r#"{"block":"gain1","port":"in"}"#;
        let err = connect(&model, from, to, "signal", "{}", None).unwrap_err();
        Python::attach(|py| {
            let msg = err.value(py).to_string();
            // `BuilderError::CrossParadigm`'s `Display` names both paradigms and the reason
            // rather than using the literal word "cross-paradigm" -- this asserts the specific
            // variant's message (not a generic "connect failed"), matching what the task
            // description means by "include ... literally".
            assert!(
                msg.contains(
                    "cannot connect a PhysicalNetwork block directly to a SignalFlow block"
                ),
                "got: {msg}"
            );
        });
    }

    #[test]
    fn connect_two_different_physical_domains_raises_port_kind_mismatch() {
        let model = new_model("m1", "M", 10).unwrap();
        let spec1 = r#"{"type":"passive.resistor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"r1"}"#;
        let add1: Value = serde_json::from_str(&add_block(&model, spec1).unwrap()).unwrap();
        let model = add1["model"].to_string();
        let spec2 = r#"{"type":"thermal.resistance","paradigm":"physical-network","domain":"thermal","position":[0,0],"rotation":0,"id":"rth"}"#;
        let add2: Value = serde_json::from_str(&add_block(&model, spec2).unwrap()).unwrap();
        let model = add2["model"].to_string();

        let from = r#"{"block":"r1","port":"p"}"#;
        let to = r#"{"block":"rth","port":"a"}"#;
        let err = connect(&model, from, to, "physical-electrical", "{}", None).unwrap_err();
        Python::attach(|py| {
            let msg = err.value(py).to_string();
            // The stable keyword prefix, then the full underlying message naming both the port
            // and the kind it actually declares -- the wrapper adds, never replaces.
            assert!(msg.starts_with("port-kind-mismatch: "), "got: {msg}");
            assert!(msg.contains("'rth.a' is declared 'thermal'"), "got: {msg}");
            assert!(
                msg.contains("as a 'physical-electrical' wire"),
                "got: {msg}"
            );
        });
    }

    #[test]
    fn connect_fanning_in_on_a_signal_port_raises_port_fan_in_on_signal() {
        let mut model = new_model("m1", "M", 10).unwrap();
        for id in ["s1", "s2", "g1"] {
            let spec = format!(
                r#"{{"type":"control.gain","paradigm":"signal-flow","domain":"control","position":[0,0],"rotation":0,"id":"{id}"}}"#
            );
            let add: Value = serde_json::from_str(&add_block(&model, &spec).unwrap()).unwrap();
            model = add["model"].to_string();
        }
        let to = r#"{"block":"g1","port":"in"}"#;
        let first: Value = serde_json::from_str(
            &connect(
                &model,
                r#"{"block":"s1","port":"out"}"#,
                to,
                "signal",
                "{}",
                None,
            )
            .unwrap(),
        )
        .unwrap();
        let model = first["model"].to_string();

        let err = connect(
            &model,
            r#"{"block":"s2","port":"out"}"#,
            to,
            "signal",
            "{}",
            None,
        )
        .unwrap_err();
        Python::attach(|py| {
            let msg = err.value(py).to_string();
            assert!(msg.starts_with("port-fan-in-on-signal: "), "got: {msg}");
            assert!(
                msg.contains("causal port 'g1.in' is already driven"),
                "got: {msg}"
            );
        });
    }

    #[test]
    fn connect_a_reserved_kind_raises_port_reserved_kind() {
        let mut model = new_model("m1", "M", 10).unwrap();
        for id in ["m1b", "m2b"] {
            let spec = format!(
                r#"{{"type":"magnetic.core","paradigm":"physical-network","domain":"mixed","position":[0,0],"rotation":0,"id":"{id}"}}"#
            );
            let add: Value = serde_json::from_str(&add_block(&model, &spec).unwrap()).unwrap();
            model = add["model"].to_string();
        }
        let err = connect(
            &model,
            r#"{"block":"m1b","port":"p"}"#,
            r#"{"block":"m2b","port":"p"}"#,
            "reserved.physical-magnetic",
            "{}",
            None,
        )
        .unwrap_err();
        Python::attach(|py| {
            let msg = err.value(py).to_string();
            assert!(msg.starts_with("port-reserved-kind: "), "got: {msg}");
            assert!(msg.contains("reserved.physical-magnetic"), "got: {msg}");
        });
    }

    /// A `{"<block type>": <contract>}` payload for `connect`'s optional sixth argument: one
    /// gain whose port `dim` follows its own `width` parameter.
    fn gain_registry_json() -> String {
        r#"{"control.gain": {
            "name": "control.gain",
            "label": "Gain",
            "parameters": [{"name": "width", "type": "number", "default": 1}],
            "ports": [
                {"id": "in", "side": "left", "kind": "signal", "direction": "in",
                 "dim": ["${{ params.width }}"]},
                {"id": "out", "side": "right", "kind": "signal", "direction": "out",
                 "dim": ["${{ params.width }}"]}
            ],
            "geometry": {"bbox": [40, 30], "primitives": []}
        }}"#
        .to_string()
    }

    /// Two `control.gain` blocks of the given widths, wired `g1.out -> g2.in`, with the registry
    /// above supplied (or not).
    fn gain_chain(from_width: i64, to_width: i64, contracts: Option<&str>) -> PyResult<String> {
        let mut model = new_model("m1", "M", 10).unwrap();
        for (id, width) in [("g1", from_width), ("g2", to_width)] {
            let spec = format!(
                r#"{{"type":"control.gain","paradigm":"signal-flow","domain":"signal","position":[0,0],"rotation":0,"id":"{id}","params":{{"width":{width}}}}}"#
            );
            let add: Value = serde_json::from_str(&add_block(&model, &spec).unwrap()).unwrap();
            model = add["model"].to_string();
        }
        connect(
            &model,
            r#"{"block":"g1","port":"out"}"#,
            r#"{"block":"g2","port":"in"}"#,
            "signal",
            "{}",
            contracts,
        )
    }

    #[test]
    fn connect_a_dim_mismatch_raises_port_dim_mismatch_only_when_contracts_are_supplied() {
        let registry = gain_registry_json();

        let err = gain_chain(3, 1, Some(&registry)).unwrap_err();
        Python::attach(|py| {
            let msg = err.value(py).to_string();
            assert!(msg.starts_with("port-dim-mismatch: "), "got: {msg}");
            assert!(
                msg.contains("cannot connect 'g1.out' to 'g2.in'"),
                "got: {msg}"
            );
            assert!(
                msg.contains("the source produces dim [3], but the destination requires dim [1]"),
                "got: {msg}"
            );
        });

        // Same widths -> accepted, so this is not a checker that rejects everything.
        gain_chain(3, 3, Some(&registry)).unwrap();

        // And with no registry the mismatch is simply invisible, exactly as before: the document
        // alone has no idea what dimension either port carries.
        gain_chain(3, 1, None).unwrap();
    }

    #[test]
    fn connect_a_signal_wire_onto_a_contract_declared_physical_port_raises_port_kind_mismatch() {
        // Neither block-level check can see this: both blocks are `physical-network` with
        // `domain: "mixed"`. Only the registered contract knows `sen2.p` is conserving.
        let contracts = r#"{"sensor.voltage": {
            "name": "sensor.voltage",
            "label": "Voltage sensor",
            "ports": [
                {"id": "p", "side": "left", "kind": "physical-electrical", "direction": "inout"},
                {"id": "out", "side": "right", "kind": "signal", "direction": "out"}
            ],
            "geometry": {"bbox": [40, 30], "primitives": []}
        }}"#;

        let mut model = new_model("m1", "M", 10).unwrap();
        for id in ["sen", "sen2"] {
            let spec = format!(
                r#"{{"type":"sensor.voltage","paradigm":"physical-network","domain":"mixed","position":[0,0],"rotation":0,"id":"{id}"}}"#
            );
            let add: Value = serde_json::from_str(&add_block(&model, &spec).unwrap()).unwrap();
            model = add["model"].to_string();
        }
        let from = r#"{"block":"sen","port":"out"}"#;
        let to = r#"{"block":"sen2","port":"p"}"#;

        let err = connect(&model, from, to, "signal", "{}", Some(contracts)).unwrap_err();
        Python::attach(|py| {
            let msg = err.value(py).to_string();
            assert!(msg.starts_with("port-kind-mismatch: "), "got: {msg}");
            assert!(
                msg.contains("'sen2.p' is declared 'physical-electrical'"),
                "got: {msg}"
            );
        });

        // Without the contract this is still accepted -- the fallback is preserved, not tightened.
        connect(&model, from, to, "signal", "{}", None).unwrap();
    }

    #[test]
    fn connect_with_malformed_contracts_json_raises_value_error_not_panic() {
        let err = gain_chain(1, 1, Some("not json")).unwrap_err();
        Python::attach(|py| {
            let msg = err.value(py).to_string();
            assert!(msg.contains("invalid contract registry JSON"), "got: {msg}");
        });
    }

    /// `gsim-tools` and any agent building a schematic in code reach this crate, not the Rust
    /// API, so the rating slot has to survive *this* JSON contract too. A rating dropped here
    /// would be a limit the author wrote and nothing enforces.
    #[test]
    fn add_block_carries_a_rating_and_compile_emits_it() {
        let mut model = new_model("m1", "M", 10).unwrap();
        for spec in [
            r#"{"type":"source.voltage.dc","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"Vin","params":{"V":10.0}}"#,
            r#"{"type":"passive.inductor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"L1","params":{"L":3.6e-5},"ratings":{"i_max":60,"on_violation":"stop"}}"#,
            r#"{"type":"routing.ground","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"gnd"}"#,
        ] {
            let add: Value = serde_json::from_str(&add_block(&model, spec).unwrap()).unwrap();
            model = add["model"].to_string();
        }
        let parsed: Value = serde_json::from_str(&model).unwrap();
        let rated = parsed["blocks"]
            .as_array()
            .unwrap()
            .iter()
            .find(|b| b["id"] == "L1")
            .unwrap();
        assert_eq!(rated["ratings"]["i_max"], 60);

        for (from, to) in [
            (
                r#"{"block":"Vin","port":"p"}"#,
                r#"{"block":"L1","port":"p"}"#,
            ),
            (
                r#"{"block":"L1","port":"n"}"#,
                r#"{"block":"gnd","port":"p"}"#,
            ),
            (
                r#"{"block":"Vin","port":"n"}"#,
                r#"{"block":"gnd","port":"p"}"#,
            ),
        ] {
            let conn: Value = serde_json::from_str(
                &connect(&model, from, to, "physical-electrical", "{}", None).unwrap(),
            )
            .unwrap();
            model = conn["model"].to_string();
        }

        let out = compile(&model, "general-simulator").unwrap();
        let netlist: Value = serde_json::from_str(&out).unwrap();
        let netlist = netlist["netlist"].as_str().unwrap();
        assert!(netlist.contains("i_max=60 on_violation=stop"), "{netlist}");
    }

    #[test]
    fn add_block_duplicate_id_raises_with_duplicate_in_message() {
        let model = new_model("m1", "M", 10).unwrap();
        let spec = r#"{"type":"passive.resistor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"r1"}"#;
        let add: Value = serde_json::from_str(&add_block(&model, spec).unwrap()).unwrap();
        let model = add["model"].to_string();

        let err = add_block(&model, spec).unwrap_err();
        Python::attach(|py| {
            let msg = err.value(py).to_string();
            assert!(msg.to_lowercase().contains("duplicate"), "got: {msg}");
        });
    }

    #[test]
    fn add_block_invalid_rotation_raises() {
        let model = new_model("m1", "M", 10).unwrap();
        let spec = r#"{"type":"passive.resistor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":45,"id":"r1"}"#;
        let err = add_block(&model, spec).unwrap_err();
        Python::attach(|py| {
            let msg = err.value(py).to_string();
            assert!(msg.to_lowercase().contains("rotation"), "got: {msg}");
        });
    }

    #[test]
    fn bad_json_raises_value_error_not_panic() {
        let result = add_block(r#"{not json"#, "{}");
        assert!(result.is_err());
    }

    #[test]
    fn evaluate_component_and_validate_parameters_on_a_real_contract() {
        let contract_json = std::fs::read_to_string(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../gsim-core/tests/fixtures/general_simulator/control.sum.json"
        ))
        .unwrap();

        let evaluated = evaluate_component(&contract_json, r#"{"signs": [1, 1, -1]}"#).unwrap();
        let evaluated_val: Value = serde_json::from_str(&evaluated).unwrap();
        assert_eq!(evaluated_val["ports"].as_array().unwrap().len(), 4); // 3 inputs + out

        let failures = validate_parameters(&contract_json, r#"{"signs": []}"#).unwrap();
        let failures_val: Value = serde_json::from_str(&failures).unwrap();
        assert_eq!(failures_val.as_array().unwrap().len(), 1);
        assert_eq!(failures_val[0]["parameter"], "signs");

        let ok = validate_parameters(&contract_json, r#"{"signs": [1, -1]}"#).unwrap();
        assert_eq!(ok, "[]");
    }

    #[test]
    fn evaluate_component_bad_contract_json_raises() {
        let err = evaluate_component("{not json", "{}").unwrap_err();
        Python::attach(|py| {
            let msg = err.value(py).to_string();
            assert!(!msg.is_empty());
        });
    }

    #[test]
    fn place_without_overlap_steps_around_a_blocker() {
        let existing = r#"[{"x":100,"y":100,"w":20,"h":20}]"#;
        let result =
            place_without_overlap(existing, 20, 20, 100, 100, "horizontal", 5, 10).unwrap();
        let pos: (i64, i64) = serde_json::from_str(&result).unwrap();
        assert_ne!(pos, (100, 100));
    }

    #[test]
    fn place_without_overlap_invalid_axis_raises() {
        let err = place_without_overlap("[]", 20, 20, 0, 0, "diagonal", 5, 10).unwrap_err();
        Python::attach(|py| {
            let msg = err.value(py).to_string();
            assert!(msg.contains("axis"), "got: {msg}");
        });
    }

    #[test]
    fn layered_layout_orders_a_chain_left_to_right() {
        let blocks =
            r#"[{"id":"a","w":40,"h":20},{"id":"b","w":40,"h":20},{"id":"c","w":40,"h":20}]"#;
        let edges = r#"[["a","b"],["b","c"]]"#;
        let result = layered_layout(blocks, edges, 20, 10, 10).unwrap();
        let positions: HashMap<String, (i64, i64)> = serde_json::from_str(&result).unwrap();
        assert!(positions["a"].0 < positions["b"].0);
        assert!(positions["b"].0 < positions["c"].0);
    }

    #[test]
    fn load_document_rejects_non_v2_schema_version() {
        let text = r#"{"schema_version":1,"model":{"id":"m","name":"M","blocks":[],"wires":[]}}"#;
        let err = load_document(text).unwrap_err();
        Python::attach(|py| {
            let msg = err.value(py).to_string();
            assert!(
                msg.contains("schema_version") || msg.contains("2"),
                "got: {msg}"
            );
        });
    }

    #[test]
    fn version_is_not_empty() {
        assert!(!version().is_empty());
    }

    // -- subckt ------------------------------------------------------------

    const LEAF_DEF: &str = r#"{"id":"leaf","name":"LEAF","ports":[
        {"id":"a","kind":"physical-electrical"},
        {"id":"b","kind":"physical-electrical"}]}"#;

    fn err_msg(err: PyErr) -> String {
        Python::attach(|py| err.value(py).to_string())
    }

    #[test]
    fn add_subckt_def_then_instantiate_twice_and_wire_both() {
        let model = new_model("m1", "M", 10).unwrap();
        let added: Value =
            serde_json::from_str(&add_subckt_def(&model, LEAF_DEF).unwrap()).unwrap();
        assert_eq!(added["def_id"], "leaf");
        let model = serde_json::to_string(&added["model"]).unwrap();

        let mut model = model;
        for id in ["x1", "x2"] {
            let spec = format!(r#"{{"def_ref":"leaf","position":[0,0],"id":"{id}"}}"#);
            let r: Value =
                serde_json::from_str(&instantiate_subckt(&model, &spec).unwrap()).unwrap();
            assert_eq!(r["block_id"], id);
            model = serde_json::to_string(&r["model"]).unwrap();
        }

        // Ordinary connect() wires the def's own port ids -- no catalogue lookup involved.
        let r: Value = serde_json::from_str(
            &connect(
                &model,
                r#"{"block":"x1","port":"b"}"#,
                r#"{"block":"x2","port":"a"}"#,
                "physical-electrical",
                "{}",
                None,
            )
            .unwrap(),
        )
        .unwrap();
        let model = serde_json::to_string(&r["model"]).unwrap();

        let doc = save_document(&model).unwrap();
        let reloaded: Value = serde_json::from_str(&load_document(&doc).unwrap()).unwrap();
        assert_eq!(reloaded["schema_version"], 2);
        assert_eq!(
            reloaded["model"]["subckt_defs"].as_array().unwrap().len(),
            1
        );
        assert_eq!(reloaded["model"]["blocks"].as_array().unwrap().len(), 2);
        assert_eq!(reloaded["model"]["blocks"][0]["subckt_ref"], "leaf");
        assert_eq!(reloaded["model"]["blocks"][0]["paradigm"], "spice-subckt");
        assert_eq!(
            reloaded["model"]["blocks"][0]["type"],
            "spice-subckt.instance"
        );
    }

    #[test]
    fn add_subckt_def_duplicate_id_raises_with_duplicate_in_message() {
        let model = new_model("m1", "M", 10).unwrap();
        let added: Value =
            serde_json::from_str(&add_subckt_def(&model, LEAF_DEF).unwrap()).unwrap();
        let model = serde_json::to_string(&added["model"]).unwrap();
        let msg = err_msg(add_subckt_def(&model, LEAF_DEF).unwrap_err());
        assert!(msg.starts_with("duplicate:"), "got: {msg}");
    }

    #[test]
    fn add_subckt_def_cycle_raises_naming_the_actual_cycle() {
        let model = new_model("m1", "M", 10).unwrap();
        let a = r#"{"id":"a","name":"A","instances":[{"id":"X1","def_ref":"b"}]}"#;
        let added: Value = serde_json::from_str(&add_subckt_def(&model, a).unwrap()).unwrap();
        let model = serde_json::to_string(&added["model"]).unwrap();
        let b = r#"{"id":"b","name":"B","instances":[{"id":"X1","def_ref":"a"}]}"#;
        let msg = err_msg(add_subckt_def(&model, b).unwrap_err());
        assert!(msg.starts_with("cyclic-subckt-def:"), "got: {msg}");
        assert!(
            msg.contains("a -> b -> a") || msg.contains("b -> a -> b"),
            "the message must name the actual cycle, got: {msg}"
        );
    }

    #[test]
    fn add_subckt_def_self_reference_raises() {
        let model = new_model("m1", "M", 10).unwrap();
        let d = r#"{"id":"loopy","name":"L","instances":[{"id":"X1","def_ref":"loopy"}]}"#;
        let msg = err_msg(add_subckt_def(&model, d).unwrap_err());
        assert!(msg.contains("loopy -> loopy"), "got: {msg}");
    }

    #[test]
    fn add_subckt_def_bad_port_kind_raises() {
        let model = new_model("m1", "M", 10).unwrap();
        let d = r#"{"id":"d1","name":"D","ports":[{"id":"bus","kind":"physical-signal"}]}"#;
        let msg = err_msg(add_subckt_def(&model, d).unwrap_err());
        assert!(msg.starts_with("invalid-subckt:"), "got: {msg}");
        assert!(msg.contains("physical-signal"), "got: {msg}");
    }

    #[test]
    fn instantiate_unknown_def_ref_raises() {
        let model = new_model("m1", "M", 10).unwrap();
        let msg = err_msg(
            instantiate_subckt(&model, r#"{"def_ref":"ghost","position":[0,0]}"#).unwrap_err(),
        );
        assert!(msg.starts_with("unknown-subckt-def:"), "got: {msg}");
        assert!(msg.contains("ghost"), "got: {msg}");
    }

    #[test]
    fn instantiate_subckt_bad_json_raises_value_error_not_panic() {
        let model = new_model("m1", "M", 10).unwrap();
        assert!(instantiate_subckt(&model, "{not json").is_err());
        assert!(add_subckt_def(&model, "{not json").is_err());
    }

    #[test]
    fn compile_emits_a_netlist_and_reports_notes() {
        let model = new_model("m1", "M", 10).unwrap();
        let r = |m: &str, s: &str| -> String {
            let v: Value = serde_json::from_str(&add_block(m, s).unwrap()).unwrap();
            serde_json::to_string(&v["model"]).unwrap()
        };
        let model = r(
            &model,
            r#"{"type":"passive.resistor","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"R1","params":{"R":1000}}"#,
        );
        let model = r(
            &model,
            r#"{"type":"routing.ground","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"gnd"}"#,
        );
        let mut model = model;
        for port in ["p", "n"] {
            let v: Value = serde_json::from_str(
                &connect(
                    &model,
                    &format!(r#"{{"block":"R1","port":"{port}"}}"#),
                    r#"{"block":"gnd","port":"p"}"#,
                    "physical-electrical",
                    "{}",
                    None,
                )
                .unwrap(),
            )
            .unwrap();
            model = serde_json::to_string(&v["model"]).unwrap();
        }
        let out: Value =
            serde_json::from_str(&compile(&model, "general-simulator").unwrap()).unwrap();
        assert!(
            out["netlist"].as_str().unwrap().contains("R1 0 0 1000"),
            "{out}"
        );
        assert!(out["notes"].is_array());
    }

    #[test]
    fn compile_unknown_target_raises_keyword_prefixed() {
        let model = new_model("m1", "M", 10).unwrap();
        let msg = err_msg(compile(&model, "ngspice").unwrap_err());
        assert!(msg.starts_with("unknown-target:"), "got: {msg}");
    }

    #[test]
    fn compile_unknown_type_raises_keyword_prefixed() {
        let model = new_model("m1", "M", 10).unwrap();
        let v: Value = serde_json::from_str(
            &add_block(
                &model,
                r#"{"type":"made.up.type","paradigm":"physical-network","domain":"electrical","position":[0,0],"rotation":0,"id":"z1"}"#,
            )
            .unwrap(),
        )
        .unwrap();
        let model = serde_json::to_string(&v["model"]).unwrap();
        let msg = err_msg(compile(&model, "general-simulator").unwrap_err());
        assert!(msg.starts_with("unknown-type:"), "got: {msg}");
        assert!(msg.contains("made.up.type"), "got: {msg}");
    }

    /// A `Model` carrying the four features `gsim-core` does not model, plus a key no struct
    /// anywhere models. See `gsim-core/tests/the_document_keeps_what_it_does_not_model_78.rs`.
    const MODEL_WITH_UNMODELLED_FIELDS: &str = r#"{
        "id": "top", "name": "Top", "grid": 10,
        "blocks": [{
            "id": "sub1", "type": "hierarchy.subsystem", "paradigm": "hierarchy",
            "domain": "mixed", "position": [0, 0],
            "subsystem": { "id": "inner", "name": "Inner", "blocks": [], "wires": [] }
        }],
        "wires": [],
        "subckt_defs": [{ "id": "od", "name": "OPAMP", "body": "E1 out 0 inp inn 1e5" }],
        "ports": [{ "id": "p1", "direction": "in", "kind": "signal" }],
        "parent_param_aliases": [{ "inner": "x", "outer": "fsw" }],
        "a_field_from_a_later_format_version": 42
    }"#;

    /// The wheel is the officially recommended way to build a document programmatically, so
    /// this is the surface a user actually loses data through -- #78 is only fixed if it is
    /// fixed *here*, not merely on the Rust struct.
    #[test]
    fn save_document_keeps_the_fields_the_engine_does_not_model_78() {
        let doc: Value =
            serde_json::from_str(&save_document(MODEL_WITH_UNMODELLED_FIELDS).unwrap()).unwrap();
        let model = &doc["model"];
        assert_eq!(model["blocks"][0]["subsystem"]["id"], "inner");
        assert_eq!(model["subckt_defs"][0]["body"], "E1 out 0 inp inn 1e5");
        assert_eq!(model["ports"][0]["id"], "p1");
        assert_eq!(model["parent_param_aliases"][0]["outer"], "fsw");
        assert_eq!(model["a_field_from_a_later_format_version"], 42);

        // ...and a second trip through the pair the editor actually calls keeps them too.
        let again: Value = serde_json::from_str(&load_document(&doc.to_string()).unwrap()).unwrap();
        assert_eq!(again["model"]["blocks"][0]["subsystem"]["id"], "inner");
        assert_eq!(
            again["model"]["subckt_defs"][0]["body"],
            "E1 out 0 inp inn 1e5"
        );
    }
}