dcmnorm 0.22.5

Fast DICOM toolkit: parse, render, transcode, reformat, de-identify and network (DIMSE) DICOM medical images.
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
//! Native DICOM Upper Layer / DIMSE service class user (SCU) operations: C-ECHO, C-STORE,
//! C-FIND, and C-MOVE. Ports the same request/response shapes as the dcmtk CLIs
//! (`echoscu`/`dcmsend`/`findscu`/`movescu`) this replaces, but as library calls that return
//! structured results instead of printing/exiting - callers decide what counts as a failure.
//!
//! `dcmnorm-dimse` (the DICOM Upper Layer/association crate used here) is purely transport-layer: it
//! knows about PDUs and presentation-context negotiation, nothing about DIMSE command semantics.
//! Every operation below hand-builds its own command dataset via
//! `InMemDicomObject::command_from_element_iter` + `dcmnorm_dictionary::tags`, the same way
//! dcmtk/dicom-rs's example CLIs do - there is no higher-level DIMSE helper anywhere in this
//! dependency stack, including for C-MOVE (which has no reference implementation to port from;
//! its command dataset and response loop are built directly from PS3.7).
//!
//! `dcmnorm-dimse` 0.9.1's `ClientAssociation` does not release on `Drop` (older versions did) - every
//! function here explicitly releases once it has a terminal result (via `release_and_log` - see
//! its doc comment for why a failed release is only ever logged, never turned into an `Err`, and
//! can't fall back to `.abort()` the way every other fallible step does) and aborts on error paths
//! otherwise.

use std::collections::HashMap;
use std::error::Error as StdError;
use std::fmt;
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use dcmnorm_core::dictionary::{DataDictionary, DataDictionaryEntry};
use dcmnorm_core::{dicom_value, DataElement, PrimitiveValue, VR};
use dcmnorm_dictionary::{tags, uids, StandardDataDictionary};
use dcmnorm_dimse::{
    association::{client::ClientAssociationOptions, Error as AssociationError},
    pdu::{PDataValue, PDataValueType, Pdu, PresentationContextNegotiated},
    ClientAssociation, Incoming,
};
use dcmnorm_encoding::{TransferSyntax, TransferSyntaxIndex};
use dcmnorm_object::{FileMetaTable, InMemDicomObject, OpenFileOptions, ReadPreamble};
use dcmnorm_transcode::TransferSyntaxRegistry;

use super::io::{can_encode_transfer_syntax, read_dicom_file, transcode_dcmnorm_object_owned};
use super::json::write_dataset_as_dicom_json_with_options;
use super::streaming_transcode::prepare_streaming_dataset_for_dimse;
use super::types::{
    DicomJsonError, DicomJsonFormat, DicomJsonKeyStyle, DicomJsonWriteOptions, ReadError,
    TranscodeError, WriteError,
};

/// Which DICOM UL teardown verb an external `cancel` request is asking for - see
/// [`CancelSignal`]. `Release` sends a real A-RELEASE-RQ and waits (briefly) for the peer's
/// A-RELEASE-RP, matching a normal successful terminal response's own teardown path. `Abort`
/// sends A-ABORT and returns immediately without waiting on the peer at all - faster and more
/// certain when the caller needs to be assured the association is over as soon as possible.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CancelMode {
    Release,
    Abort,
}

/// A shared flag an external caller uses to ask an in-progress SCU call to stop waiting and
/// tear down its association - checked once per `poll_bounded` tick (see its doc comment).
/// Replaces a plain `AtomicBool` so a caller can ask for either DICOM UL teardown verb
/// ([`CancelMode`]), not just "cancel".
pub struct CancelSignal(AtomicU8);

impl CancelSignal {
    pub fn new() -> Arc<Self> {
        Arc::new(Self(AtomicU8::new(0)))
    }

    pub fn request(&self, mode: CancelMode) {
        let value = match mode {
            CancelMode::Release => 1,
            CancelMode::Abort => 2,
        };
        self.0.store(value, Ordering::SeqCst);
    }

    pub fn requested(&self) -> Option<CancelMode> {
        match self.0.load(Ordering::SeqCst) {
            1 => Some(CancelMode::Release),
            2 => Some(CancelMode::Abort),
            _ => None,
        }
    }
}

#[derive(Debug)]
pub enum DimseError {
    Association(AssociationError),
    Read(ReadError),
    Write(WriteError),
    Transcode(TranscodeError),
    Json(DicomJsonError),
    Io(std::io::Error),
    UnknownTransferSyntax(String),
    NoAcceptedPresentationContext,
    NoAcceptablePresentationContext {
        sop_class_uid: String,
        transfer_syntax_uid: String,
    },
    NoFilesToSend,
    InvalidQueryKey(String),
    /// A `move_scu` retrieve's level/UID options don't form a valid C-MOVE Identifier (an unknown
    /// `QueryRetrieveLevel`, a SERIES/IMAGE retrieve without its `SeriesInstanceUID`, an IMAGE
    /// retrieve without any `SOPInstanceUID`, or a UID that isn't one) - rejected before any
    /// association is opened.
    InvalidMoveIdentifier(String),
    /// Something the peer sent didn't have the shape a well-behaved SCP response should have
    /// (missing Status, malformed PDU sequence, etc.) - not one of the specific, expected error
    /// paths above.
    Protocol(String),
    /// The operation's absolute wall-clock ceiling (`*ScuOptions::timeout`) elapsed before it
    /// reached a terminal state. Distinct from `Io`'s per-read timeout: this fires even if
    /// individual reads keep succeeding - e.g. a peer sending periodic pending-status responses
    /// without ever making real progress - since it's checked against a fixed deadline computed
    /// once at the start of the call, not reset by activity. See `poll_bounded`.
    AbsoluteTimeout,
    /// A `move_scu` retrieve's own `stale_data_path` hasn't had a file created/modified within
    /// `stale_data_timeout`, even though the association with the source is still nominally
    /// alive (e.g. it keeps sending pending C-MOVE-RSPs) - a faster, more specific signal than
    /// `AbsoluteTimeout` for a retrieve that's stopped actually writing data to our own storage.
    StaleDataConnection {
        path: PathBuf,
    },
    /// An external caller (`*ScuOptions::cancel`) asked this operation to stop waiting - not
    /// a peer/protocol failure. `move_scu` catches this itself and turns it into a successful,
    /// `cancelled: true` result rather than letting it propagate as an error to its caller (see
    /// `poll_bounded` and `move_scu`); `echo_scu`/`store_scu`/`find_scu` have no equivalent
    /// "we already know the outcome" case, so it propagates as a plain error for them.
    Cancelled(CancelMode),
}

impl fmt::Display for DimseError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Association(error) => write!(formatter, "DICOM association error: {error}"),
            Self::Read(error) => write!(formatter, "failed to read DICOM data: {error}"),
            Self::Write(error) => write!(formatter, "failed to write DICOM data: {error}"),
            Self::Transcode(error) => write!(formatter, "failed to transcode DICOM data: {error}"),
            Self::Json(error) => write!(formatter, "failed to build DICOM JSON: {error}"),
            Self::Io(error) => write!(formatter, "I/O error: {error}"),
            Self::UnknownTransferSyntax(uid) => write!(formatter, "unknown transfer syntax: {uid}"),
            Self::NoAcceptedPresentationContext => {
                write!(formatter, "peer did not accept any proposed presentation context")
            }
            Self::NoAcceptablePresentationContext { sop_class_uid, transfer_syntax_uid } => write!(
                formatter,
                "no accepted presentation context for SOP class {sop_class_uid} with transfer syntax {transfer_syntax_uid}"
            ),
            Self::NoFilesToSend => write!(formatter, "no valid DICOM files to send"),
            Self::InvalidQueryKey(key) => write!(formatter, "invalid query key '{key}'"),
            Self::InvalidMoveIdentifier(message) => write!(formatter, "invalid C-MOVE identifier: {message}"),
            Self::Protocol(message) => write!(formatter, "DIMSE protocol error: {message}"),
            Self::AbsoluteTimeout => write!(formatter, "operation exceeded its absolute timeout"),
            Self::StaleDataConnection { path } => write!(
                formatter,
                "no new data written under {} within the configured staleness window; treating the connection as stale",
                path.display()
            ),
            Self::Cancelled(CancelMode::Release) => {
                write!(formatter, "operation was cancelled by the caller (graceful release)")
            }
            Self::Cancelled(CancelMode::Abort) => {
                write!(formatter, "operation was cancelled by the caller (hard abort)")
            }
        }
    }
}

impl StdError for DimseError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Self::Association(error) => Some(error),
            Self::Read(error) => Some(error),
            Self::Write(error) => Some(error),
            Self::Transcode(error) => Some(error),
            Self::Json(error) => Some(error),
            Self::Io(error) => Some(error),
            Self::UnknownTransferSyntax(_)
            | Self::NoAcceptedPresentationContext
            | Self::NoAcceptablePresentationContext { .. }
            | Self::NoFilesToSend
            | Self::InvalidQueryKey(_)
            | Self::InvalidMoveIdentifier(_)
            | Self::Protocol(_)
            | Self::AbsoluteTimeout
            | Self::StaleDataConnection { .. }
            | Self::Cancelled(_) => None,
        }
    }
}

