pubmed-client 0.1.0

An async Rust client for PubMed and PMC APIs for retrieving biomedical research articles
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
use serde::{Deserialize, Serialize};

// Re-export common types
pub use crate::common::{Affiliation, Author};

/// Represents a PubMed article with metadata
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PubMedArticle {
    /// PubMed ID
    pub pmid: String,
    /// Article title
    pub title: String,
    /// List of authors with detailed metadata
    pub authors: Vec<Author>,
    /// Number of authors (computed from authors list)
    pub author_count: u32,
    /// Journal name
    pub journal: String,
    /// Publication date
    pub pub_date: String,
    /// DOI (Digital Object Identifier)
    pub doi: Option<String>,
    /// PMC ID if available (with PMC prefix, e.g., "PMC7092803")
    pub pmc_id: Option<String>,
    /// Abstract text (if available)
    pub abstract_text: Option<String>,
    /// Article types (e.g., "Clinical Trial", "Review", etc.)
    pub article_types: Vec<String>,
    /// MeSH headings associated with the article
    pub mesh_headings: Option<Vec<MeshHeading>>,
    /// Author-provided keywords
    pub keywords: Option<Vec<String>>,
    /// Chemical substances mentioned in the article
    pub chemical_list: Option<Vec<ChemicalConcept>>,
    /// Journal volume (e.g., "88")
    pub volume: Option<String>,
    /// Journal issue number (e.g., "3")
    pub issue: Option<String>,
    /// Page range (e.g., "123-130")
    pub pages: Option<String>,
    /// Article language (e.g., "eng", "jpn")
    pub language: Option<String>,
    /// ISO journal abbreviation (e.g., "J Biol Chem")
    pub journal_abbreviation: Option<String>,
    /// ISSN (International Standard Serial Number)
    pub issn: Option<String>,
}

/// Database information from EInfo API
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DatabaseInfo {
    /// Database name (e.g., "pubmed", "pmc")
    pub name: String,
    /// Human-readable menu name
    pub menu_name: String,
    /// Database description
    pub description: String,
    /// Database build version
    pub build: Option<String>,
    /// Number of records in database
    pub count: Option<u64>,
    /// Last update timestamp
    pub last_update: Option<String>,
    /// Available search fields
    pub fields: Vec<FieldInfo>,
    /// Available links to other databases
    pub links: Vec<LinkInfo>,
}

/// Information about a database search field
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FieldInfo {
    /// Short field name (e.g., "titl", "auth")
    pub name: String,
    /// Full field name (e.g., "Title", "Author")
    pub full_name: String,
    /// Field description
    pub description: String,
    /// Number of indexed terms
    pub term_count: Option<u64>,
    /// Whether field contains dates
    pub is_date: bool,
    /// Whether field contains numerical values
    pub is_numerical: bool,
    /// Whether field uses single token indexing
    pub single_token: bool,
    /// Whether field uses hierarchical indexing
    pub hierarchy: bool,
    /// Whether field is hidden from users
    pub is_hidden: bool,
}

/// Information about database links
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct LinkInfo {
    /// Link name
    pub name: String,
    /// Menu display name
    pub menu: String,
    /// Link description
    pub description: String,
    /// Target database
    pub target_db: String,
}

/// Results from ELink API for related article discovery
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct RelatedArticles {
    /// Source PMIDs that were queried
    pub source_pmids: Vec<u32>,
    /// Related article PMIDs found
    pub related_pmids: Vec<u32>,
    /// Link type (e.g., "pubmed_pubmed", "pubmed_pubmed_reviews")
    pub link_type: String,
}

/// PMC links discovered through ELink API
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PmcLinks {
    /// Source PMIDs that were queried
    pub source_pmids: Vec<u32>,
    /// PMC IDs that have full text available
    pub pmc_ids: Vec<String>,
}

/// Citation information from ELink API
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Citations {
    /// Source PMIDs that were queried
    pub source_pmids: Vec<u32>,
    /// PMIDs of articles that cite the source articles
    pub citing_pmids: Vec<u32>,
    /// Link type (e.g., "pubmed_pubmed_citedin")
    pub link_type: String,
}

/// Search result with WebEnv session information for history server pagination
#[derive(Debug, Clone)]
pub struct SearchResult {
    /// List of PMIDs matching the search query
    pub pmids: Vec<String>,
    /// Total number of results matching the query
    pub total_count: usize,
    /// WebEnv session identifier for history server
    pub webenv: Option<String>,
    /// Query key for history server
    pub query_key: Option<String>,
    /// How PubMed interpreted and translated the search query
    ///
    /// For example, searching "asthma" might be translated to:
    /// `"asthma"[MeSH Terms] OR "asthma"[All Fields]`
    ///
    /// This is useful for debugging search queries and understanding
    /// how PubMed's automatic term mapping works.
    pub query_translation: Option<String>,
}

