papers-zotero 0.2.0

Rust client for the Zotero personal research library API
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
use crate::cache::DiskCache;
use crate::error::{Result, ZoteroError};
use crate::params::{CollectionListParams, ItemListParams, TagListParams};
use crate::response::PagedResponse;
use crate::types::*;
use serde::de::DeserializeOwned;

const DEFAULT_BASE_URL: &str = "https://api.zotero.org";

/// Returns the path to the Zotero executable if it is found on disk, or
/// `None` if Zotero does not appear to be installed.
fn find_zotero_exe() -> Option<String> {
    let mut candidates: Vec<String> = Vec::new();

    #[cfg(target_os = "windows")]
    {
        if let Ok(pf) = std::env::var("PROGRAMFILES") {
            candidates.push(format!(r"{pf}\Zotero\zotero.exe"));
        } else {
            candidates.push(r"C:\Program Files\Zotero\zotero.exe".into());
        }
        if let Ok(local) = std::env::var("LOCALAPPDATA") {
            candidates.push(format!(r"{local}\Zotero\zotero.exe"));
        }
    }

    #[cfg(target_os = "macos")]
    {
        candidates.push("/Applications/Zotero.app/Contents/MacOS/zotero".into());
    }

    #[cfg(target_os = "linux")]
    {
        if let Ok(home) = std::env::var("HOME") {
            candidates.push(format!("{home}/Zotero/zotero"));
        }
        candidates.push("/opt/Zotero/zotero".into());
        candidates.push("/usr/lib/zotero/zotero".into());
        candidates.push("/usr/bin/zotero".into());
    }

    candidates.into_iter().find(|p| std::path::Path::new(p).exists())
}

/// Async client for the [Zotero Web API v3](https://www.zotero.org/support/dev/web_api/v3/start).
///
/// Provides 25+ methods covering all read endpoints for items, collections,
/// tags, searches, and groups in a user's Zotero library.
///
/// # Creating a client
///
/// ```no_run
/// use papers_zotero::ZoteroClient;
///
/// // Read credentials from ZOTERO_USER_ID and ZOTERO_API_KEY env vars
/// let client = ZoteroClient::from_env().unwrap();
///
/// // Or pass explicit credentials
/// let client = ZoteroClient::new("16916553", "your-api-key");
/// ```
///
/// # Example: list items
///
/// ```no_run
/// # async fn example() -> papers_zotero::Result<()> {
/// use papers_zotero::{ZoteroClient, ItemListParams};
///
/// let client = ZoteroClient::from_env()?;
/// let params = ItemListParams::builder()
///     .q("machine learning")
///     .sort("dateModified")
///     .direction("desc")
///     .limit(5)
///     .build();
/// let response = client.list_items(&params).await?;
/// println!("Total: {:?}, got: {}", response.total_results, response.items.len());
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct ZoteroClient {
    http: reqwest::Client,
    base_url: String,
    user_id: String,
    api_key: String,
    cache: Option<DiskCache>,
}

impl ZoteroClient {
    /// Create a new client with explicit user ID and API key.
    pub fn new(user_id: impl Into<String>, api_key: impl Into<String>) -> Self {
        Self {
            http: reqwest::Client::new(),
            base_url: DEFAULT_BASE_URL.to_string(),
            user_id: user_id.into(),
            api_key: api_key.into(),
            cache: None,
        }
    }

    /// Create a client from `ZOTERO_USER_ID` and `ZOTERO_API_KEY` environment
    /// variables.
    ///
    /// Returns `Err` if either variable is not set.
    pub fn from_env() -> Result<Self> {
        let user_id = std::env::var("ZOTERO_USER_ID").map_err(|_| ZoteroError::Api {
            status: 0,
            message: "ZOTERO_USER_ID environment variable not set".into(),
        })?;
        let api_key = std::env::var("ZOTERO_API_KEY").map_err(|_| ZoteroError::Api {
            status: 0,
            message: "ZOTERO_API_KEY environment variable not set".into(),
        })?;
        Ok(Self::new(user_id, api_key))
    }