impl From<AssociationError> for DimseError {
    fn from(value: AssociationError) -> Self {
        Self::Association(value)
    }
}

impl From<ReadError> for DimseError {
    fn from(value: ReadError) -> Self {
        Self::Read(value)
    }
}

impl From<WriteError> for DimseError {
    fn from(value: WriteError) -> Self {
        Self::Write(value)
    }
}

impl From<TranscodeError> for DimseError {
    fn from(value: TranscodeError) -> Self {
        Self::Transcode(value)
    }
}

impl From<DicomJsonError> for DimseError {
    fn from(value: DicomJsonError) -> Self {
        Self::Json(value)
    }
}

impl From<std::io::Error> for DimseError {
    fn from(value: std::io::Error) -> Self {
        Self::Io(value)
    }
}

/// Optional sink for DIMSE debug detail - association negotiation, each command sent/received,
/// and the eventual release/abort - that every `*_scu` function below reports through if its
/// Options carry one via `on_log`. A trait (rather than a plain `Fn(String)`) so the napi
/// binding can implement it once over a `ThreadsafeFunction`, matching how `ScpHandlers` bridges
/// its own callbacks across that same boundary.
pub trait DimseLogger: Send + Sync {
    fn log(&self, message: String);
}

/// Calls `logger.log(message())` if a logger is present - `message` is only built when
/// something is actually listening, so this costs nothing when no logger was supplied.
///
/// `pub(super)` (rather than private) so `scp.rs` - the SCP/server-side counterpart of this
/// module's SCU functions - can report the same association/presentation-context/per-message/
/// release detail through its own `ScpOptions::on_log`.
pub(super) fn log_event(logger: Option<&dyn DimseLogger>, message: impl FnOnce() -> String) {
    if let Some(logger) = logger {
        logger.log(message());
    }
}

pub(super) fn transfer_syntax(uid: &str) -> Result<&'static TransferSyntax, DimseError> {
    TransferSyntaxRegistry
        .get(uid)
        .ok_or_else(|| DimseError::UnknownTransferSyntax(uid.to_owned()))
}

pub(super) fn implicit_vr_le() -> &'static TransferSyntax {
    transfer_syntax(uids::IMPLICIT_VR_LITTLE_ENDIAN)
        .expect("Implicit VR Little Endian is always registered")
}

fn default_transfer_syntaxes() -> Vec<String> {
    vec![
        uids::EXPLICIT_VR_LITTLE_ENDIAN.to_owned(),
        uids::IMPLICIT_VR_LITTLE_ENDIAN.to_owned(),
    ]
}

/// Establishes an association proposing the given (abstract syntax, transfer syntaxes) pairs,
/// each as its own presentation context - mirrors how `store_scu` needs one context per (SOP
/// class, transfer syntax) pair it might send, while `echo_scu`/`find_scu`/`move_scu` each pass
/// a single pair.
fn establish(
    destination: &str,
    calling_ae_title: &str,
    called_ae_title: Option<&str>,
    max_pdu_length: u32,
    presentation_contexts: &[(String, Vec<String>)],
    timeout: Option<Duration>,
    logger: Option<&dyn DimseLogger>,
) -> Result<ClientAssociation<TcpStream>, DimseError> {
    log_event(logger, || {
        format!(
            "opening association to {destination} (calling AE {calling_ae_title:?}, called AE {:?}, max PDU {max_pdu_length}, {} presentation context(s) proposed)",
            called_ae_title.unwrap_or("<none>"),
            presentation_contexts.len()
        )
    });

    let mut options = ClientAssociationOptions::new()
        .calling_ae_title(calling_ae_title.to_owned())
        .max_pdu_length(max_pdu_length);

    for (abstract_syntax, transfer_syntaxes) in presentation_contexts {
        options =
            options.with_presentation_context(abstract_syntax.clone(), transfer_syntaxes.clone());
    }

    if let Some(called_ae_title) = called_ae_title {
        options = options.called_ae_title(called_ae_title.to_owned());
    }

    if let Some(timeout) = timeout {
        options = options
            .read_timeout(timeout)
            .write_timeout(timeout)
            .connection_timeout(timeout);
    }

    match options.establish_with(destination) {
        Ok(assoc) => {
            log_event(logger, || {
                let negotiated = assoc
                    .presentation_contexts()
                    .iter()
                    .map(|pc| format!("#{} {} / {}", pc.id, pc.abstract_syntax, pc.transfer_syntax))
                    .collect::<Vec<_>>()
                    .join(", ");
                format!(
                    "association established; negotiated presentation context(s): [{negotiated}]"
                )
            });
            Ok(assoc)
        }
        Err(error) => {
            log_event(logger, || format!("association failed: {error}"));
            Err(error.into())
        }
    }
}

fn send_command(
    assoc: &mut ClientAssociation<TcpStream>,
    pc_id: u8,
    command: &InMemDicomObject,
) -> Result<(), DimseError> {
    let mut data = Vec::with_capacity(128);
    command.write_dataset_with_ts(&mut data, implicit_vr_le())?;
    assoc.send(&Pdu::PData {
        data: vec![PDataValue {
            presentation_context_id: pc_id,
            value_type: PDataValueType::Command,
            is_last: true,
            data,
        }],
    })?;
    Ok(())
}

/// Sends a Command followed by its Data Set (the Identifier for C-FIND/C-MOVE, or the instance
/// for C-STORE) as a single P-DATA-TF PDU - one `assoc.send()`, one write - whenever both fit
/// under the negotiated PDU size. Splitting them into two separate PDUs/writes (as this used to
/// do unconditionally for C-FIND/C-MOVE) leaves a gap between them that, since `dcmnorm-dimse`'s
/// TcpStream never sets TCP_NODELAY, Nagle's algorithm can stretch out unpredictably - at least
/// one real-world SCP encountered in production doesn't tolerate that gap and drops or garbles
/// the association. Falls back to two PDUs (fragmenting the data set via `send_pdata`) only when
/// combined they don't fit in one.
fn send_command_with_data(
    assoc: &mut ClientAssociation<TcpStream>,
    pc_id: u8,
    command: &InMemDicomObject,
    data: Vec<u8>,
) -> Result<(), DimseError> {
    let mut command_data = Vec::with_capacity(128);
    command.write_dataset_with_ts(&mut command_data, implicit_vr_le())?;

    let combined_len = command_data.len() + data.len();
    if combined_len < assoc.acceptor_max_pdu_length().saturating_sub(100) as usize {
        assoc.send(&Pdu::PData {
            data: vec![
                PDataValue {
                    presentation_context_id: pc_id,
                    value_type: PDataValueType::Command,
                    is_last: true,
                    data: command_data,
                },
                PDataValue {
                    presentation_context_id: pc_id,
                    value_type: PDataValueType::Data,
                    is_last: true,
                    data,
                },
            ],
        })?;
    } else {
        assoc.send(&Pdu::PData {
            data: vec![PDataValue {
                presentation_context_id: pc_id,
                value_type: PDataValueType::Command,
                is_last: true,
                data: command_data,
            }],
        })?;
        let mut writer = assoc.send_pdata(pc_id);
        std::io::Write::write_all(&mut writer, &data)?;
        writer.finish()?;
    }
    Ok(())
}

/// The next response command. Message-level (dcmnorm-dimse's `message.rs`): PDU boundaries mean nothing, a peer may pack
/// a response, its data set and the next response into one PDU (dcm4che does), and a read timeout (a `poll_bounded` tick)
/// mid-PDU or mid-message keeps what was read for the retry.
fn receive_command(
    assoc: &mut ClientAssociation<TcpStream>,
) -> Result<InMemDicomObject, DimseError> {
    match assoc.receive_command()? {
        Incoming::Command { data, .. } => Ok(InMemDicomObject::read_dataset_with_ts(
            data.as_slice(),
            implicit_vr_le(),
        )?),
        Incoming::Pdu(other) => Err(DimseError::Protocol(format!(
            "unexpected response PDU: {other:?}"
        ))),
    }
}

/// The data set that follows the response command just received (see `receive_command`).
fn read_pdata_to_end(assoc: &mut ClientAssociation<TcpStream>) -> Result<Vec<u8>, DimseError> {
    Ok(assoc.receive_data_set()?)
}