impl SearchResult {
    /// Get the history session if WebEnv and query_key are available
    ///
    /// Returns `Some(HistorySession)` if both webenv and query_key are present,
    /// `None` otherwise.
    pub fn history_session(&self) -> Option<HistorySession> {
        match (&self.webenv, &self.query_key) {
            (Some(webenv), Some(query_key)) => Some(HistorySession {
                webenv: webenv.clone(),
                query_key: query_key.clone(),
            }),
            _ => None,
        }
    }

    /// Check if this result has history session information
    pub fn has_history(&self) -> bool {
        self.webenv.is_some() && self.query_key.is_some()
    }
}

/// History server session information for paginated fetching
///
/// This represents a session on NCBI's history server that can be used
/// to efficiently fetch large result sets in batches without re-running
/// the search query.
///
/// # Note
///
/// WebEnv sessions typically expire after 1 hour of inactivity.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistorySession {
    /// WebEnv session identifier
    pub webenv: String,
    /// Query key within the session
    pub query_key: String,
}

/// Medical Subject Heading (MeSH) qualifier/subheading
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MeshQualifier {
    /// Qualifier name (e.g., "drug therapy", "genetics")
    pub qualifier_name: String,
    /// Unique identifier for the qualifier
    pub qualifier_ui: String,
    /// Whether this qualifier is a major topic
    pub major_topic: bool,
}

/// Medical Subject Heading (MeSH) descriptor term
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MeshTerm {
    /// Descriptor name (e.g., "Diabetes Mellitus, Type 2")
    pub descriptor_name: String,
    /// Unique identifier for the descriptor
    pub descriptor_ui: String,
    /// Whether this term is a major topic of the article
    pub major_topic: bool,
    /// Associated qualifiers/subheadings
    pub qualifiers: Vec<MeshQualifier>,
}

/// Supplemental MeSH concept (for substances, diseases, etc.)
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SupplementalConcept {
    /// Concept name
    pub name: String,
    /// Unique identifier
    pub ui: String,
    /// Concept type (e.g., "Disease", "Drug")
    pub concept_type: Option<String>,
}

/// Chemical substance mentioned in the article
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ChemicalConcept {
    /// Chemical name
    pub name: String,
    /// Registry number (e.g., CAS number)
    pub registry_number: Option<String>,
    /// Chemical UI
    pub ui: Option<String>,
}

/// Complete MeSH heading information for an article
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MeshHeading {
    /// MeSH descriptor terms
    pub mesh_terms: Vec<MeshTerm>,
    /// Supplemental concepts
    pub supplemental_concepts: Vec<SupplementalConcept>,
}

impl PubMedArticle {
    /// Get all major MeSH terms from the article
    ///
    /// # Returns
    ///
    /// A vector of major MeSH term names
    ///
    /// # Example
    ///
    /// ```
    /// # use pubmed_client_rs::pubmed::PubMedArticle;
    /// # let article = PubMedArticle {
    /// #     pmid: "123".to_string(),
    /// #     title: "Test".to_string(),
    /// #     authors: vec![],
    /// #     author_count: 0,
    /// #     journal: "Test Journal".to_string(),
    /// #     pub_date: "2023".to_string(),
    /// #     doi: None,
    /// #     abstract_text: None,
    /// #     article_types: vec![],
    /// #     mesh_headings: None,
    /// #     keywords: None,
    /// #     chemical_list: None,
    /// #     volume: None, issue: None, pages: None,
    /// #     language: None, journal_abbreviation: None, issn: None,
    /// # };
    /// let major_terms = article.get_major_mesh_terms();
    /// ```
    pub fn get_major_mesh_terms(&self) -> Vec<String> {
        let mut major_terms = Vec::new();

        if let Some(mesh_headings) = &self.mesh_headings {
            for heading in mesh_headings {
                for term in &heading.mesh_terms {
                    if term.major_topic {
                        major_terms.push(term.descriptor_name.clone());
                    }
                }
            }
        }

        major_terms
    }