    /// Create a client from environment variables, preferring the local Zotero
    /// API (`http://localhost:23119`) if it is running and has the local API
    /// enabled. Falls back to the web API with disk cache when unavailable.
    ///
    /// Use this instead of `from_env()` for interactive tools where low latency
    /// matters. The local API requires "Enable Local API" to be turned on in
    /// Zotero → Settings → Advanced.
    pub async fn from_env_prefer_local() -> Result<Self> {
        let user_id = std::env::var("ZOTERO_USER_ID").map_err(|_| ZoteroError::Api {
            status: 0,
            message: "ZOTERO_USER_ID environment variable not set".into(),
        })?;
        let api_key = std::env::var("ZOTERO_API_KEY").map_err(|_| ZoteroError::Api {
            status: 0,
            message: "ZOTERO_API_KEY environment variable not set".into(),
        })?;

        const LOCAL_BASE: &str = "http://127.0.0.1:23119/api";
        let probe_url = format!("{LOCAL_BASE}/users/{user_id}/items?limit=0");
        let local_ok = reqwest::Client::new()
            .get(&probe_url)
            .timeout(std::time::Duration::from_millis(500))
            .send()
            .await
            .map(|r| r.status().is_success())
            .unwrap_or(false);

        if local_ok {
            // Local API is up — no cache needed, it's all in-process on this machine.
            Ok(Self::new(user_id, api_key).with_base_url(LOCAL_BASE))
        } else {
            // If Zotero is installed but not running, surface an actionable error
            // rather than silently falling back to the slower remote API.
            // Set ZOTERO_CHECK_LAUNCHED=0 to opt out of this check.
            let skip_check = std::env::var("ZOTERO_CHECK_LAUNCHED")
                .map(|v| v == "0")
                .unwrap_or(false);
            if !skip_check {
                if let Some(path) = find_zotero_exe() {
                    return Err(ZoteroError::NotRunning { path });
                }
            }
            // Zotero not found on disk — fall back to web API with disk cache.
            let mut client = Self::new(user_id, api_key);
            if let Ok(cache) = DiskCache::default_location(std::time::Duration::from_secs(60)) {
                client = client.with_cache(cache);
            }
            Ok(client)
        }
    }