/// Releases `assoc`, logging clearly if the release itself fails - unlike a bare
/// `assoc.release()?`, which this replaces at every call site and which failed *silently*: no log
/// line at all, just whatever generic error the top-level caller happened to surface, if any.
///
/// Deliberately does *not* return a `Result` - every call site calls this only after it already
/// has the operation's real outcome in hand (a validated terminal DIMSE response), and per PS3.7's
/// layering, the DIMSE operation is complete once that response is received; A-RELEASE is a
/// separate, purely transport-level teardown courtesy, not part of the operation's own success
/// criteria (this matches dcmtk: `movescu`'s reported exit status comes from the C-MOVE-RSP alone,
/// never from whether the later `ASC_releaseAssociation` succeeded). A caller that let a release
/// hiccup override an already-successful result would report the operation as failed - and for a
/// queue-backed caller like the move service, that means an unnecessary retry, re-driving a source
/// PACS through a whole retrieve it already completed. So this only ever logs; it can't fail the
/// call.
///
/// This also can't reuse the log+abort pattern every other fallible step in these SCU functions
/// uses, because `ClientAssociation::release`/`::abort` both take `self` by value - once
/// `release()` has consumed and failed on `assoc`, there is no association object left to call
/// `.abort()` on; that's a hard constraint of this dcmnorm-dimse version's API, not a choice made here.
/// `release()` sends A-RELEASE-RQ and then expects `Pdu::ReleaseRP` back; if the peer sends
/// anything else first (including a stray trailing `PData` - the same shape as the RamSoft "Failed
/// SOP Instance UID List sent as its own PDU" case `move_scu` already drains for, just now on a
/// success/terminal response instead of a failure one), `release()` returns `Err` without sending
/// an A-ABORT PDU. The underlying TCP socket still gets closed (via `TcpStream`'s own `Drop`, once
/// the consumed `assoc` goes out of scope here) - so the peer does see the connection go away -
/// just as an abrupt close rather than a graceful DICOM release/abort handshake.
fn release_and_log(
    assoc: ClientAssociation<TcpStream>,
    logger: Option<&dyn DimseLogger>,
    on_success: impl FnOnce() -> String,
) {
    match assoc.release() {
        Ok(()) => log_event(logger, on_success),
        Err(error) => log_event(logger, || {
            format!(
                "association release failed (peer did not send a clean A-RELEASE-RP), but the \
                 operation's own result was already determined and is not affected by this: {}",
                DimseError::from(error)
            )
        }),
    }
}

// ---------------------------------------------------------------------------------------------
// Absolute-deadline enforcement
//
// `establish`'s `read_timeout` (set once, via `TcpStream::set_read_timeout`) bounds each
// individual blocking read syscall, but a fresh call gets a fresh window - so a peer that keeps
// the association alive by responding periodically (e.g. repeated pending C-MOVE-RSPs) can hold
// a read loop open indefinitely even though nothing is really progressing. `poll_bounded` below
// converts that per-syscall timeout into a genuine absolute ceiling for the whole operation by
// re-deriving each read's timeout from however much of a fixed deadline is left, so it can only
// ever shrink - never reset - as the operation runs.
// ---------------------------------------------------------------------------------------------

/// How often `poll_bounded` re-checks the deadline/stale-data watch/cancel signal while waiting
/// for a read that hasn't produced anything yet. Short enough that a 60s stale-data window (see
/// `StaleDataWatch`) gets several checks, and that an external `cancel` request (see
/// `CancelSignal`) - which a caller may now be synchronously awaiting the real completion of, via
/// `abort()`/`release()` on the napi handle - is noticed well under a second rather than up to the
/// old 5s tick; still long enough not to matter as syscall/CPU overhead at this call frequency.
const POLL_INTERVAL: Duration = Duration::from_millis(500);

/// True if `error`'s source chain bottoms out in an `io::Error` of kind `WouldBlock` or
/// `TimedOut` - i.e. this was just a `poll_bounded` tick finding nothing to read yet, not a real
/// failure. Walks the chain rather than matching a specific `DimseError`/`AssociationError`/
/// `ReadError` shape since a read timeout can surface wrapped in any of several dcmnorm-dimse
/// variants (`ReceivePdu`, `ReceivePduItem`, ...) depending on exactly where mid-PDU it landed.
fn is_read_timeout(error: &DimseError) -> bool {
    let mut current: &(dyn StdError + 'static) = error;
    loop {
        if let Some(io_error) = current.downcast_ref::<std::io::Error>() {
            return matches!(
                io_error.kind(),
                std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
            );
        }
        match current.source() {
            Some(source) => current = source,
            None => return false,
        }
    }
}

/// Watches a local directory's newest file mtime on behalf of a `move_scu` retrieve, so a
/// connection that's technically still alive (the peer keeps responding) but has stopped
/// actually writing new data to our own storage - e.g. a C-STORE receiver stalled downstream, or
/// a peer sending no-progress keepalive pending statuses - can be caught well before the
/// absolute deadline. `move_scu` has no other way to observe this: the instances a C-MOVE
/// retrieve causes to be written arrive over a *separate* inbound association this call has no
/// visibility into (see `MoveScuOptions::stale_data_path`), so this polls the filesystem instead.
struct StaleDataWatch {
    path: PathBuf,
    stale_after: Duration,
    last_progress_at: Instant,
    last_mtime: Option<std::time::SystemTime>,
}

impl StaleDataWatch {
    fn new(path: PathBuf, stale_after: Duration) -> Self {
        Self {
            path,
            stale_after,
            last_progress_at: Instant::now(),
            last_mtime: None,
        }
    }

    /// Newest mtime among the directory's files, or `None` if it doesn't exist yet (nothing has
    /// arrived at all) or is empty - either way, "no progress observed", not an error.
    fn newest_mtime(&self) -> Option<std::time::SystemTime> {
        std::fs::read_dir(&self.path)
            .ok()?
            .filter_map(|entry| entry.ok()?.metadata().ok()?.modified().ok())
            .max()
    }

    fn check(&mut self) -> Result<(), DimseError> {
        let newest = self.newest_mtime();
        if newest.is_some() && newest != self.last_mtime {
            self.last_mtime = newest;
            self.last_progress_at = Instant::now();
        }
        if self.last_progress_at.elapsed() >= self.stale_after {
            return Err(DimseError::StaleDataConnection {
                path: self.path.clone(),
            });
        }
        Ok(())
    }
}

/// Runs `op` (a `receive_command`/`read_pdata_to_end`-shaped blocking read), re-issuing it with
/// ever-shrinking read timeouts until it produces something other than a plain "nothing arrived
/// this tick" timeout. Between ticks, checks `deadline` (`AbsoluteTimeout` once passed),
/// `stale_watch` (`StaleDataConnection` once its window elapses), and `cancel` (`Cancelled` once
/// set) - any of the three aborts the wait immediately without another read attempt. A `deadline`
/// of `None` disables the absolute ceiling entirely (ticks stay at `POLL_INTERVAL`, matching
/// pre-existing behavior for callers that don't opt in).
fn poll_bounded<T>(
    assoc: &mut ClientAssociation<TcpStream>,
    deadline: Option<Instant>,
    mut stale_watch: Option<&mut StaleDataWatch>,
    cancel: Option<&CancelSignal>,
    mut op: impl FnMut(&mut ClientAssociation<TcpStream>) -> Result<T, DimseError>,
) -> Result<T, DimseError> {
    loop {
        if let Some(deadline) = deadline {
            if Instant::now() >= deadline {
                return Err(DimseError::AbsoluteTimeout);
            }
        }
        if let Some(watch) = stale_watch.as_mut() {
            watch.check()?;
        }
        if let Some(cancel) = cancel {
            if let Some(mode) = cancel.requested() {
                return Err(DimseError::Cancelled(mode));
            }
        }

        let tick = match deadline {
            Some(deadline) => POLL_INTERVAL
                .min(deadline.saturating_duration_since(Instant::now()))
                .max(Duration::from_millis(1)),
            None => POLL_INTERVAL,
        };
        assoc
            .inner_stream()
            .set_read_timeout(Some(tick))
            .map_err(DimseError::Io)?;

        match op(assoc) {
            Ok(value) => return Ok(value),
            Err(error) if is_read_timeout(&error) => continue,
            Err(error) => return Err(error),
        }
    }
}

fn command_status(command: &InMemDicomObject) -> Result<u16, DimseError> {
    command
        .element(tags::STATUS)
        .map_err(|error| DimseError::Protocol(format!("response is missing Status: {error}")))?
        .to_int::<u16>()
        .map_err(|error| DimseError::Protocol(format!("Status is not a valid integer: {error}")))
}

fn command_u16(command: &InMemDicomObject, tag: dcmnorm_core::Tag) -> u16 {
    command
        .element(tag)
        .ok()
        .and_then(|element| element.to_int::<u16>().ok())
        .unwrap_or(0)
}

/// Whether a received command's `CommandDataSetType` (PS3.7 E.2) says a data set follows it as
/// its own P-DATA-TF - `0x0101` means none, anything else (including the field being absent,
/// which shouldn't happen for a well-formed response but shouldn't be misread as "dataset
/// present" either) means one does.
fn command_has_dataset(command: &InMemDicomObject) -> bool {
    command
        .element(tags::COMMAND_DATA_SET_TYPE)
        .ok()
        .and_then(|element| element.to_int::<u16>().ok())
        .is_some_and(|value| value != 0x0101)
}

/// `0xFF00` ("pending, matches follow") and `0xFF01` ("pending, optional keys not supported")
/// are the two DICOM-defined pending statuses for C-FIND/C-MOVE responses - see PS3.7 C.4.
fn is_pending_status(status: u16) -> bool {
    status == 0xFF00 || status == 0xFF01
}

// ---------------------------------------------------------------------------------------------
// C-ECHO
// ---------------------------------------------------------------------------------------------

pub struct EchoScuOptions {
    pub calling_ae_title: String,
    pub called_ae_title: Option<String>,
    pub timeout: Option<Duration>,
    pub on_log: Option<Box<dyn DimseLogger>>,
    /// Lets an external caller interrupt an in-progress echo - see `MoveScuOptions.cancel` for
    /// the general shape. Unlike move, there's no "we already know the outcome" success case
    /// here: a cancelled echo is just `Err(DimseError::Cancelled(_))`, same as any other failure.
    pub cancel: Option<Arc<CancelSignal>>,
}

/// Performs a C-ECHO (DICOM Verification) against `destination` ("host:port"). Returns the
/// response Status code (0 = success) - callers decide what threshold counts as "up".
pub fn echo_scu(destination: &str, options: EchoScuOptions) -> Result<u16, DimseError> {
    let logger = options.on_log.as_deref();
    let deadline = options.timeout.map(|timeout| Instant::now() + timeout);
    let cancel = options.cancel.as_deref();
    let mut assoc = establish(
        destination,
        &options.calling_ae_title,
        options.called_ae_title.as_deref(),
        dcmnorm_dimse::pdu::DEFAULT_MAX_PDU,
        &[(uids::VERIFICATION.to_owned(), default_transfer_syntaxes())],
        options.timeout,
        logger,
    )?;

    let pc = assoc
        .presentation_contexts()
        .first()
        .cloned()
        .ok_or(DimseError::NoAcceptedPresentationContext)?;

    let command = InMemDicomObject::command_from_element_iter([
        DataElement::new(
            tags::AFFECTED_SOP_CLASS_UID,
            VR::UI,
            dicom_value!(Str, uids::VERIFICATION),
        ),
        DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x0030])),
        DataElement::new(tags::MESSAGE_ID, VR::US, dicom_value!(U16, [1])),
        DataElement::new(
            tags::COMMAND_DATA_SET_TYPE,
            VR::US,
            dicom_value!(U16, [0x0101]),
        ),
    ]);

    log_event(logger, || "sending C-ECHO-RQ (message id 1)".to_owned());
    let result = send_command(&mut assoc, pc.id, &command)
        .and_then(|_| poll_bounded(&mut assoc, deadline, None, cancel, receive_command));

    let response = match result {
        Ok(response) => response,
        Err(error) => {
            log_event(logger, || {
                format!("aborting association after error: {error}")
            });
            let _ = assoc.abort();
            return Err(error);
        }
    };

    let status = command_status(&response)?;
    log_event(logger, || {
        format!("received C-ECHO-RSP: status=0x{status:04X}")
    });
    release_and_log(assoc, logger, || "association released".to_owned());
    Ok(status)
}