    /// Check if the article has a specific MeSH term
    ///
    /// # Arguments
    ///
    /// * `term` - The MeSH term to check for
    ///
    /// # Returns
    ///
    /// `true` if the article has the specified MeSH term, `false` otherwise
    ///
    /// # Example
    ///
    /// ```
    /// # use pubmed_client_rs::pubmed::PubMedArticle;
    /// # let article = PubMedArticle {
    /// #     pmid: "123".to_string(),
    /// #     title: "Test".to_string(),
    /// #     authors: vec![],
    /// #     author_count: 0,
    /// #     journal: "Test Journal".to_string(),
    /// #     pub_date: "2023".to_string(),
    /// #     doi: None,
    /// #     abstract_text: None,
    /// #     article_types: vec![],
    /// #     mesh_headings: None,
    /// #     keywords: None,
    /// #     chemical_list: None,
    /// #     volume: None, issue: None, pages: None,
    /// #     language: None, journal_abbreviation: None, issn: None,
    /// # };
    /// let has_diabetes = article.has_mesh_term("Diabetes Mellitus");
    /// ```
    pub fn has_mesh_term(&self, term: &str) -> bool {
        if let Some(mesh_headings) = &self.mesh_headings {
            for heading in mesh_headings {
                for mesh_term in &heading.mesh_terms {
                    if mesh_term.descriptor_name.eq_ignore_ascii_case(term) {
                        return true;
                    }
                }
            }
        }
        false
    }

    /// Get all MeSH terms from the article
    ///
    /// # Returns
    ///
    /// A vector of all MeSH term names
    pub fn get_all_mesh_terms(&self) -> Vec<String> {
        let mut terms = Vec::new();

        if let Some(mesh_headings) = &self.mesh_headings {
            for heading in mesh_headings {
                for term in &heading.mesh_terms {
                    terms.push(term.descriptor_name.clone());
                }
            }
        }

        terms
    }

    /// Get corresponding authors from the article
    ///
    /// # Returns
    ///
    /// A vector of references to authors marked as corresponding
    pub fn get_corresponding_authors(&self) -> Vec<&Author> {
        self.authors
            .iter()
            .filter(|author| author.is_corresponding)
            .collect()
    }

    /// Get authors affiliated with a specific institution
    ///
    /// # Arguments
    ///
    /// * `institution` - Institution name to search for (case-insensitive substring match)
    ///
    /// # Returns
    ///
    /// A vector of references to authors with matching affiliations
    pub fn get_authors_by_institution(&self, institution: &str) -> Vec<&Author> {
        let institution_lower = institution.to_lowercase();
        self.authors
            .iter()
            .filter(|author| {
                author.affiliations.iter().any(|affil| {
                    affil
                        .institution
                        .as_ref()
                        .is_some_and(|inst| inst.to_lowercase().contains(&institution_lower))
                })
            })
            .collect()
    }

    /// Get all unique countries from author affiliations
    ///
    /// # Returns
    ///
    /// A vector of unique country names
    pub fn get_author_countries(&self) -> Vec<String> {
        use std::collections::HashSet;
        let mut countries: HashSet<String> = HashSet::new();

        for author in &self.authors {
            for affiliation in &author.affiliations {
                if let Some(country) = &affiliation.country {
                    countries.insert(country.clone());
                }
            }
        }

        countries.into_iter().collect()
    }

    /// Get authors with ORCID identifiers
    ///
    /// # Returns
    ///
    /// A vector of references to authors who have ORCID IDs
    pub fn get_authors_with_orcid(&self) -> Vec<&Author> {
        self.authors
            .iter()
            .filter(|author| author.orcid.is_some())
            .collect()
    }

    /// Check if the article has international collaboration
    ///
    /// # Returns
    ///
    /// `true` if authors are from multiple countries
    pub fn has_international_collaboration(&self) -> bool {
        self.get_author_countries().len() > 1
    }

    /// Calculate MeSH term similarity between two articles
    ///
    /// # Arguments
    ///
    /// * `other` - The other article to compare with
    ///
    /// # Returns
    ///
    /// A similarity score between 0.0 and 1.0 based on Jaccard similarity
    ///
    /// # Example
    ///
    /// ```
    /// # use pubmed_client_rs::pubmed::PubMedArticle;
    /// # let article1 = PubMedArticle {
    /// #     pmid: "123".to_string(),
    /// #     title: "Test".to_string(),
    /// #     authors: vec![],
    /// #     author_count: 0,
    /// #     journal: "Test Journal".to_string(),
    /// #     pub_date: "2023".to_string(),
    /// #     doi: None,
    /// #     abstract_text: None,
    /// #     article_types: vec![],
    /// #     mesh_headings: None,
    /// #     keywords: None,
    /// #     chemical_list: None,
    /// #     volume: None, issue: None, pages: None,
    /// #     language: None, journal_abbreviation: None, issn: None,
    /// # };
    /// # let article2 = article1.clone();
    /// let similarity = article1.mesh_term_similarity(&article2);
    /// ```
    pub fn mesh_term_similarity(&self, other: &PubMedArticle) -> f64 {
        use std::collections::HashSet;

        let terms1: HashSet<String> = self
            .get_all_mesh_terms()
            .into_iter()
            .map(|t| t.to_lowercase())
            .collect();

        let terms2: HashSet<String> = other
            .get_all_mesh_terms()
            .into_iter()
            .map(|t| t.to_lowercase())
            .collect();

        if terms1.is_empty() && terms2.is_empty() {
            return 0.0;
        }

        let intersection = terms1.intersection(&terms2).count();
        let union = terms1.union(&terms2).count();

        if union == 0 {
            0.0
        } else {
            intersection as f64 / union as f64
        }
    }