    /// Override the base URL. Useful for testing with a mock server.
    pub fn with_base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = url.into();
        self
    }

    /// Enable disk caching of successful responses.
    pub fn with_cache(mut self, cache: DiskCache) -> Self {
        self.cache = Some(cache);
        self
    }

    // ── Private helpers ────────────────────────────────────────────────

    fn user_prefix(&self) -> String {
        format!("/users/{}", self.user_id)
    }

    /// GET request returning a JSON array with header-based pagination.
    async fn get_json_array<T: DeserializeOwned>(
        &self,
        path: &str,
        query: Vec<(&str, String)>,
    ) -> Result<PagedResponse<T>> {
        let url = format!("{}{}", self.base_url, path);
        if let Some(cache) = &self.cache
            && let Some(text) = cache.get(&url, &query, None)
        {
            // Cached responses store body + header metadata as JSON
            let cached: CachedArrayResponse =
                serde_json::from_str(&text).map_err(ZoteroError::Json)?;
            let items: Vec<T> =
                serde_json::from_str(&cached.body).map_err(ZoteroError::Json)?;
            return Ok(PagedResponse {
                items,
                total_results: cached.total_results,
                last_modified_version: cached.last_modified_version,
            });
        }
        let resp = self
            .http
            .get(&url)
            .query(&query)
            .header("Zotero-API-Version", "3")
            .header("Zotero-API-Key", &self.api_key)
            .send()
            .await?;
        let status = resp.status();
        if !status.is_success() {
            let message = resp.text().await.unwrap_or_default();
            return Err(ZoteroError::Api {
                status: status.as_u16(),
                message,
            });
        }
        let total_results = resp
            .headers()
            .get("Total-Results")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse().ok());
        let last_modified_version = resp
            .headers()
            .get("Last-Modified-Version")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse().ok());
        let text = resp.text().await?;
        if let Some(cache) = &self.cache {
            let cached = CachedArrayResponse {
                body: text.clone(),
                total_results,
                last_modified_version,
            };
            if let Ok(cache_text) = serde_json::to_string(&cached) {
                cache.set(&url, &query, None, &cache_text);
            }
        }
        let items: Vec<T> = serde_json::from_str(&text).map_err(ZoteroError::Json)?;
        Ok(PagedResponse {
            items,
            total_results,
            last_modified_version,
        })
    }

    /// GET request returning a single JSON object.
    async fn get_json_single<T: DeserializeOwned>(
        &self,
        path: &str,
        query: Vec<(&str, String)>,
    ) -> Result<T> {
        let url = format!("{}{}", self.base_url, path);
        if let Some(cache) = &self.cache
            && let Some(text) = cache.get(&url, &query, None)
        {
            return serde_json::from_str(&text).map_err(ZoteroError::Json);
        }
        let resp = self
            .http
            .get(&url)
            .query(&query)
            .header("Zotero-API-Version", "3")
            .header("Zotero-API-Key", &self.api_key)
            .send()
            .await?;
        let status = resp.status();
        if !status.is_success() {
            let message = resp.text().await.unwrap_or_default();
            return Err(ZoteroError::Api {
                status: status.as_u16(),
                message,
            });
        }
        let text = resp.text().await?;
        if let Some(cache) = &self.cache {
            cache.set(&url, &query, None, &text);
        }
        serde_json::from_str(&text).map_err(ZoteroError::Json)
    }

    /// GET request returning raw bytes (for file downloads).
    /// Does not use caching (files are too large).
    async fn get_binary(&self, path: &str) -> Result<Vec<u8>> {
        let url = format!("{}{}", self.base_url, path);
        let resp = self
            .http
            .get(&url)
            .header("Zotero-API-Version", "3")
            .header("Zotero-API-Key", &self.api_key)
            .send()
            .await?;
        let status = resp.status();
        if !status.is_success() {
            let message = resp.text().await.unwrap_or_default();
            return Err(ZoteroError::Api {
                status: status.as_u16(),
                message,
            });
        }
        Ok(resp.bytes().await?.to_vec())
    }

    // ── Item endpoints ─────────────────────────────────────────────────

    /// List all items in the library.
    ///
    /// `GET /users/<id>/items`
    pub async fn list_items(&self, params: &ItemListParams) -> Result<PagedResponse<Item>> {
        let path = format!("{}/items", self.user_prefix());
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    /// List top-level items (excludes child attachments and notes).
    ///
    /// `GET /users/<id>/items/top`
    pub async fn list_top_items(&self, params: &ItemListParams) -> Result<PagedResponse<Item>> {
        let path = format!("{}/items/top", self.user_prefix());
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    /// List items in the trash.
    ///
    /// `GET /users/<id>/items/trash`
    pub async fn list_trash_items(&self, params: &ItemListParams) -> Result<PagedResponse<Item>> {
        let path = format!("{}/items/trash", self.user_prefix());
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    /// Get a single item by key.
    ///
    /// `GET /users/<id>/items/<key>`
    pub async fn get_item(&self, key: &str) -> Result<Item> {
        let path = format!("{}/items/{}", self.user_prefix(), key);
        self.get_json_single(&path, vec![]).await
    }

    /// List child items (attachments and notes) of a parent item.
    ///
    /// `GET /users/<id>/items/<key>/children`
    pub async fn list_item_children(
        &self,
        key: &str,
        params: &ItemListParams,
    ) -> Result<PagedResponse<Item>> {
        let path = format!("{}/items/{}/children", self.user_prefix(), key);
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    /// List items in "My Publications".
    ///
    /// `GET /users/<id>/publications/items`
    pub async fn list_publication_items(
        &self,
        params: &ItemListParams,
    ) -> Result<PagedResponse<Item>> {
        let path = format!("{}/publications/items", self.user_prefix());
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    /// List items in a specific collection.
    ///
    /// `GET /users/<id>/collections/<key>/items`
    pub async fn list_collection_items(
        &self,
        collection_key: &str,
        params: &ItemListParams,
    ) -> Result<PagedResponse<Item>> {
        let path = format!(
            "{}/collections/{}/items",
            self.user_prefix(),
            collection_key
        );
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    /// List top-level items in a specific collection (excludes child
    /// attachments/notes).
    ///
    /// `GET /users/<id>/collections/<key>/items/top`
    pub async fn list_collection_top_items(
        &self,
        collection_key: &str,
        params: &ItemListParams,
    ) -> Result<PagedResponse<Item>> {
        let path = format!(
            "{}/collections/{}/items/top",
            self.user_prefix(),
            collection_key
        );
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    /// Download the file content of an attachment item.
    ///
    /// `GET /users/<id>/items/<key>/file`
    ///
    /// Returns raw bytes. The reqwest client follows the S3 redirect
    /// automatically.
    pub async fn download_item_file(&self, key: &str) -> Result<Vec<u8>> {
        let path = format!("{}/items/{}/file", self.user_prefix(), key);
        self.get_binary(&path).await
    }

    // ── Collection endpoints ───────────────────────────────────────────

    /// List all collections in the library.
    ///
    /// `GET /users/<id>/collections`
    pub async fn list_collections(
        &self,
        params: &CollectionListParams,
    ) -> Result<PagedResponse<Collection>> {
        let path = format!("{}/collections", self.user_prefix());
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    /// List top-level collections (no parent).
    ///
    /// `GET /users/<id>/collections/top`
    pub async fn list_top_collections(
        &self,
        params: &CollectionListParams,
    ) -> Result<PagedResponse<Collection>> {
        let path = format!("{}/collections/top", self.user_prefix());
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    /// Get a single collection by key.
    ///
    /// `GET /users/<id>/collections/<key>`
    pub async fn get_collection(&self, key: &str) -> Result<Collection> {
        let path = format!("{}/collections/{}", self.user_prefix(), key);
        self.get_json_single(&path, vec![]).await
    }

    /// List sub-collections of a collection.
    ///
    /// `GET /users/<id>/collections/<key>/collections`
    pub async fn list_subcollections(
        &self,
        key: &str,
        params: &CollectionListParams,
    ) -> Result<PagedResponse<Collection>> {
        let path = format!("{}/collections/{}/collections", self.user_prefix(), key);
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    // ── Search endpoints ───────────────────────────────────────────────

    /// List saved searches.
    ///
    /// `GET /users/<id>/searches`
    pub async fn list_searches(&self) -> Result<PagedResponse<SavedSearch>> {
        let path = format!("{}/searches", self.user_prefix());
        self.get_json_array(&path, vec![]).await
    }

    /// Get a single saved search by key.
    ///
    /// `GET /users/<id>/searches/<key>`
    pub async fn get_search(&self, key: &str) -> Result<SavedSearch> {
        let path = format!("{}/searches/{}", self.user_prefix(), key);
        self.get_json_single(&path, vec![]).await
    }

    // ── Tag endpoints ──────────────────────────────────────────────────

    /// List all tags in the library.
    ///
    /// `GET /users/<id>/tags`
    pub async fn list_tags(&self, params: &TagListParams) -> Result<PagedResponse<Tag>> {
        let path = format!("{}/tags", self.user_prefix());
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    /// Get a single tag by name.
    ///
    /// `GET /users/<id>/tags/<urlencoded-name>`
    pub async fn get_tag(&self, name: &str) -> Result<PagedResponse<Tag>> {
        let encoded = urlencoded(name);
        let path = format!("{}/tags/{}", self.user_prefix(), encoded);
        self.get_json_array(&path, vec![]).await
    }

    /// List tags on a specific item.
    ///
    /// `GET /users/<id>/items/<key>/tags`
    pub async fn list_item_tags(
        &self,
        key: &str,
        params: &TagListParams,
    ) -> Result<PagedResponse<Tag>> {
        let path = format!("{}/items/{}/tags", self.user_prefix(), key);
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    /// List all tags used across all items.
    ///
    /// `GET /users/<id>/items/tags`
    pub async fn list_items_tags(&self, params: &TagListParams) -> Result<PagedResponse<Tag>> {
        let path = format!("{}/items/tags", self.user_prefix());
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    /// List tags used across top-level items.
    ///
    /// `GET /users/<id>/items/top/tags`
    pub async fn list_top_items_tags(&self, params: &TagListParams) -> Result<PagedResponse<Tag>> {
        let path = format!("{}/items/top/tags", self.user_prefix());
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    /// List tags used across trashed items.
    ///
    /// `GET /users/<id>/items/trash/tags`
    pub async fn list_trash_tags(&self, params: &TagListParams) -> Result<PagedResponse<Tag>> {
        let path = format!("{}/items/trash/tags", self.user_prefix());
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    /// List tags used across items in a collection.
    ///
    /// `GET /users/<id>/collections/<key>/tags`
    pub async fn list_collection_tags(
        &self,
        collection_key: &str,
        params: &TagListParams,
    ) -> Result<PagedResponse<Tag>> {
        let path = format!(
            "{}/collections/{}/tags",
            self.user_prefix(),
            collection_key
        );
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    /// List tags across items in a collection.
    ///
    /// `GET /users/<id>/collections/<key>/items/tags`
    pub async fn list_collection_items_tags(
        &self,
        collection_key: &str,
        params: &TagListParams,
    ) -> Result<PagedResponse<Tag>> {
        let path = format!(
            "{}/collections/{}/items/tags",
            self.user_prefix(),
            collection_key
        );
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    /// List tags across top-level items in a collection.
    ///
    /// `GET /users/<id>/collections/<key>/items/top/tags`
    pub async fn list_collection_top_items_tags(
        &self,
        collection_key: &str,
        params: &TagListParams,
    ) -> Result<PagedResponse<Tag>> {
        let path = format!(
            "{}/collections/{}/items/top/tags",
            self.user_prefix(),
            collection_key
        );
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    /// List tags across publication items.
    ///
    /// `GET /users/<id>/publications/items/tags`
    ///
    /// **Quirk:** This endpoint returns ALL library tags, not just publication
    /// tags.
    pub async fn list_publication_tags(
        &self,
        params: &TagListParams,
    ) -> Result<PagedResponse<Tag>> {
        let path = format!("{}/publications/items/tags", self.user_prefix());
        self.get_json_array(&path, params.to_query_pairs()).await
    }

    // ── Group endpoints ────────────────────────────────────────────────

    /// List groups the user belongs to.
    ///
    /// `GET /users/<id>/groups`
    pub async fn list_groups(&self) -> Result<PagedResponse<Group>> {
        let path = format!("{}/groups", self.user_prefix());
        self.get_json_array(&path, vec![]).await
    }

    // ── Key info endpoint ──────────────────────────────────────────────

    /// Get information about the current API key.
    ///
    /// `GET /keys/<key>`
    pub async fn get_key_info(&self) -> Result<serde_json::Value> {
        let path = format!("/keys/{}", self.api_key);
        self.get_json_single(&path, vec![]).await
    }
}

/// Minimal percent-encoding for tag names in URL paths.
fn urlencoded(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for byte in s.bytes() {
        match byte {
            b'A'..=b'Z'
            | b'a'..=b'z'
            | b'0'..=b'9'
            | b'-'
            | b'_'
            | b'.'
            | b'~' => out.push(byte as char),
            b' ' => out.push_str("%20"),
            _ => {
                out.push('%');
                out.push(char::from(b"0123456789ABCDEF"[(byte >> 4) as usize]));
                out.push(char::from(b"0123456789ABCDEF"[(byte & 0xf) as usize]));
            }
        }
    }
    out
}

/// Internal type for caching array responses with header metadata.
#[derive(serde::Serialize, serde::Deserialize)]
struct CachedArrayResponse {
    body: String,
    total_results: Option<u64>,
    last_modified_version: Option<u64>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cache::DiskCache;
    use std::time::Duration;
    use wiremock::matchers::{header, method, path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn item_list_json() -> String {
        r#"[{
            "key": "ABC12345",
            "version": 100,
            "library": { "type": "user", "id": 1, "name": "test", "links": {} },
            "links": {},
            "meta": {},
            "data": {
                "key": "ABC12345",
                "version": 100,
                "itemType": "journalArticle",
                "title": "Test",
                "creators": [],
                "tags": [],
                "collections": [],
                "relations": {},
                "dateAdded": "2024-01-01T00:00:00Z",
                "dateModified": "2024-01-01T00:00:00Z"
            }
        }]"#
        .to_string()
    }

    fn single_item_json() -> String {
        r#"{
            "key": "ABC12345",
            "version": 100,
            "library": { "type": "user", "id": 1, "name": "test", "links": {} },
            "links": {},
            "meta": {},
            "data": {
                "key": "ABC12345",
                "version": 100,
                "itemType": "journalArticle",
                "title": "Test",
                "creators": [],
                "tags": [],
                "collections": [],
                "relations": {},
                "dateAdded": "2024-01-01T00:00:00Z",
                "dateModified": "2024-01-01T00:00:00Z"
            }
        }"#
        .to_string()
    }

    fn collection_list_json() -> String {
        r#"[{
            "key": "COL12345",
            "version": 50,
            "library": { "type": "user", "id": 1, "name": "test", "links": {} },
            "links": {},
            "meta": { "numCollections": 0, "numItems": 5 },
            "data": {
                "key": "COL12345",
                "version": 50,
                "name": "Test Collection",
                "parentCollection": false,
                "relations": {}
            }
        }]"#
        .to_string()
    }

    fn tag_list_json() -> String {
        r#"[{
            "tag": "TestTag",
            "links": {},
            "meta": { "type": 0, "numItems": 3 }
        }]"#
        .to_string()
    }

    async fn setup_client(server: &MockServer) -> ZoteroClient {
        ZoteroClient::new("12345", "test-key").with_base_url(server.uri())
    }

    fn array_response(body: &str) -> ResponseTemplate {
        ResponseTemplate::new(200)
            .set_body_string(body.to_string())
            .insert_header("Total-Results", "42")
            .insert_header("Last-Modified-Version", "100")
    }

    // ── Item list tests ───────────────────────────────────────────────

    #[tokio::test]
    async fn test_list_items() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/items"))
            .and(header("Zotero-API-Version", "3"))
            .and(header("Zotero-API-Key", "test-key"))
            .respond_with(array_response(&item_list_json()))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let resp = client.list_items(&ItemListParams::default()).await.unwrap();
        assert_eq!(resp.items.len(), 1);
        assert_eq!(resp.total_results, Some(42));
        assert_eq!(resp.last_modified_version, Some(100));
        assert_eq!(resp.items[0].key, "ABC12345");
    }

    #[tokio::test]
    async fn test_list_top_items() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/items/top"))
            .respond_with(array_response(&item_list_json()))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let resp = client
            .list_top_items(&ItemListParams::default())
            .await
            .unwrap();
        assert_eq!(resp.items.len(), 1);
    }

    #[tokio::test]
    async fn test_list_trash_items() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/items/trash"))
            .respond_with(array_response(&item_list_json()))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let resp = client
            .list_trash_items(&ItemListParams::default())
            .await
            .unwrap();
        assert_eq!(resp.items.len(), 1);
    }

    #[tokio::test]
    async fn test_get_item() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/items/ABC12345"))
            .respond_with(ResponseTemplate::new(200).set_body_string(single_item_json()))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let item = client.get_item("ABC12345").await.unwrap();
        assert_eq!(item.key, "ABC12345");
    }

    #[tokio::test]
    async fn test_list_item_children() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/items/ABC12345/children"))
            .respond_with(array_response(&item_list_json()))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let resp = client
            .list_item_children("ABC12345", &ItemListParams::default())
            .await
            .unwrap();
        assert_eq!(resp.items.len(), 1);
    }

    #[tokio::test]
    async fn test_list_collection_items() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/collections/COL1/items"))
            .respond_with(array_response(&item_list_json()))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let resp = client
            .list_collection_items("COL1", &ItemListParams::default())
            .await
            .unwrap();
        assert_eq!(resp.items.len(), 1);
    }

    #[tokio::test]
    async fn test_list_collection_top_items() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/collections/COL1/items/top"))
            .respond_with(array_response(&item_list_json()))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let resp = client
            .list_collection_top_items("COL1", &ItemListParams::default())
            .await
            .unwrap();
        assert_eq!(resp.items.len(), 1);
    }

    // ── Item params test ──────────────────────────────────────────────

    #[tokio::test]
    async fn test_item_list_with_params() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/items"))
            .and(query_param("q", "test"))
            .and(query_param("itemType", "book"))
            .and(query_param("sort", "dateModified"))
            .and(query_param("direction", "desc"))
            .and(query_param("limit", "5"))
            .respond_with(array_response(&item_list_json()))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let params = ItemListParams::builder()
            .q("test")
            .item_type("book")
            .sort("dateModified")
            .direction("desc")
            .limit(5)
            .build();
        let resp = client.list_items(&params).await.unwrap();
        assert_eq!(resp.items.len(), 1);
    }

    // ── Collection tests ──────────────────────────────────────────────

    #[tokio::test]
    async fn test_list_collections() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/collections"))
            .respond_with(array_response(&collection_list_json()))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let resp = client
            .list_collections(&CollectionListParams::default())
            .await
            .unwrap();
        assert_eq!(resp.items.len(), 1);
        assert_eq!(resp.items[0].data.name, "Test Collection");
    }

    #[tokio::test]
    async fn test_list_top_collections() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/collections/top"))
            .respond_with(array_response(&collection_list_json()))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let resp = client
            .list_top_collections(&CollectionListParams::default())
            .await
            .unwrap();
        assert_eq!(resp.items.len(), 1);
    }

    #[tokio::test]
    async fn test_get_collection() {
        let server = MockServer::start().await;
        let single_json = r#"{
            "key": "COL12345",
            "version": 50,
            "library": { "type": "user", "id": 1, "name": "test", "links": {} },
            "links": {},
            "meta": {},
            "data": { "key": "COL12345", "version": 50, "name": "Test", "parentCollection": false, "relations": {} }
        }"#;
        Mock::given(method("GET"))
            .and(path("/users/12345/collections/COL12345"))
            .respond_with(ResponseTemplate::new(200).set_body_string(single_json))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let coll = client.get_collection("COL12345").await.unwrap();
        assert_eq!(coll.key, "COL12345");
    }

    #[tokio::test]
    async fn test_list_subcollections() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/collections/COL1/collections"))
            .respond_with(array_response(&collection_list_json()))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let resp = client
            .list_subcollections("COL1", &CollectionListParams::default())
            .await
            .unwrap();
        assert_eq!(resp.items.len(), 1);
    }

    // ── Tag tests ─────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_list_tags() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/tags"))
            .respond_with(array_response(&tag_list_json()))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let resp = client.list_tags(&TagListParams::default()).await.unwrap();
        assert_eq!(resp.items.len(), 1);
        assert_eq!(resp.items[0].tag, "TestTag");
    }

    #[tokio::test]
    async fn test_list_items_tags() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/items/tags"))
            .respond_with(array_response(&tag_list_json()))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let resp = client
            .list_items_tags(&TagListParams::default())
            .await
            .unwrap();
        assert_eq!(resp.items.len(), 1);
    }

    #[tokio::test]
    async fn test_list_collection_tags() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/collections/COL1/tags"))
            .respond_with(array_response(&tag_list_json()))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let resp = client
            .list_collection_tags("COL1", &TagListParams::default())
            .await
            .unwrap();
        assert_eq!(resp.items.len(), 1);
    }

    // ── Search tests ──────────────────────────────────────────────────

    #[tokio::test]
    async fn test_list_searches() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/searches"))
            .respond_with(array_response("[]"))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let resp = client.list_searches().await.unwrap();
        assert!(resp.items.is_empty());
    }

    // ── Group tests ───────────────────────────────────────────────────

    #[tokio::test]
    async fn test_list_groups() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/groups"))
            .respond_with(array_response("[]"))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let resp = client.list_groups().await.unwrap();
        assert!(resp.items.is_empty());
    }

    // ── Error tests ───────────────────────────────────────────────────

    #[tokio::test]
    async fn test_error_404() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/items/NOTFOUND"))
            .respond_with(ResponseTemplate::new(404).set_body_string("Not found"))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let err = client.get_item("NOTFOUND").await.unwrap_err();
        match err {
            ZoteroError::Api { status, message } => {
                assert_eq!(status, 404);
                assert_eq!(message, "Not found");
            }
            _ => panic!("Expected Api error, got {:?}", err),
        }
    }

    #[tokio::test]
    async fn test_error_403() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/items"))
            .respond_with(ResponseTemplate::new(403).set_body_string("Forbidden"))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let err = client
            .list_items(&ItemListParams::default())
            .await
            .unwrap_err();
        match err {
            ZoteroError::Api { status, .. } => assert_eq!(status, 403),
            _ => panic!("Expected Api error"),
        }
    }

    // ── Header extraction test ────────────────────────────────────────

    #[tokio::test]
    async fn test_header_extraction() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/items"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string("[]")
                    .insert_header("Total-Results", "999")
                    .insert_header("Last-Modified-Version", "42"),
            )
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let resp = client.list_items(&ItemListParams::default()).await.unwrap();
        assert_eq!(resp.total_results, Some(999));
        assert_eq!(resp.last_modified_version, Some(42));
    }

    #[tokio::test]
    async fn test_missing_headers() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/items"))
            .respond_with(ResponseTemplate::new(200).set_body_string("[]"))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let resp = client.list_items(&ItemListParams::default()).await.unwrap();
        assert_eq!(resp.total_results, None);
        assert_eq!(resp.last_modified_version, None);
    }

    // ── Cache tests ───────────────────────────────────────────────────

    fn temp_cache() -> DiskCache {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        use std::time::{SystemTime, UNIX_EPOCH};
        let mut h = DefaultHasher::new();
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos()
            .hash(&mut h);
        std::thread::current().id().hash(&mut h);
        let dir = std::env::temp_dir()
            .join("papers-zotero-test-cache")
            .join(format!("{:x}", h.finish()));
        DiskCache::new(dir, Duration::from_secs(600)).unwrap()
    }

    #[tokio::test]
    async fn test_cache_hit_avoids_second_request() {
        let server = MockServer::start().await;
        let mock = Mock::given(method("GET"))
            .and(path("/users/12345/items"))
            .respond_with(array_response(&item_list_json()))
            .expect(1)
            .named("list_items")
            .mount_as_scoped(&server)
            .await;
        let client = ZoteroClient::new("12345", "test-key")
            .with_base_url(server.uri())
            .with_cache(temp_cache());
        let resp1 = client.list_items(&ItemListParams::default()).await.unwrap();
        assert_eq!(resp1.items.len(), 1);
        // Second call from cache
        let resp2 = client.list_items(&ItemListParams::default()).await.unwrap();
        assert_eq!(resp2.items.len(), 1);
        assert_eq!(resp2.total_results, Some(42));
        drop(mock);
    }

    #[tokio::test]
    async fn test_cache_error_not_cached() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/items/bad"))
            .respond_with(ResponseTemplate::new(500).set_body_string("error"))
            .expect(2)
            .mount(&server)
            .await;
        let client = ZoteroClient::new("12345", "test-key")
            .with_base_url(server.uri())
            .with_cache(temp_cache());
        let _ = client.get_item("bad").await;
        let _ = client.get_item("bad").await;
    }

    // ── File download test ────────────────────────────────────────────

    #[tokio::test]
    async fn test_download_item_file() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/items/ATTACH1/file"))
            .and(header("Zotero-API-Version", "3"))
            .and(header("Zotero-API-Key", "test-key"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_bytes(b"fake-pdf-bytes".to_vec()),
            )
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let bytes = client.download_item_file("ATTACH1").await.unwrap();
        assert_eq!(bytes, b"fake-pdf-bytes");
    }

    #[tokio::test]
    async fn test_download_item_file_404() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/users/12345/items/MISSING/file"))
            .respond_with(ResponseTemplate::new(404).set_body_string("Not found"))
            .mount(&server)
            .await;
        let client = setup_client(&server).await;
        let err = client.download_item_file("MISSING").await.unwrap_err();
        match err {
            ZoteroError::Api { status, .. } => assert_eq!(status, 404),
            _ => panic!("Expected Api error, got {:?}", err),
        }
    }

    // ── URL encoding test ─────────────────────────────────────────────

    #[test]
    fn test_urlencoded() {
        assert_eq!(urlencoded("simple"), "simple");
        assert_eq!(urlencoded("with space"), "with%20space");
        assert_eq!(urlencoded("special/chars&more"), "special%2Fchars%26more");
    }
}