// ---------------------------------------------------------------------------------------------
// C-STORE
// ---------------------------------------------------------------------------------------------

pub struct StoreScuOptions {
    pub calling_ae_title: String,
    pub called_ae_title: Option<String>,
    pub max_pdu_length: u32,
    /// When true, only the file's own transfer syntax is proposed - a peer that doesn't support
    /// it fails that file rather than receiving a transcoded copy.
    pub never_transcode: bool,
    /// Absolute ceiling for the whole call - connect through release - not reset by activity
    /// (see `poll_bounded`).
    pub timeout: Option<Duration>,
    pub on_log: Option<Box<dyn DimseLogger>>,
    /// Lets an external caller interrupt an in-progress send - see `MoveScuOptions.cancel` for
    /// the general shape. Unlike move, there's no "we already know the outcome" success case
    /// here: a cancelled send is just `Err(DimseError::Cancelled(_))`, same as any other failure.
    pub cancel: Option<Arc<CancelSignal>>,
}

#[derive(Clone, Debug)]
pub struct StoreScuResult {
    pub sop_instance_uid: String,
    pub status: u16,
}

struct StoreFile {
    path: PathBuf,
    sop_class_uid: String,
    sop_instance_uid: String,
    transfer_syntax_uid: String,
    /// True only when the file parsed strictly as Part 10 under its declared transfer syntax.
    /// Files recovered via `read_dicom_file`'s flexible decoder (e.g. Implicit VR dataset
    /// mislabeled Explicit VR in Group 0002, or meta-less files) must be serialized in the
    /// negotiated transfer syntax rather than raw-copied off disk.
    raw_part10_passthrough_ok: bool,
}

fn store_file_from_object(
    path: &Path,
    object: &dcmnorm_object::DefaultDicomObject,
    raw_part10_passthrough_ok: bool,
) -> StoreFile {
    let meta = object.meta();
    let dataset_uid = |tag| {
        object
            .element(tag)
            .ok()
            .and_then(|e| e.to_str().ok())
            .map(|s| s.trim_end_matches(['\0', ' ']).to_owned())
            .filter(|s| !s.is_empty())
    };
    let sop_class_uid = dataset_uid(tags::SOP_CLASS_UID).unwrap_or_else(|| {
        meta.media_storage_sop_class_uid
            .trim_end_matches(['\0', ' '])
            .to_owned()
    });
    let sop_instance_uid = dataset_uid(tags::SOP_INSTANCE_UID).unwrap_or_else(|| {
        meta.media_storage_sop_instance_uid
            .trim_end_matches(['\0', ' '])
            .to_owned()
    });
    let transfer_syntax_uid = meta
        .transfer_syntax
        .trim_end_matches(['\0', ' '])
        .to_owned();
    StoreFile {
        path: path.to_owned(),
        sop_class_uid,
        sop_instance_uid,
        transfer_syntax_uid,
        raw_part10_passthrough_ok,
    }
}

fn probe_store_file(path: &Path) -> Result<StoreFile, DimseError> {
    // Fast path for Part 10 files: read preamble + File Meta Information + dataset elements only
    // up to (0008,0018) (~400 bytes, never touching PixelData). Per DICOM PS3.7, C-STORE-RQ
    // AffectedSOPClassUID/AffectedSOPInstanceUID must come from dataset (0008,0016)/(0008,0018),
    // falling back to Group 0002 MediaStorageSOP*UID only when absent - real clinical/anonymized
    // Part 10 files frequently carry stale Group 0002 MediaStorageSOP*UID values.
    if let Ok(object) = OpenFileOptions::new()
        .read_preamble(ReadPreamble::Always)
        .read_until(dcmnorm_core::Tag(0x0008, 0x0019))
        .open_file(path)
    {
        return Ok(store_file_from_object(path, &object, true));
    }

    let object = read_dicom_file(path)?;
    Ok(store_file_from_object(path, &object, false))
}

/// Sends each of `files` via C-STORE to `destination` ("host:port"). Presentation contexts are
/// built from the actual files about to be sent: one context per distinct (SOP class, transfer
/// syntax) pair actually present among `files`, proposing only that single transfer syntax so an
/// acceptance is an exact match requiring no transcode at all. Unless `never_transcode`, each SOP
/// class also gets one shared fallback context offering Explicit/Implicit VR Little Endian (minus
/// whichever of those the class's files already cover natively) - the two transfer syntaxes this
/// build can always encode into, for peers that don't support a file's native compression.
///
/// Earlier versions of this function proposed each SOP class only once, seeded from whichever
/// file of that class happened to be probed first - if that file's native transfer syntax was
/// something this build can only decode (e.g. JPEG 2000, see [`can_encode_transfer_syntax`]), a
/// peer could accept it as the class's one negotiated transfer syntax, and any other file of that
/// class would then need an encode this build can't perform. Proposing one context per (class,
/// transfer syntax) pair means a peer can only negotiate a transfer syntax this build actually
/// has a file for - see [`select_store_presentation_context`] for how a decode-only accepted
/// context is avoided as a transcode fallback for a *different* file's send.
///
/// The fallback path still reuses dcmnorm's own [`transcode_dcmnorm_object`], which (via
/// openjpeg/kakadu/jpeg-ls/ffmpeg) can transcode a strictly wider set of source transfer syntaxes
/// than the storescu CLI's uncompressed-only fallback did.
///
/// Returns one [`StoreScuResult`] per file that could be probed and sent; only association-level
/// failure (can't connect, no acceptable presentation context at all) is a hard `Err` - a
/// per-file non-success Status is just data in the result, not a thrown error, since the caller
/// is in a better position to decide which statuses are retryable/fatal.
pub fn store_scu(
    destination: &str,
    files: &[PathBuf],
    options: StoreScuOptions,
) -> Result<Vec<StoreScuResult>, DimseError> {
    let logger = options.on_log.as_deref();
    let deadline = options.timeout.map(|timeout| Instant::now() + timeout);
    let cancel = options.cancel.as_deref();
    let probed: Vec<StoreFile> = files
        .iter()
        .filter_map(|path| probe_store_file(path).ok())
        .collect();
    if probed.is_empty() {
        return Err(DimseError::NoFilesToSend);
    }

    let mut presentation_contexts: Vec<(String, Vec<String>)> = Vec::new();
    let mut seen_pairs = std::collections::HashSet::new();
    let mut native_by_sop_class: HashMap<&str, std::collections::HashSet<&str>> = HashMap::new();

    for file in &probed {
        if seen_pairs.insert((
            file.sop_class_uid.as_str(),
            file.transfer_syntax_uid.as_str(),
        )) {
            presentation_contexts.push((
                file.sop_class_uid.clone(),
                vec![file.transfer_syntax_uid.clone()],
            ));
        }
        native_by_sop_class
            .entry(file.sop_class_uid.as_str())
            .or_default()
            .insert(file.transfer_syntax_uid.as_str());
    }

    if !options.never_transcode {
        for (sop_class_uid, native_transfer_syntaxes) in &native_by_sop_class {
            let fallback: Vec<String> = default_transfer_syntaxes()
                .into_iter()
                .filter(|ts| !native_transfer_syntaxes.contains(ts.as_str()))
                .collect();
            if !fallback.is_empty() {
                presentation_contexts.push(((*sop_class_uid).to_owned(), fallback));
            }
        }
    }

    let mut assoc = establish(
        destination,
        &options.calling_ae_title,
        options.called_ae_title.as_deref(),
        options.max_pdu_length,
        &presentation_contexts,
        options.timeout,
        logger,
    )?;

    let negotiated = assoc.presentation_contexts().to_vec();

    let mut results = Vec::with_capacity(probed.len());
    for (index, file) in probed.iter().enumerate() {
        let message_id = (index + 1) as u16;
        match send_and_receive_store(
            &mut assoc,
            file,
            &negotiated,
            message_id,
            deadline,
            cancel,
            logger,
        ) {
            Ok(status) => results.push(StoreScuResult {
                sop_instance_uid: file.sop_instance_uid.clone(),
                status,
            }),
            Err(error) => {
                log_event(logger, || {
                    format!(
                        "aborting association after error on {}: {error}",
                        file.sop_instance_uid
                    )
                });
                let _ = assoc.abort();
                return Err(error);
            }
        }
    }

    release_and_log(assoc, logger, || {
        format!("association released ({} instance(s) sent)", results.len())
    });
    Ok(results)
}