    /// Get MeSH qualifiers for a specific term
    ///
    /// # Arguments
    ///
    /// * `term` - The MeSH term to get qualifiers for
    ///
    /// # Returns
    ///
    /// A vector of qualifier names for the specified term
    pub fn get_mesh_qualifiers(&self, term: &str) -> Vec<String> {
        let mut qualifiers = Vec::new();

        if let Some(mesh_headings) = &self.mesh_headings {
            for heading in mesh_headings {
                for mesh_term in &heading.mesh_terms {
                    if mesh_term.descriptor_name.eq_ignore_ascii_case(term) {
                        for qualifier in &mesh_term.qualifiers {
                            qualifiers.push(qualifier.qualifier_name.clone());
                        }
                    }
                }
            }
        }

        qualifiers
    }

    /// Check if the article has any MeSH terms
    ///
    /// # Returns
    ///
    /// `true` if the article has MeSH terms, `false` otherwise
    pub fn has_mesh_terms(&self) -> bool {
        self.mesh_headings
            .as_ref()
            .map(|h| !h.is_empty())
            .unwrap_or(false)
    }

    /// Get chemicals mentioned in the article
    ///
    /// # Returns
    ///
    /// A vector of chemical names
    pub fn get_chemical_names(&self) -> Vec<String> {
        self.chemical_list
            .as_ref()
            .map(|chemicals| chemicals.iter().map(|c| c.name.clone()).collect())
            .unwrap_or_default()
    }
}

// ================================================================================================
// ESpell API types
// ================================================================================================

/// Represents a segment of the spelled query from the ESpell API
///
/// Each segment is either an original (unchanged) part of the query or a
/// replacement (corrected spelling suggestion).
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub enum SpelledQuerySegment {
    /// A term or separator that was not changed
    Original(String),
    /// A corrected/suggested replacement term
    Replaced(String),
}

/// Result from the ESpell API providing spelling suggestions
///
/// ESpell provides spelling suggestions for terms within a single text query
/// in a given database. It acts as a preprocessing/spell-check tool to improve
/// search accuracy before executing actual searches.
///
/// # Example
///
/// ```no_run
/// use pubmed_client_rs::PubMedClient;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let client = PubMedClient::new();
///     let result = client.spell_check("asthmaa OR alergies").await?;
///     println!("Original: {}", result.query);
///     println!("Corrected: {}", result.corrected_query);
///     Ok(())
/// }
/// ```
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SpellCheckResult {
    /// The database that was queried
    pub database: String,
    /// The original query string as submitted
    pub query: String,
    /// The full corrected/suggested query as a plain string
    pub corrected_query: String,
    /// Detailed segments showing which terms were replaced vs. kept
    pub spelled_query: Vec<SpelledQuerySegment>,
}

impl SpellCheckResult {
    /// Check if the query had any spelling corrections
    pub fn has_corrections(&self) -> bool {
        self.query != self.corrected_query
    }

    /// Get only the replaced (corrected) terms
    pub fn replacements(&self) -> Vec<&str> {
        self.spelled_query
            .iter()
            .filter_map(|segment| match segment {
                SpelledQuerySegment::Replaced(s) => Some(s.as_str()),
                SpelledQuerySegment::Original(_) => None,
            })
            .collect()
    }
}

// ================================================================================================
// ECitMatch API types
// ================================================================================================

/// Input for a single citation match query
///
/// Used with the ECitMatch API to find PMIDs from citation information.
/// Each field corresponds to a part of the citation string sent to the API.
///
/// # Example
///
/// ```
/// use pubmed_client_rs::pubmed::CitationQuery;
///
/// let query = CitationQuery::new(
///     "proc natl acad sci u s a",
///     "1991",
///     "88",
///     "3248",
///     "mann bj",
///     "Art1",
/// );
/// ```
#[derive(Debug, Clone)]
pub struct CitationQuery {
    /// Journal title abbreviation (e.g., "proc natl acad sci u s a")
    pub journal: String,
    /// Publication year (e.g., "1991")
    pub year: String,
    /// Volume number (e.g., "88")
    pub volume: String,
    /// First page number (e.g., "3248")
    pub first_page: String,
    /// Author name (e.g., "mann bj")
    pub author_name: String,
    /// User-defined key for identifying results (e.g., "Art1")
    pub key: String,
}

impl CitationQuery {
    /// Create a new citation query
    pub fn new(
        journal: &str,
        year: &str,
        volume: &str,
        first_page: &str,
        author_name: &str,
        key: &str,
    ) -> Self {
        Self {
            journal: journal.to_string(),
            year: year.to_string(),
            volume: volume.to_string(),
            first_page: first_page.to_string(),
            author_name: author_name.to_string(),
            key: key.to_string(),
        }
    }

    /// Format this citation as a bdata string for the ECitMatch API
    pub(crate) fn to_bdata(&self) -> String {
        format!(
            "{}|{}|{}|{}|{}|{}|",
            self.journal.replace(' ', "+"),
            self.year,
            self.volume,
            self.first_page,
            self.author_name.replace(' ', "+"),
            self.key,
        )
    }
}

/// Status of a citation match result
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub enum CitationMatchStatus {
    /// A unique PMID was found for the citation
    Found,
    /// No PMID could be found for the citation
    NotFound,
    /// Multiple PMIDs matched the citation (ambiguous)
    Ambiguous,
}

/// Result of a single citation match from the ECitMatch API
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CitationMatch {
    /// Journal title from the query
    pub journal: String,
    /// Year from the query
    pub year: String,
    /// Volume from the query
    pub volume: String,
    /// First page from the query
    pub first_page: String,
    /// Author name from the query
    pub author_name: String,
    /// User-defined key from the query
    pub key: String,
    /// Matched PMID (if found)
    pub pmid: Option<String>,
    /// Match status
    pub status: CitationMatchStatus,
}

/// Results from ECitMatch API for batch citation matching
///
/// Contains the results of matching multiple citations to PMIDs.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CitationMatches {
    /// List of citation match results
    pub matches: Vec<CitationMatch>,
}

impl CitationMatches {
    /// Get only the successfully matched citations
    pub fn found(&self) -> Vec<&CitationMatch> {
        self.matches
            .iter()
            .filter(|m| m.status == CitationMatchStatus::Found)
            .collect()
    }

    /// Get the number of successful matches
    pub fn found_count(&self) -> usize {
        self.matches
            .iter()
            .filter(|m| m.status == CitationMatchStatus::Found)
            .count()
    }
}

// ================================================================================================
// EGQuery API types
// ================================================================================================

/// Record count for a single NCBI database from the EGQuery API
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DatabaseCount {
    /// Internal database name (e.g., "pubmed", "pmc", "nuccore")
    pub db_name: String,
    /// Human-readable database name (e.g., "PubMed", "PMC", "Nucleotide")
    pub menu_name: String,
    /// Number of records matching the query in this database
    pub count: u64,
    /// Status of the query for this database (e.g., "Ok")
    pub status: String,
}

/// Results from EGQuery API for global database search
///
/// Contains the number of records matching a query across all NCBI Entrez databases.
///
/// # Example
///
/// ```no_run
/// use pubmed_client_rs::PubMedClient;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let client = PubMedClient::new();
///     let results = client.global_query("asthma").await?;
///     for db in &results.results {
///         if db.count > 0 {
///             println!("{}: {} records", db.menu_name, db.count);
///         }
///     }
///     Ok(())
/// }
/// ```
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GlobalQueryResults {
    /// The query term that was searched
    pub term: String,
    /// Results for each NCBI database
    pub results: Vec<DatabaseCount>,
}

impl GlobalQueryResults {
    /// Get results for databases with matching records (count > 0)
    pub fn non_zero(&self) -> Vec<&DatabaseCount> {
        self.results.iter().filter(|r| r.count > 0).collect()
    }

    /// Get the count for a specific database
    pub fn count_for(&self, db_name: &str) -> Option<u64> {
        self.results
            .iter()
            .find(|r| r.db_name == db_name)
            .map(|r| r.count)
    }
}

// ================================================================================================
// ESummary API types
// ================================================================================================