/// Picks which negotiated context to send `file` under: an exact (SOP class, transfer syntax)
/// match needs no transcode, so it's used whenever the peer accepted it. Otherwise, among
/// contexts negotiated for the same SOP class under a *different* transfer syntax, only one this
/// build can actually encode into is eligible - this is what keeps a peer's acceptance of another
/// file's decode-only native context (e.g. JPEG 2000) from being reused here as a transcode
/// target it can't reach; see [`store_scu`]'s doc comment for the failure this avoids.
fn select_store_presentation_context<'a>(
    file: &StoreFile,
    negotiated: &'a [PresentationContextNegotiated],
) -> Result<(&'a PresentationContextNegotiated, &'static TransferSyntax), DimseError> {
    let exact = negotiated.iter().find(|pc| {
        pc.abstract_syntax == file.sop_class_uid && pc.transfer_syntax == file.transfer_syntax_uid
    });
    if let Some(pc) = exact {
        return Ok((pc, transfer_syntax(&pc.transfer_syntax)?));
    }

    let fallback = negotiated
        .iter()
        .filter(|pc| pc.abstract_syntax == file.sop_class_uid)
        .find(|pc| can_encode_transfer_syntax(&pc.transfer_syntax));
    match fallback {
        Some(pc) => Ok((pc, transfer_syntax(&pc.transfer_syntax)?)),
        None => Err(DimseError::NoAcceptablePresentationContext {
            sop_class_uid: file.sop_class_uid.clone(),
            transfer_syntax_uid: file.transfer_syntax_uid.clone(),
        }),
    }
}

fn check_send_limits(
    deadline: Option<Instant>,
    cancel: Option<&CancelSignal>,
) -> Result<(), DimseError> {
    if let Some(deadline) = deadline {
        if Instant::now() >= deadline {
            return Err(DimseError::AbsoluteTimeout);
        }
    }
    if let Some(cancel) = cancel {
        if let Some(mode) = cancel.requested() {
            return Err(DimseError::Cancelled(mode));
        }
    }
    Ok(())
}

/// Wraps a `Write` sink (such as `PDataWriter`) to check `deadline` and `cancel` between chunks
/// during large C-STORE dataset sends, allowing the caller to abort the association cleanly
/// without emitting a final `is_last = true` PDV.
struct BoundedSendWriter<'a, W> {
    inner: &'a mut W,
    deadline: Option<Instant>,
    cancel: Option<&'a CancelSignal>,
    interrupted: Option<DimseError>,
}

impl<'a, W: std::io::Write> BoundedSendWriter<'a, W> {
    fn new(inner: &'a mut W, deadline: Option<Instant>, cancel: Option<&'a CancelSignal>) -> Self {
        Self {
            inner,
            deadline,
            cancel,
            interrupted: None,
        }
    }

    fn take_interrupted(&mut self) -> Option<DimseError> {
        self.interrupted.take()
    }
}

impl<W: std::io::Write> std::io::Write for BoundedSendWriter<'_, W> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        if let Err(err) = check_send_limits(self.deadline, self.cancel) {
            let msg = err.to_string();
            self.interrupted = Some(err);
            return Err(std::io::Error::other(msg));
        }
        self.inner.write(buf)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        if let Err(err) = check_send_limits(self.deadline, self.cancel) {
            let msg = err.to_string();
            self.interrupted = Some(err);
            return Err(std::io::Error::other(msg));
        }
        self.inner.flush()
    }
}

fn verify_store_object_matches_probed(
    object: &dcmnorm_object::DefaultDicomObject,
    expected: &StoreFile,
) -> Result<(), DimseError> {
    let actual = store_file_from_object(&expected.path, object, expected.raw_part10_passthrough_ok);
    if actual.sop_class_uid != expected.sop_class_uid
        || actual.sop_instance_uid != expected.sop_instance_uid
        || actual.transfer_syntax_uid != expected.transfer_syntax_uid
    {
        return Err(DimseError::Io(std::io::Error::other(format!(
            "file {} changed after probing before C-STORE send (expected SOP class/instance/TS {}/{}/{}, found {}/{}/{})",
            expected.path.display(),
            expected.sop_class_uid,
            expected.sop_instance_uid,
            expected.transfer_syntax_uid,
            actual.sop_class_uid,
            actual.sop_instance_uid,
            actual.transfer_syntax_uid,
        ))));
    }
    Ok(())
}

fn send_and_receive_store(
    assoc: &mut ClientAssociation<TcpStream>,
    file: &StoreFile,
    negotiated: &[PresentationContextNegotiated],
    message_id: u16,
    deadline: Option<Instant>,
    cancel: Option<&CancelSignal>,
    logger: Option<&dyn DimseLogger>,
) -> Result<u16, DimseError> {
    use std::io::{Read, Seek, SeekFrom};

    let (pc, target_ts) = select_store_presentation_context(file, negotiated)?;

    let command = InMemDicomObject::command_from_element_iter([
        DataElement::new(
            tags::AFFECTED_SOP_CLASS_UID,
            VR::UI,
            dicom_value!(Str, &file.sop_class_uid),
        ),
        DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x0001])),
        DataElement::new(tags::MESSAGE_ID, VR::US, dicom_value!(U16, [message_id])),
        DataElement::new(tags::PRIORITY, VR::US, dicom_value!(U16, [0x0000])),
        DataElement::new(
            tags::COMMAND_DATA_SET_TYPE,
            VR::US,
            dicom_value!(U16, [0x0000]),
        ),
        DataElement::new(
            tags::AFFECTED_SOP_INSTANCE_UID,
            VR::UI,
            dicom_value!(Str, &file.sop_instance_uid),
        ),
    ]);

    log_event(logger, || {
        format!(
            "sending C-STORE-RQ #{message_id}: SOP instance {} (class {}, transfer syntax {})",
            file.sop_instance_uid,
            file.sop_class_uid,
            target_ts.uid()
        )
    });

    check_send_limits(deadline, cancel)?;

    if target_ts.uid() == file.transfer_syntax_uid && file.raw_part10_passthrough_ok {
        // Exact transfer syntax match on a strict Part 10 file: open once, structurally validate
        // the full dataset (skipping PixelData in O(1) RAM) and re-verify SOP UIDs + transfer
        // syntax on this open descriptor before sending C-STORE-RQ, then stream the raw dataset
        // bytes straight from this same handle to PDataWriter.
        let mut raw_file = std::fs::File::open(&file.path)?;
        let file_len = raw_file.metadata()?.len();
        let validated = OpenFileOptions::new()
            .read_preamble(ReadPreamble::Always)
            .from_reader_deferring(
                std::io::BufReader::new(&mut raw_file),
                Some(file_len),
                &|h| {
                    h.tag != tags::SOP_CLASS_UID
                        && h.tag != tags::SOP_INSTANCE_UID
                        && h.tag != tags::SPECIFIC_CHARACTER_SET
                },
                true,
                false,
            )
            .map_err(|e| {
                DimseError::Io(std::io::Error::other(format!(
                    "validating {} before C-STORE send: {e}",
                    file.path.display()
                )))
            })?;
        let Some((validated_obj, _)) = validated else {
            // Either a dataset-compressed (deflated) file or a deferred element extending past
            // EOF: re-parse from this same open descriptor so truncated files error out before
            // C-STORE-RQ and deflated replacements still respect the negotiated transfer syntax.
            raw_file.seek(SeekFrom::Start(0))?;
            let object = OpenFileOptions::new()
                .read_preamble(ReadPreamble::Always)
                .from_reader(std::io::BufReader::new(&mut raw_file))
                .map_err(|e| {
                    DimseError::Io(std::io::Error::other(format!(
                        "validating {} before C-STORE send: {e}",
                        file.path.display()
                    )))
                })?;
            verify_store_object_matches_probed(&object, file)?;
            check_send_limits(deadline, cancel)?;
            send_command(assoc, pc.id, &command)?;
            let mut writer = assoc.send_pdata(pc.id);
            let mut bounded = BoundedSendWriter::new(&mut writer, deadline, cancel);
            if let Err(err) = object.write_dataset_with_ts(&mut bounded, target_ts) {
                if let Some(interrupted) = bounded.take_interrupted() {
                    return Err(interrupted);
                }
                return Err(err.into());
            }
            writer.finish()?;
            let response = poll_bounded(assoc, deadline, None, cancel, receive_command)?;
            let status = command_status(&response)?;
            log_event(logger, || {
                format!("received C-STORE-RSP #{message_id}: status=0x{status:04X}")
            });
            return Ok(status);
        };
        verify_store_object_matches_probed(&validated_obj, file)?;

        raw_file.seek(SeekFrom::Start(0))?;
        let mut buf_reader = std::io::BufReader::new(raw_file);
        let Some(_meta) = FileMetaTable::read_from(&mut buf_reader)? else {
            return Err(DimseError::Io(std::io::Error::other(format!(
                "file {} lost Part 10 File Meta Information before C-STORE send",
                file.path.display()
            ))));
        };
        let dataset_offset = buf_reader.stream_position()?;
        let dataset_len = file_len.saturating_sub(dataset_offset);
        let mut raw_file = buf_reader.into_inner();
        raw_file.seek(SeekFrom::Start(dataset_offset))?;

        check_send_limits(deadline, cancel)?;
        // Cap the combined single-PDU fast path at 64 KiB so a peer advertising unlimited
        // max PDU (0 -> u32::MAX) or a file growing concurrently never buffers a huge dataset.
        let single_pdu_limit = assoc
            .acceptor_max_pdu_length()
            .min(65_536)
            .saturating_sub(256) as u64;
        if dataset_len < single_pdu_limit {
            let mut data = Vec::with_capacity(dataset_len as usize);
            raw_file.by_ref().take(dataset_len).read_to_end(&mut data)?;
            if data.len() as u64 != dataset_len {
                return Err(DimseError::Io(std::io::Error::new(
                    std::io::ErrorKind::UnexpectedEof,
                    format!(
                        "file {} shrank before C-STORE send (expected {dataset_len} dataset bytes, read {})",
                        file.path.display(),
                        data.len()
                    ),
                )));
            }
            send_command_with_data(assoc, pc.id, &command, data)?;
        } else {
            send_command(assoc, pc.id, &command)?;
            let mut writer = assoc.send_pdata(pc.id);
            let mut bounded = BoundedSendWriter::new(&mut writer, deadline, cancel);
            let copied = match std::io::copy(&mut raw_file.by_ref().take(dataset_len), &mut bounded)
            {
                Ok(n) => n,
                Err(err) => {
                    if let Some(interrupted) = bounded.take_interrupted() {
                        return Err(interrupted);
                    }
                    return Err(err.into());
                }
            };
            if copied != dataset_len {
                return Err(DimseError::Io(std::io::Error::new(
                    std::io::ErrorKind::UnexpectedEof,
                    format!(
                        "file {} shrank during C-STORE send (expected {dataset_len} dataset bytes, sent {copied})",
                        file.path.display()
                    ),
                )));
            }
            writer.finish()?;
        }
    } else if target_ts.uid() == file.transfer_syntax_uid {
        // File required flexible recovery (e.g. Implicit-VR dataset mislabeled Explicit VR in
        // Group 0002, or meta-less dump): serialize it cleanly in the negotiated transfer syntax.
        let object = read_dicom_file(&file.path)?;
        verify_store_object_matches_probed(&object, file)?;
        check_send_limits(deadline, cancel)?;
        send_command(assoc, pc.id, &command)?;
        let mut writer = assoc.send_pdata(pc.id);
        let mut bounded = BoundedSendWriter::new(&mut writer, deadline, cancel);
        if let Err(err) = object.write_dataset_with_ts(&mut bounded, target_ts) {
            if let Some(interrupted) = bounded.take_interrupted() {
                return Err(interrupted);
            }
            return Err(err.into());
        }
        writer.finish()?;
    } else if let Some(prepared) = prepare_streaming_dataset_for_dimse(&file.path, target_ts.uid())?
    {
        // Streaming fallback transcode (e.g. compressed file -> Explicit/Implicit VR LE):
        // validates identity on the open handle before sending C-STORE-RQ, then streams decoded
        // frames directly into PDataWriter with bounded memory and no temp file.
        verify_store_object_matches_probed(prepared.object(), file)?;
        check_send_limits(deadline, cancel)?;
        send_command(assoc, pc.id, &command)?;
        let mut writer = assoc.send_pdata(pc.id);
        let mut bounded = BoundedSendWriter::new(&mut writer, deadline, cancel);
        if let Err(err) = prepared.write_to(&mut bounded) {
            if let Some(interrupted) = bounded.take_interrupted() {
                return Err(interrupted);
            }
            return Err(err.into());
        }
        writer.finish()?;
    } else {
        // Non-streamable fallback (e.g. deflated/MPEG/meta-less): transcode owned (no extra
        // deep clone) and stream the serialized dataset directly into PDataWriter instead of
        // allocating a full-dataset Vec<u8> copy.
        let object = read_dicom_file(&file.path)?;
        verify_store_object_matches_probed(&object, file)?;
        let object = transcode_dcmnorm_object_owned(object, target_ts.uid())?;
        check_send_limits(deadline, cancel)?;
        send_command(assoc, pc.id, &command)?;
        let mut writer = assoc.send_pdata(pc.id);
        let mut bounded = BoundedSendWriter::new(&mut writer, deadline, cancel);
        if let Err(err) = object.write_dataset_with_ts(&mut bounded, target_ts) {
            if let Some(interrupted) = bounded.take_interrupted() {
                return Err(interrupted);
            }
            return Err(err.into());
        }
        writer.finish()?;
    }

    let response = poll_bounded(assoc, deadline, None, cancel, receive_command)?;
    let status = command_status(&response)?;
    log_event(logger, || {
        format!("received C-STORE-RSP #{message_id}: status=0x{status:04X}")
    });
    Ok(status)
}

// ---------------------------------------------------------------------------------------------
// C-FIND
// ---------------------------------------------------------------------------------------------

pub struct FindScuOptions {
    pub calling_ae_title: String,
    pub called_ae_title: Option<String>,
    pub max_pdu_length: u32,
    /// Absolute ceiling for the whole call - connect through release - not reset by activity
    /// (see `poll_bounded`).
    pub timeout: Option<Duration>,
    pub on_log: Option<Box<dyn DimseLogger>>,
    /// Lets an external caller interrupt an in-progress query - see `MoveScuOptions.cancel` for
    /// the general shape. Unlike move, there's no "we already know the outcome" success case
    /// here: a cancelled query is just `Err(DimseError::Cancelled(_))`, same as any other failure.
    pub cancel: Option<Arc<CancelSignal>>,
}

fn put_query_attribute(
    identifier: &mut InMemDicomObject,
    key: &str,
    value: &str,
) -> Result<(), DimseError> {
    let tag = StandardDataDictionary
        .parse_tag(key)
        .ok_or_else(|| DimseError::InvalidQueryKey(key.to_owned()))?;
    let vr = StandardDataDictionary
        .by_tag(tag)
        .map(|entry| entry.vr().relaxed())
        .ok_or_else(|| DimseError::InvalidQueryKey(key.to_owned()))?;
    identifier.put_str(tag, vr, value.to_owned());
    Ok(())
}

/// Builds a C-FIND/C-MOVE Identifier dataset from `query` (tag keyword/hex -> value; an empty
/// value is a universal-match "return key", mirroring findscu's bare `-k TAG` vs `-k TAG=value`).
/// `QueryRetrieveLevel` defaults to `"STUDY"` when not present in `query`.
fn build_identifier(query: &HashMap<String, String>) -> Result<InMemDicomObject, DimseError> {
    let mut identifier = InMemDicomObject::new_empty();
    for (key, value) in query {
        put_query_attribute(&mut identifier, key, value)?;
    }
    if identifier.element(tags::QUERY_RETRIEVE_LEVEL).is_err() {
        put_query_attribute(&mut identifier, "QueryRetrieveLevel", "STUDY")?;
    }
    Ok(identifier)
}