/// Lightweight article summary from the ESummary API
///
/// Contains basic metadata (title, authors, journal, dates) without the full
/// abstract, MeSH terms, or chemical lists that EFetch provides. Use this when
/// you only need basic bibliographic information for a large number of articles.
///
/// # Example
///
/// ```no_run
/// use pubmed_client_rs::PubMedClient;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let client = PubMedClient::new();
///     let summaries = client.fetch_summaries(&["31978945", "33515491"]).await?;
///     for summary in &summaries {
///         println!("{}: {} ({})", summary.pmid, summary.title, summary.pub_date);
///     }
///     Ok(())
/// }
/// ```
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ArticleSummary {
    /// PubMed ID
    pub pmid: String,
    /// Article title
    pub title: String,
    /// Author names (e.g., ["Zhu N", "Zhang D", "Wang W"])
    pub authors: Vec<String>,
    /// Journal name (source field)
    pub journal: String,
    /// Full journal name (e.g., "The New England journal of medicine")
    pub full_journal_name: String,
    /// Publication date (e.g., "2020 Feb")
    pub pub_date: String,
    /// Electronic publication date (e.g., "2020 Jan 24")
    pub epub_date: String,
    /// DOI (Digital Object Identifier)
    pub doi: Option<String>,
    /// PMC ID if available (e.g., "PMC7092803")
    pub pmc_id: Option<String>,
    /// Journal volume (e.g., "382")
    pub volume: String,
    /// Journal issue (e.g., "8")
    pub issue: String,
    /// Page range (e.g., "727-733")
    pub pages: String,
    /// Languages (e.g., ["eng"])
    pub languages: Vec<String>,
    /// Publication types (e.g., ["Journal Article", "Review"])
    pub pub_types: Vec<String>,
    /// ISSN
    pub issn: String,
    /// Electronic ISSN
    pub essn: String,
    /// Sorted publication date (e.g., "2020/02/20 00:00")
    pub sort_pub_date: String,
    /// PMC reference count (number of citing articles in PMC)
    pub pmc_ref_count: u64,
    /// Record status (e.g., "PubMed - indexed for MEDLINE")
    pub record_status: String,
}

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

    fn create_test_author() -> Author {
        Author {
            surname: Some("Doe".to_string()),
            given_names: Some("John A".to_string()),
            initials: Some("JA".to_string()),
            suffix: None,
            full_name: "John A Doe".to_string(),
            affiliations: vec![
                Affiliation {
                    id: None,
                    institution: Some("Harvard Medical School".to_string()),
                    department: Some("Department of Medicine".to_string()),
                    address: Some("Boston, MA".to_string()),
                    country: Some("USA".to_string()),
                },
                Affiliation {
                    id: None,
                    institution: Some("Massachusetts General Hospital".to_string()),
                    department: None,
                    address: Some("Boston, MA".to_string()),
                    country: Some("USA".to_string()),
                },
            ],
            orcid: Some("0000-0001-2345-6789".to_string()),
            email: Some("john.doe@hms.harvard.edu".to_string()),
            is_corresponding: true,
            roles: vec![
                "Conceptualization".to_string(),
                "Writing - original draft".to_string(),
            ],
        }
    }

    fn create_test_article_with_mesh() -> PubMedArticle {
        PubMedArticle {
            pmid: "12345".to_string(),
            title: "Test Article".to_string(),
            authors: vec![create_test_author()],
            author_count: 1,
            journal: "Test Journal".to_string(),
            pub_date: "2023".to_string(),
            doi: None,
            pmc_id: None,
            abstract_text: None,
            article_types: vec![],
            mesh_headings: Some(vec![
                MeshHeading {
                    mesh_terms: vec![MeshTerm {
                        descriptor_name: "Diabetes Mellitus, Type 2".to_string(),
                        descriptor_ui: "D003924".to_string(),
                        major_topic: true,
                        qualifiers: vec![
                            MeshQualifier {
                                qualifier_name: "drug therapy".to_string(),
                                qualifier_ui: "Q000188".to_string(),
                                major_topic: false,
                            },
                            MeshQualifier {
                                qualifier_name: "genetics".to_string(),
                                qualifier_ui: "Q000235".to_string(),
                                major_topic: true,
                            },
                        ],
                    }],
                    supplemental_concepts: vec![],
                },
                MeshHeading {
                    mesh_terms: vec![MeshTerm {
                        descriptor_name: "Hypertension".to_string(),
                        descriptor_ui: "D006973".to_string(),
                        major_topic: false,
                        qualifiers: vec![],
                    }],
                    supplemental_concepts: vec![],
                },
            ]),
            keywords: Some(vec!["diabetes".to_string(), "treatment".to_string()]),
            chemical_list: Some(vec![ChemicalConcept {
                name: "Metformin".to_string(),
                registry_number: Some("657-24-9".to_string()),
                ui: Some("D008687".to_string()),
            }]),
            volume: Some("45".to_string()),
            issue: Some("3".to_string()),
            pages: Some("123-130".to_string()),
            language: Some("eng".to_string()),
            journal_abbreviation: Some("Test J".to_string()),
            issn: Some("1234-5678".to_string()),
        }
    }

    #[test]
    fn test_get_major_mesh_terms() {
        let article = create_test_article_with_mesh();
        let major_terms = article.get_major_mesh_terms();

        assert_eq!(major_terms.len(), 1);
        assert_eq!(major_terms[0], "Diabetes Mellitus, Type 2");
    }

    #[test]
    fn test_has_mesh_term() {
        let article = create_test_article_with_mesh();

        assert!(article.has_mesh_term("Diabetes Mellitus, Type 2"));
        assert!(article.has_mesh_term("DIABETES MELLITUS, TYPE 2")); // Case insensitive
        assert!(article.has_mesh_term("Hypertension"));
        assert!(!article.has_mesh_term("Cancer"));
    }

    #[test]
    fn test_get_all_mesh_terms() {
        let article = create_test_article_with_mesh();
        let all_terms = article.get_all_mesh_terms();

        assert_eq!(all_terms.len(), 2);
        assert!(all_terms.contains(&"Diabetes Mellitus, Type 2".to_string()));
        assert!(all_terms.contains(&"Hypertension".to_string()));
    }

    #[test]
    fn test_mesh_term_similarity() {
        let article1 = create_test_article_with_mesh();
        let mut article2 = create_test_article_with_mesh();

        // Same article should have similarity of 1.0
        let similarity = article1.mesh_term_similarity(&article2);
        assert_eq!(similarity, 1.0);

        // Different MeSH terms
        article2.mesh_headings = Some(vec![MeshHeading {
            mesh_terms: vec![
                MeshTerm {
                    descriptor_name: "Diabetes Mellitus, Type 2".to_string(),
                    descriptor_ui: "D003924".to_string(),
                    major_topic: true,
                    qualifiers: vec![],
                },
                MeshTerm {
                    descriptor_name: "Obesity".to_string(),
                    descriptor_ui: "D009765".to_string(),
                    major_topic: false,
                    qualifiers: vec![],
                },
            ],
            supplemental_concepts: vec![],
        }]);

        let similarity = article1.mesh_term_similarity(&article2);
        // Should have partial similarity (1 common term out of 3 unique terms)
        assert!(similarity > 0.0 && similarity < 1.0);
        assert_eq!(similarity, 1.0 / 3.0); // Jaccard similarity

        // No MeSH terms
        let article3 = PubMedArticle {
            pmid: "54321".to_string(),
            title: "Test".to_string(),
            authors: vec![],
            author_count: 0,
            journal: "Test".to_string(),
            pub_date: "2023".to_string(),
            doi: None,
            pmc_id: None,
            abstract_text: None,
            article_types: vec![],
            mesh_headings: None,
            keywords: None,
            chemical_list: None,
            volume: None,
            issue: None,
            pages: None,
            language: None,
            journal_abbreviation: None,
            issn: None,
        };

        assert_eq!(article1.mesh_term_similarity(&article3), 0.0);
    }

    #[test]
    fn test_get_mesh_qualifiers() {
        let article = create_test_article_with_mesh();

        let qualifiers = article.get_mesh_qualifiers("Diabetes Mellitus, Type 2");
        assert_eq!(qualifiers.len(), 2);
        assert!(qualifiers.contains(&"drug therapy".to_string()));
        assert!(qualifiers.contains(&"genetics".to_string()));

        let qualifiers = article.get_mesh_qualifiers("Hypertension");
        assert_eq!(qualifiers.len(), 0);

        let qualifiers = article.get_mesh_qualifiers("Nonexistent Term");
        assert_eq!(qualifiers.len(), 0);
    }

    #[test]
    fn test_has_mesh_terms() {
        let article = create_test_article_with_mesh();
        assert!(article.has_mesh_terms());

        let mut article_no_mesh = article.clone();
        article_no_mesh.mesh_headings = None;
        assert!(!article_no_mesh.has_mesh_terms());

        let mut article_empty_mesh = article.clone();
        article_empty_mesh.mesh_headings = Some(vec![]);
        assert!(!article_empty_mesh.has_mesh_terms());
    }

    #[test]
    fn test_get_chemical_names() {
        let article = create_test_article_with_mesh();
        let chemicals = article.get_chemical_names();

        assert_eq!(chemicals.len(), 1);
        assert_eq!(chemicals[0], "Metformin");

        let mut article_no_chemicals = article.clone();
        article_no_chemicals.chemical_list = None;
        let chemicals = article_no_chemicals.get_chemical_names();
        assert_eq!(chemicals.len(), 0);
    }

    #[test]
    fn test_author_creation() {
        let author = Author::new(Some("Smith".to_string()), Some("Jane".to_string()));
        assert_eq!(author.surname, Some("Smith".to_string()));
        assert_eq!(author.given_names, Some("Jane".to_string()));
        assert_eq!(author.full_name, "Jane Smith");
        assert!(!author.has_orcid());
        assert!(!author.is_corresponding);
    }

    #[test]
    fn test_author_affiliations() {
        let author = create_test_author();

        assert!(author.is_affiliated_with("Harvard"));
        assert!(author.is_affiliated_with("Massachusetts General"));
        assert!(!author.is_affiliated_with("Stanford"));

        let primary = author.primary_affiliation().unwrap();
        assert_eq!(
            primary.institution,
            Some("Harvard Medical School".to_string())
        );

        assert!(author.has_orcid());
        assert!(author.is_corresponding);
    }

    #[test]
    fn test_get_corresponding_authors() {
        let article = create_test_article_with_mesh();
        let corresponding = article.get_corresponding_authors();

        assert_eq!(corresponding.len(), 1);
        assert_eq!(corresponding[0].full_name, "John A Doe");
    }

    #[test]
    fn test_get_authors_by_institution() {
        let article = create_test_article_with_mesh();

        let harvard_authors = article.get_authors_by_institution("Harvard");
        assert_eq!(harvard_authors.len(), 1);

        let stanford_authors = article.get_authors_by_institution("Stanford");
        assert_eq!(stanford_authors.len(), 0);
    }

    #[test]
    fn test_get_author_countries() {
        let article = create_test_article_with_mesh();
        let countries = article.get_author_countries();

        assert_eq!(countries.len(), 1);
        assert!(countries.contains(&"USA".to_string()));
    }

    #[test]
    fn test_international_collaboration() {
        let article = create_test_article_with_mesh();
        assert!(!article.has_international_collaboration());

        // Create article with international authors
        let mut international_article = article.clone();
        let mut uk_author = create_test_author();
        uk_author.affiliations[0].country = Some("UK".to_string());
        international_article.authors.push(uk_author);
        international_article.author_count = 2;

        assert!(international_article.has_international_collaboration());
    }

    #[test]
    fn test_get_authors_with_orcid() {
        let article = create_test_article_with_mesh();
        let authors_with_orcid = article.get_authors_with_orcid();

        assert_eq!(authors_with_orcid.len(), 1);
        assert_eq!(
            authors_with_orcid[0].orcid,
            Some("0000-0001-2345-6789".to_string())
        );
    }

    #[test]
    fn test_format_author_name() {
        assert_eq!(
            format_author_name(&Some("Smith".to_string()), &Some("John".to_string()), &None),
            "John Smith"
        );

        assert_eq!(
            format_author_name(&Some("Doe".to_string()), &None, &Some("J".to_string())),
            "J Doe"
        );

        assert_eq!(
            format_author_name(&Some("Johnson".to_string()), &None, &None),
            "Johnson"
        );

        assert_eq!(
            format_author_name(&None, &Some("Jane".to_string()), &None),
            "Jane"
        );

        assert_eq!(format_author_name(&None, &None, &None), "Unknown Author");
    }

    #[test]
    fn test_spell_check_result_has_corrections() {
        let result = SpellCheckResult {
            database: "pubmed".to_string(),
            query: "asthmaa".to_string(),
            corrected_query: "asthma".to_string(),
            spelled_query: vec![SpelledQuerySegment::Replaced("asthma".to_string())],
        };
        assert!(result.has_corrections());

        let no_correction = SpellCheckResult {
            database: "pubmed".to_string(),
            query: "asthma".to_string(),
            corrected_query: "asthma".to_string(),
            spelled_query: vec![SpelledQuerySegment::Original("asthma".to_string())],
        };
        assert!(!no_correction.has_corrections());
    }

    #[test]
    fn test_spell_check_result_replacements() {
        let result = SpellCheckResult {
            database: "pubmed".to_string(),
            query: "asthmaa OR alergies".to_string(),
            corrected_query: "asthma or allergies".to_string(),
            spelled_query: vec![
                SpelledQuerySegment::Original("".to_string()),
                SpelledQuerySegment::Replaced("asthma".to_string()),
                SpelledQuerySegment::Original(" OR ".to_string()),
                SpelledQuerySegment::Replaced("allergies".to_string()),
            ],
        };
        let replacements = result.replacements();
        assert_eq!(replacements.len(), 2);
        assert_eq!(replacements[0], "asthma");
        assert_eq!(replacements[1], "allergies");
    }

    #[test]
    fn test_bibliographic_fields_on_article() {
        let article = create_test_article_with_mesh();

        assert_eq!(article.volume, Some("45".to_string()));
        assert_eq!(article.issue, Some("3".to_string()));
        assert_eq!(article.pages, Some("123-130".to_string()));
        assert_eq!(article.language, Some("eng".to_string()));
        assert_eq!(article.journal_abbreviation, Some("Test J".to_string()));
        assert_eq!(article.issn, Some("1234-5678".to_string()));
    }
}