/// Performs a C-FIND (Study Root Query/Retrieve) against `destination`, returning each matched
/// Identifier as flat/hex-keyed DICOM JSON (same shape as [`super::read_json`]'s default).
pub fn find_scu(
    destination: &str,
    query: &HashMap<String, String>,
    options: FindScuOptions,
) -> Result<Vec<String>, DimseError> {
    let logger = options.on_log.as_deref();
    let deadline = options.timeout.map(|timeout| Instant::now() + timeout);
    let cancel = options.cancel.as_deref();
    let abstract_syntax = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_FIND;

    let mut assoc = establish(
        destination,
        &options.calling_ae_title,
        options.called_ae_title.as_deref(),
        options.max_pdu_length,
        &[(abstract_syntax.to_owned(), default_transfer_syntaxes())],
        options.timeout,
        logger,
    )?;

    let pc = assoc
        .presentation_contexts()
        .first()
        .cloned()
        .ok_or(DimseError::NoAcceptedPresentationContext)?;
    let ts = transfer_syntax(&pc.transfer_syntax)?;

    let identifier = build_identifier(query)?;
    let mut identifier_data = Vec::with_capacity(128);
    identifier.write_dataset_with_ts(&mut identifier_data, ts)?;

    let command = InMemDicomObject::command_from_element_iter([
        DataElement::new(
            tags::AFFECTED_SOP_CLASS_UID,
            VR::UI,
            dicom_value!(Str, abstract_syntax),
        ),
        DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x0020])),
        DataElement::new(tags::MESSAGE_ID, VR::US, dicom_value!(U16, [1])),
        DataElement::new(tags::PRIORITY, VR::US, dicom_value!(U16, [0x0000])),
        DataElement::new(
            tags::COMMAND_DATA_SET_TYPE,
            VR::US,
            dicom_value!(U16, [0x0001]),
        ),
    ]);

    // Logs query key names only, not values - an Identifier commonly carries PHI (PatientName,
    // PatientID) that a debug log shouldn't echo even at the debug tier.
    log_event(logger, || {
        let mut keys: Vec<&str> = query.keys().map(String::as_str).collect();
        keys.sort_unstable();
        format!(
            "sending C-FIND-RQ (message id 1); query key(s): [{}]",
            keys.join(", ")
        )
    });

    if let Err(error) = send_command_with_data(&mut assoc, pc.id, &command, identifier_data) {
        log_event(logger, || {
            format!("aborting association after error: {error}")
        });
        let _ = assoc.abort();
        return Err(error);
    }

    let mut matches = Vec::new();
    loop {
        let response = match poll_bounded(&mut assoc, deadline, None, cancel, receive_command) {
            Ok(response) => response,
            Err(error) => {
                log_event(logger, || {
                    format!("aborting association after error: {error}")
                });
                let _ = assoc.abort();
                return Err(error);
            }
        };
        let status = match command_status(&response) {
            Ok(status) => status,
            Err(error) => {
                log_event(logger, || {
                    format!("aborting association after error: {error}")
                });
                let _ = assoc.abort();
                return Err(error);
            }
        };

        log_event(logger, || {
            format!("received C-FIND-RSP: status=0x{status:04X}")
        });

        if status == 0x0000 {
            break;
        }
        if !is_pending_status(status) {
            log_event(logger, || {
                format!("aborting association: C-FIND-RSP failed with status 0x{status:04X}")
            });
            let _ = assoc.abort();
            return Err(DimseError::Protocol(format!(
                "C-FIND-RSP failed with status {status:#06X}"
            )));
        }

        let bytes = match poll_bounded(&mut assoc, deadline, None, cancel, read_pdata_to_end) {
            Ok(bytes) => bytes,
            Err(error) => {
                log_event(logger, || {
                    format!("aborting association after error: {error}")
                });
                let _ = assoc.abort();
                return Err(error);
            }
        };
        let matched = InMemDicomObject::read_dataset_with_ts(bytes.as_slice(), ts)?;
        let json = write_dataset_as_dicom_json_with_options(
            matched,
            ts.uid(),
            DicomJsonWriteOptions {
                key_style: DicomJsonKeyStyle::Hex,
                format: DicomJsonFormat::Flat,
                ..Default::default()
            },
        )?;
        matches.push(json);
    }

    release_and_log(assoc, logger, || {
        format!("association released ({} match(es))", matches.len())
    });
    Ok(matches)
}

// ---------------------------------------------------------------------------------------------
// C-MOVE
// ---------------------------------------------------------------------------------------------

/// The level a C-MOVE retrieves at (PS3.4 C.4.2.1.4, Study Root model): the whole study, one
/// series of it, or a list of instances in one series. Parses from/prints as the DICOM
/// `QueryRetrieveLevel` code string (`"STUDY"`, `"SERIES"`, `"IMAGE"`), case-insensitively.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum QueryRetrieveLevel {
    #[default]
    Study,
    Series,
    Image,
}

impl QueryRetrieveLevel {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Study => "STUDY",
            Self::Series => "SERIES",
            Self::Image => "IMAGE",
        }
    }
}

impl fmt::Display for QueryRetrieveLevel {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl std::str::FromStr for QueryRetrieveLevel {
    type Err = DimseError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value.trim().to_ascii_uppercase().as_str() {
            "STUDY" => Ok(Self::Study),
            "SERIES" => Ok(Self::Series),
            "IMAGE" => Ok(Self::Image),
            _ => Err(DimseError::InvalidMoveIdentifier(format!(
                "unknown QueryRetrieveLevel '{value}' (expected STUDY, SERIES or IMAGE)"
            ))),
        }
    }
}

pub struct MoveScuOptions {
    pub calling_ae_title: String,
    pub called_ae_title: Option<String>,
    pub max_pdu_length: u32,
    /// Absolute ceiling for the whole call - connect through release - not reset by activity
    /// (see `poll_bounded`). A peer that keeps the association alive with periodic pending
    /// C-MOVE-RSPs but never actually finishes still gets cut off once this elapses.
    pub timeout: Option<Duration>,
    /// Directory to watch for local write progress (see `StaleDataWatch`) - typically this
    /// retrieve's own cache destination (`<cachepath>/S_<studyInstanceUid>`). Both this and
    /// `stale_data_timeout` must be set for the watch to run; `None` disables it.
    pub stale_data_path: Option<PathBuf>,
    /// How long `stale_data_path` may go without a new/modified file before the connection is
    /// considered stale and aborted - independent of, and typically much shorter than, `timeout`.
    pub stale_data_timeout: Option<Duration>,
    pub on_log: Option<Box<dyn DimseLogger>>,
    /// Lets an external caller interrupt an in-progress retrieve once it's independently
    /// confirmed the study already arrived (e.g. a source PACS that pushes the instances over
    /// their own C-STORE association but never sends a terminal C-MOVE-RSP nor releases this
    /// one) - checked each `poll_bounded` tick alongside `timeout`/`stale_data_timeout`. Setting
    /// it produces a successful, `cancelled: true` result (see `move_scu`), not an error, since
    /// cancellation only happens when the data is already known to be in hand.
    pub cancel: Option<Arc<CancelSignal>>,
    /// What to retrieve: `None`/`Study` moves the whole study (the Identifier is exactly
    /// `QueryRetrieveLevel=STUDY` + `StudyInstanceUID`, as before these options existed);
    /// `Series` adds `series_instance_uid`; `Image` adds it plus `sop_instance_uids`.
    pub query_retrieve_level: Option<QueryRetrieveLevel>,
    /// Required for `Series`/`Image` retrieves; ignored for `Study`.
    pub series_instance_uid: Option<String>,
    /// Required (non-empty) for `Image` retrieves, sent as one multi-valued `SOPInstanceUID`
    /// (PS3.4 C.4.2.2.1.2, List of UID Matching); ignored otherwise.
    pub sop_instance_uids: Vec<String>,
}

/// Loose UID syntax check for retrieve keys: 1-64 characters, digits and dots only. Deliberately
/// laxer than `consistency::is_valid_uid` (no leading-zero/empty-component rule) - the UIDs come
/// from the source PACS's own C-FIND answers, and refusing a slightly non-conformant one there
/// would make that series/instance unretrievable at all. What it does catch is what would corrupt
/// the Identifier: an empty value, a `\` (which would split one UID into several), padding or
/// any other stray character.
fn check_retrieve_uid(key: &str, uid: &str) -> Result<(), DimseError> {
    let well_formed = !uid.is_empty()
        && uid.len() <= 64
        && uid
            .bytes()
            .all(|byte| byte.is_ascii_digit() || byte == b'.');
    if well_formed {
        Ok(())
    } else {
        Err(DimseError::InvalidMoveIdentifier(format!(
            "{key} '{uid}' is not a valid UID"
        )))
    }
}

/// Builds the C-MOVE Identifier for `move_scu`. A `Study` retrieve's Identifier is byte-for-byte
/// what `move_scu` always sent (its UID isn't validated, as before); `Series`/`Image` add the
/// lower-level unique keys PS3.4 C.4.2.2.1 requires at that level, validated up front so a bad
/// option fails before any association is opened.
pub(super) fn build_move_identifier(
    study_instance_uid: &str,
    level: QueryRetrieveLevel,
    series_instance_uid: Option<&str>,
    sop_instance_uids: &[String],
) -> Result<InMemDicomObject, DimseError> {
    let mut identifier = InMemDicomObject::new_empty();
    put_query_attribute(&mut identifier, "QueryRetrieveLevel", level.as_str())?;
    put_query_attribute(&mut identifier, "StudyInstanceUID", study_instance_uid)?;
    if level == QueryRetrieveLevel::Study {
        return Ok(identifier);
    }

    check_retrieve_uid("StudyInstanceUID", study_instance_uid)?;
    let series_instance_uid = series_instance_uid
        .filter(|uid| !uid.is_empty())
        .ok_or_else(|| {
            DimseError::InvalidMoveIdentifier(format!(
                "a {level}-level retrieve needs a SeriesInstanceUID"
            ))
        })?;
    check_retrieve_uid("SeriesInstanceUID", series_instance_uid)?;
    put_query_attribute(&mut identifier, "SeriesInstanceUID", series_instance_uid)?;
    if level == QueryRetrieveLevel::Series {
        return Ok(identifier);
    }

    if sop_instance_uids.is_empty() {
        return Err(DimseError::InvalidMoveIdentifier(
            "an IMAGE-level retrieve needs at least one SOPInstanceUID".to_owned(),
        ));
    }
    for uid in sop_instance_uids {
        check_retrieve_uid("SOPInstanceUID", uid)?;
    }
    identifier.put(DataElement::new(
        tags::SOP_INSTANCE_UID,
        VR::UI,
        PrimitiveValue::Strs(sop_instance_uids.iter().cloned().collect()),
    ));
    Ok(identifier)
}

#[derive(Clone, Debug, Default)]
pub struct MoveScuResult {
    pub status: u16,
    pub completed: u16,
    pub failed: u16,
    pub warning: u16,
    pub remaining: u16,
    /// True when this result was produced by `options.cancel` firing rather than a terminal
    /// C-MOVE-RSP from the peer - the sub-operation counts above reflect the last pending
    /// response seen before cancellation, not a real terminal count.
    pub cancelled: bool,
    /// Which teardown verb actually produced `cancelled: true` - `None` when `cancelled` is
    /// `false` (a real terminal C-MOVE-RSP). Lets a caller/log line distinguish a graceful
    /// release from a hard abort instead of just seeing `cancelled: true` either way.
    pub cancelled_via: Option<CancelMode>,
}

/// Tears down `assoc` per the requested `mode` and builds the resulting `cancelled: true`
/// `MoveScuResult` - the shared tail of both `Cancelled` arms in `move_scu`'s response loop.
/// `Release` matches a normal successful terminal response's own teardown (a real A-RELEASE-RQ,
/// log-only on failure - see `release_and_log`). `Abort` sends A-ABORT and returns immediately
/// without waiting on the peer at all, for a caller that needs to be assured the association is
/// over as fast as possible rather than giving the peer a chance to ACK a clean release.
fn handle_move_cancelled(
    assoc: ClientAssociation<TcpStream>,
    logger: Option<&dyn DimseLogger>,
    mode: CancelMode,
    last_result: MoveScuResult,
) -> MoveScuResult {
    match mode {
        CancelMode::Release => {
            log_event(logger, || {
                "cancelled by caller - releasing association".to_owned()
            });
            release_and_log(assoc, logger, || {
                "association released after cancellation".to_owned()
            });
        }
        CancelMode::Abort => {
            log_event(logger, || {
                "cancelled by caller - aborting association".to_owned()
            });
            let _ = assoc.abort();
        }
    }
    MoveScuResult {
        cancelled: true,
        cancelled_via: Some(mode),
        status: 0,
        ..last_result
    }
}

/// Performs a C-MOVE (Study Root Query/Retrieve), asking `destination` to push
/// `study_instance_uid` - or, per `options.query_retrieve_level`, one series of it or a list of
/// its instances - to `move_destination_ae` (an AE title `destination` already knows how to
/// reach - not a socket address). Blocks until the move reaches a terminal status; returns the
/// terminal [`MoveScuResult`] regardless of whether it was success/warning/failure so the caller
/// can decide what's retryable, mirroring [`store_scu`]'s "return data, don't decide policy" shape.
pub fn move_scu(
    destination: &str,
    move_destination_ae: &str,
    study_instance_uid: &str,
    options: MoveScuOptions,
) -> Result<MoveScuResult, DimseError> {
    let level = options.query_retrieve_level.unwrap_or_default();
    let identifier = build_move_identifier(
        study_instance_uid,
        level,
        options.series_instance_uid.as_deref(),
        &options.sop_instance_uids,
    )?;
    let logger = options.on_log.as_deref();
    let deadline = options.timeout.map(|timeout| Instant::now() + timeout);
    let mut stale_watch = match (options.stale_data_path, options.stale_data_timeout) {
        (Some(path), Some(stale_after)) => Some(StaleDataWatch::new(path, stale_after)),
        _ => None,
    };
    let cancel = options.cancel.as_deref();
    let abstract_syntax = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_MOVE;

    let mut assoc = establish(
        destination,
        &options.calling_ae_title,
        options.called_ae_title.as_deref(),
        options.max_pdu_length,
        &[(abstract_syntax.to_owned(), default_transfer_syntaxes())],
        options.timeout,
        logger,
    )?;

    let pc = assoc
        .presentation_contexts()
        .first()
        .cloned()
        .ok_or(DimseError::NoAcceptedPresentationContext)?;
    let ts = transfer_syntax(&pc.transfer_syntax)?;

    let mut identifier_data = Vec::with_capacity(128);
    identifier.write_dataset_with_ts(&mut identifier_data, ts)?;

    let command = InMemDicomObject::command_from_element_iter([
        DataElement::new(
            tags::AFFECTED_SOP_CLASS_UID,
            VR::UI,
            dicom_value!(Str, abstract_syntax),
        ),
        DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x0021])),
        DataElement::new(tags::MESSAGE_ID, VR::US, dicom_value!(U16, [1])),
        DataElement::new(tags::PRIORITY, VR::US, dicom_value!(U16, [0x0000])),
        DataElement::new(
            tags::MOVE_DESTINATION,
            VR::AE,
            dicom_value!(Str, move_destination_ae),
        ),
        DataElement::new(
            tags::COMMAND_DATA_SET_TYPE,
            VR::US,
            dicom_value!(U16, [0x0001]),
        ),
    ]);

    log_event(logger, || {
        match level {
        QueryRetrieveLevel::Study => {
            format!("sending C-MOVE-RQ: study {study_instance_uid} -> move destination AE {move_destination_ae}")
        }
        QueryRetrieveLevel::Series => format!(
            "sending C-MOVE-RQ: study {study_instance_uid} series {} -> move destination AE {move_destination_ae}",
            options.series_instance_uid.as_deref().unwrap_or_default()
        ),
        QueryRetrieveLevel::Image => format!(
            "sending C-MOVE-RQ: study {study_instance_uid} series {} ({} instance(s)) -> move destination AE {move_destination_ae}",
            options.series_instance_uid.as_deref().unwrap_or_default(),
            options.sop_instance_uids.len()
        ),
    }
    });

    if let Err(error) = send_command_with_data(&mut assoc, pc.id, &command, identifier_data) {
        log_event(logger, || {
            format!("aborting association after error: {error}")
        });
        let _ = assoc.abort();
        return Err(error);
    }

    // Tracks the most recent pending C-MOVE-RSP's sub-operation counts so a cancellation (which,
    // unlike every other exit from this loop, isn't triggered by anything the peer sent) can
    // still report a meaningful `MoveScuResult` instead of an all-zero default.
    let mut last_result = MoveScuResult::default();

    loop {
        let response = match poll_bounded(
            &mut assoc,
            deadline,
            stale_watch.as_mut(),
            cancel,
            receive_command,
        ) {
            Ok(response) => response,
            Err(DimseError::Cancelled(mode)) => {
                return Ok(handle_move_cancelled(assoc, logger, mode, last_result));
            }
            Err(error) => {
                log_event(logger, || {
                    format!("aborting association after error: {error}")
                });
                let _ = assoc.abort();
                return Err(error);
            }
        };
        let status = match command_status(&response) {
            Ok(status) => status,
            Err(error) => {
                log_event(logger, || {
                    format!("aborting association after error: {error}")
                });
                let _ = assoc.abort();
                return Err(error);
            }
        };

        // PS3.7 Table 9.3-5: a C-MOVE-RSP with Failure/Warning/Cancel status may carry a Type 1C
        // Identifier (Failed SOP Instance UID List) as its own P-DATA-TF following the command -
        // some SCPs (e.g. RamSoft) send this even for a Failure that fails the whole study. If we
        // don't drain it here it's still sitting on the wire when `release()` next calls
        // `receive()` expecting A-RELEASE-RP, which dcmnorm-dimse then rejects as an unexpected PDU.
        if command_has_dataset(&response) {
            match poll_bounded(
                &mut assoc,
                deadline,
                stale_watch.as_mut(),
                cancel,
                read_pdata_to_end,
            ) {
                Ok(_) => {}
                Err(DimseError::Cancelled(mode)) => {
                    return Ok(handle_move_cancelled(assoc, logger, mode, last_result));
                }
                Err(error) => {
                    log_event(logger, || {
                        format!("aborting association after error: {error}")
                    });
                    let _ = assoc.abort();
                    return Err(error);
                }
            }
        }

        let result = MoveScuResult {
            status,
            completed: command_u16(&response, tags::NUMBER_OF_COMPLETED_SUBOPERATIONS),
            failed: command_u16(&response, tags::NUMBER_OF_FAILED_SUBOPERATIONS),
            warning: command_u16(&response, tags::NUMBER_OF_WARNING_SUBOPERATIONS),
            remaining: command_u16(&response, tags::NUMBER_OF_REMAINING_SUBOPERATIONS),
            cancelled: false,
            cancelled_via: None,
        };

        log_event(logger, || {
            format!(
                "received C-MOVE-RSP: status=0x{status:04X} completed={} failed={} warning={} remaining={}",
                result.completed, result.failed, result.warning, result.remaining
            )
        });

        last_result = result.clone();

        if is_pending_status(status) {
            continue;
        }

        release_and_log(assoc, logger, || "association released".to_owned());
        return Ok(result);
    }
}