Skip to main content

zotron_cli/
lib.rs

1//! Minimal typed CLI surface for the Rust migration scaffold.
2
3use std::{
4    env, fs,
5    io::{self, Read},
6    path::{Path, PathBuf},
7    process::Command as ProcessCommand,
8    thread,
9    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
10};
11
12use clap::{error::ErrorKind, Parser, Subcommand};
13use serde_json::Value;
14use zotron_rpc::{StdProviderCommandRunner, UreqProviderHttpTransport, ZoteroRpc};
15use zotron_types::{
16    bm25_score_chunks, build_embedding_provider_request, build_ocr_provider_request,
17    builtin_ocr_provider_specs, cosine_similarity, execute_embedding_provider_request,
18    is_zotron_evidence_artifact, machine_artifact_exists_for_item,
19    machine_artifact_exists_in_sidecar, machine_artifact_store_root,
20    ocr_provider_spec as raw_ocr_provider_spec, parse_embedding_provider_response,
21    parse_ocr_provider_response, read_machine_artifact_sidecar, rrf_merge,
22    write_machine_artifact_sidecar, ArtifactStorePlatform, EmbeddingChunkInput,
23    EmbeddingRequestInput, EmbeddingVector, MachineArtifactKind, OcrRequestInput,
24    ProviderCommandRunner, ProviderHttpInvocation, ProviderHttpTransport, StructureChunk,
25    DEFAULT_RPC_URL,
26};
27
28pub trait RpcCaller {
29    fn call(&mut self, method: &str, params: Option<Value>) -> Result<Value, String>;
30}
31
32#[derive(Debug, Clone, PartialEq, serde::Serialize)]
33pub struct CliOcrProviderSpec {
34    pub id: &'static str,
35    pub provider: &'static str,
36    pub request_style: &'static str,
37    pub auth: &'static str,
38    pub auth_header: &'static str,
39    pub supports_pdf_direct: bool,
40    pub key_field: &'static str,
41}
42
43#[derive(Debug, Clone, PartialEq, serde::Serialize)]
44pub struct CliEmbeddingProviderSpec {
45    pub id: &'static str,
46    pub provider: &'static str,
47    pub request_style: &'static str,
48    pub default_url: String,
49    pub default_model: &'static str,
50    pub auth: &'static str,
51    pub key_field: &'static str,
52}
53
54pub fn ocr_provider_specs() -> Vec<CliOcrProviderSpec> {
55    builtin_ocr_provider_specs()
56        .into_iter()
57        .map(cli_ocr_provider_spec)
58        .collect()
59}
60
61pub fn ocr_provider_spec(provider: &str) -> Result<CliOcrProviderSpec, String> {
62    zotron_types::ocr_provider_spec(provider).map(cli_ocr_provider_spec)
63}
64
65pub fn embedding_provider_spec(provider: &str) -> Result<CliEmbeddingProviderSpec, String> {
66    let spec = zotron_types::embedding_provider_spec(provider)?;
67    Ok(CliEmbeddingProviderSpec {
68        id: spec.id,
69        provider: spec.provider_key,
70        request_style: if spec.provider_key == "alibaba" {
71            "dashscope"
72        } else {
73            spec.request_style.as_str()
74        },
75        default_url: spec.default_url.unwrap_or("").to_string(),
76        default_model: spec.default_model,
77        auth: spec.auth,
78        key_field: spec.key_field,
79    })
80}
81
82pub fn chunks_from_blocks(blocks: &[Value], max_chars: usize) -> Result<Vec<Value>, String> {
83    let typed = blocks
84        .iter()
85        .map(json_block_to_pdf_block)
86        .collect::<Result<Vec<_>, _>>()?;
87    let chunks = zotron_types::chunks_from_blocks(&typed, max_chars);
88    chunks
89        .into_iter()
90        .map(|chunk| chunk_to_cli_value(&chunk, &typed))
91        .collect()
92}
93
94fn cli_ocr_provider_spec(spec: zotron_types::OcrProviderSpec) -> CliOcrProviderSpec {
95    CliOcrProviderSpec {
96        id: spec.provider_key,
97        provider: spec.provider_key,
98        request_style: spec.request_style.as_str(),
99        auth: spec.auth,
100        auth_header: spec.auth_header,
101        supports_pdf_direct: spec.supports_pdf_direct,
102        key_field: spec.key_field,
103    }
104}
105
106fn json_block_to_pdf_block(value: &Value) -> Result<zotron_types::PdfEvidenceBlock, String> {
107    let block_key = value
108        .get("block_key")
109        .and_then(Value::as_str)
110        .ok_or_else(|| "block missing block_key".to_string())?
111        .to_string();
112    let item_key = value
113        .get("item_key")
114        .and_then(Value::as_str)
115        .ok_or_else(|| "block missing item_key".to_string())?
116        .to_string();
117    let attachment_key = value
118        .get("attachment_key")
119        .and_then(Value::as_str)
120        .ok_or_else(|| "block missing attachment_key".to_string())?
121        .to_string();
122    let page_idx = value
123        .get("page_idx")
124        .or_else(|| value.get("page"))
125        .and_then(Value::as_u64)
126        .unwrap_or(1);
127    let block_type = value
128        .get("type")
129        .or_else(|| value.get("block_type"))
130        .and_then(Value::as_str)
131        .unwrap_or("paragraph")
132        .to_string();
133    let section_path = value
134        .get("section_path")
135        .and_then(Value::as_array)
136        .map(|items| {
137            items
138                .iter()
139                .filter_map(Value::as_str)
140                .map(ToString::to_string)
141                .collect::<Vec<_>>()
142        })
143        .unwrap_or_default();
144    let text = value
145        .get("text")
146        .and_then(Value::as_str)
147        .unwrap_or("")
148        .to_string();
149    let bbox = value.get("bbox").and_then(value_bbox4);
150
151    Ok(zotron_types::PdfEvidenceBlock {
152        block_key,
153        item_key,
154        attachment_key,
155        page_idx,
156        block_type,
157        bbox,
158        section_path,
159        text,
160    })
161}
162
163fn chunk_to_cli_value(
164    chunk: &zotron_types::StructureChunk,
165    blocks: &[zotron_types::PdfEvidenceBlock],
166) -> Result<Value, String> {
167    let refs = chunk
168        .block_keys
169        .iter()
170        .filter_map(|key| blocks.iter().find(|block| &block.block_key == key))
171        .map(|block| {
172            serde_json::json!({
173                "block_key": block.block_key,
174                "page_idx": block.page_idx,
175                "bbox": block.bbox.map(|bbox| bbox.iter().map(|n| {
176                    if n.fract() == 0.0 {
177                        Value::from(*n as i64)
178                    } else {
179                        Value::from(*n)
180                    }
181                }).collect::<Vec<_>>()),
182            })
183        })
184        .collect::<Vec<_>>();
185    Ok(serde_json::json!({
186        "chunk_key": chunk.chunk_key,
187        "item_key": chunk.item_key,
188        "attachment_key": chunk.attachment_key,
189        "block_keys": chunk.block_keys,
190        "section_path": chunk.section_path,
191        "text": chunk.text,
192        "page_start": chunk.page_start,
193        "page_end": chunk.page_end,
194        "evidence_refs": refs,
195    }))
196}
197
198fn value_bbox4(value: &Value) -> Option<[f64; 4]> {
199    let arr = value.as_array()?;
200    if arr.len() != 4 {
201        return None;
202    }
203    Some([
204        arr[0].as_f64()?,
205        arr[1].as_f64()?,
206        arr[2].as_f64()?,
207        arr[3].as_f64()?,
208    ])
209}
210
211impl RpcCaller for ZoteroRpc {
212    fn call(&mut self, method: &str, params: Option<Value>) -> Result<Value, String> {
213        self.call(method, params).map_err(|err| err.to_string())
214    }
215}
216
217#[derive(Debug, Parser)]
218#[command(name = "zotron", about = "Rust client + CLI for the Zotron XPI")]
219struct Cli {
220    #[command(subcommand)]
221    command: Command,
222}
223
224#[derive(Debug, Subcommand)]
225enum OcrCommand {
226    /// Print supported OCR provider contracts.
227    Providers,
228    /// Execute an OCR provider request from JSON and emit normalized blocks.
229    #[command(name = "run")]
230    Run {
231        #[arg(long)]
232        provider: String,
233        /// Path to an OcrRequestInput JSON file, or "-" to read stdin.
234        #[arg(long)]
235        input: Option<String>,
236        /// Local PDF/image file to encode into an OcrRequestInput.
237        #[arg(long)]
238        file: Option<String>,
239        /// Zotero item key used when --file builds the OCR request.
240        #[arg(long = "item-key")]
241        item_key: Option<String>,
242        /// Zotero attachment key used when --file builds the OCR request.
243        #[arg(long = "attachment-key")]
244        attachment_key: Option<String>,
245        /// MIME type used when --file builds the OCR request.
246        #[arg(long = "mime-type")]
247        mime_type: Option<String>,
248        /// Override the provider endpoint, required for service-hosted PaddleOCR-VL.
249        #[arg(long)]
250        endpoint: Option<String>,
251        /// Environment variable containing the provider bearer token.
252        #[arg(long = "api-key-env")]
253        api_key_env: Option<String>,
254    },
255    /// Show OCR statistics for a collection.
256    Status {
257        #[arg(long)]
258        collection: String,
259        #[arg(long, default_value = DEFAULT_RPC_URL)]
260        url: String,
261    },
262    /// Parse a Zotero PDF through MinerU and write hidden sidecar OCR/RAG artifacts.
263    #[command(name = "process")]
264    Process {
265        #[arg(long, default_value = "mineru")]
266        provider: String,
267        /// Parent Zotero item key.
268        #[arg(long)]
269        parent: String,
270        /// Zotero PDF attachment key (auto-resolved from --parent when omitted).
271        #[arg(long)]
272        attachment: Option<String>,
273        /// Public URL for MinerU cloud parsing. Use --result-dir/--result-zip for offline ingestion.
274        #[arg(long = "source-url")]
275        source_url: Option<String>,
276        /// Already-extracted MinerU result directory, used by tests/offline replay.
277        #[arg(long = "result-dir")]
278        result_dir: Option<String>,
279        /// Already-downloaded MinerU result zip, used by tests/offline replay.
280        #[arg(long = "result-zip")]
281        result_zip: Option<String>,
282        /// Override MinerU submit endpoint.
283        #[arg(long = "provider-endpoint")]
284        provider_endpoint: Option<String>,
285        /// Environment variable containing the MinerU bearer token.
286        #[arg(long = "api-key-env", default_value = "ZOTRON_MINERU_API_KEY")]
287        api_key_env: String,
288        #[arg(long = "poll-interval-seconds", default_value_t = 5)]
289        poll_interval_seconds: u64,
290        #[arg(long = "timeout-seconds", default_value_t = 900)]
291        timeout_seconds: u64,
292        #[arg(long = "chunk-chars", default_value_t = 1200)]
293        chunk_chars: usize,
294        #[arg(long, default_value = DEFAULT_RPC_URL)]
295        url: String,
296    },
297}
298
299#[derive(Debug, Subcommand)]
300enum Command {
301    /// Check that Zotero is running with the Zotron XPI enabled.
302    Ping {
303        #[arg(long, default_value = DEFAULT_RPC_URL)]
304        url: String,
305    },
306    /// Generic RPC escape hatch.
307    Rpc {
308        method: String,
309        #[arg(default_value = "{}")]
310        params_json: String,
311        #[arg(long, default_value = DEFAULT_RPC_URL)]
312        url: String,
313        #[arg(long)]
314        paginate: bool,
315        #[arg(long, default_value_t = 100)]
316        page_size: usize,
317    },
318    /// Push prepared Zotero JSON (from file or stdin) to Zotero.
319    Push {
320        /// Path to a JSON file, or "-" to read from stdin.
321        json_file: String,
322        /// Optional PDF attachment path.
323        #[arg(long)]
324        pdf: Option<String>,
325        /// Collection name (fuzzy) or key.
326        #[arg(long)]
327        collection: Option<String>,
328        /// Duplicate handling: skip | update | create.
329        #[arg(long = "on-duplicate", default_value = "skip")]
330        on_duplicate: String,
331        #[arg(long, default_value = DEFAULT_RPC_URL)]
332        url: String,
333        /// Parse input + resolve collection only; do not push to Zotero.
334        #[arg(long = "dry-run")]
335        dry_run: bool,
336    },
337    /// System and plugin introspection commands.
338    System {
339        #[command(subcommand)]
340        command: SystemCommand,
341    },
342    /// Search items by text, tag, identifier, or structured conditions.
343    Search(SearchArgs),
344    /// Inspect and manage Zotero items.
345    Items {
346        #[command(subcommand)]
347        command: ItemsCommand,
348    },
349    /// Inspect Zotero collections.
350    Collections {
351        #[command(subcommand)]
352        command: CollectionsCommand,
353    },
354    /// Inspect Zotero notes.
355    Notes {
356        #[command(subcommand)]
357        command: NotesCommand,
358    },
359    /// Inspect Zotero attachments.
360    Attachments {
361        #[command(subcommand)]
362        command: AttachmentsCommand,
363    },
364    /// Inspect Zotero preferences.
365    Settings {
366        #[command(subcommand)]
367        command: SettingsCommand,
368    },
369    /// Inspect and manage Zotero tags.
370    Tags {
371        #[command(subcommand)]
372        command: TagsCommand,
373    },
374    /// Export items as BibTeX, RIS, CSL-JSON, or formatted bibliography.
375    Export(ExportArgs),
376    /// List, create, and delete PDF annotations.
377    Annotations {
378        #[command(subcommand)]
379        command: AnnotationsCommand,
380    },
381    /// OCR PDFs and manage raw/block/chunk evidence artifacts.
382    Ocr {
383        #[command(subcommand)]
384        command: OcrCommand,
385    },
386    /// Build and search retrieval artifacts.
387    Rag {
388        #[command(subcommand)]
389        command: RagCommand,
390    },
391    /// Batch fill missing PDFs in a collection via Zotero's resolver chain.
392    #[command(name = "find-pdfs")]
393    FindPdfs {
394        #[arg(long)]
395        collection: String,
396        #[arg(long, default_value_t = 0)]
397        limit: usize,
398        #[arg(long, default_value = DEFAULT_RPC_URL)]
399        url: String,
400    },
401}
402
403struct RagSearchOptions {
404    query: String,
405    collection: Option<String>,
406    keys: Vec<String>,
407    zotero: bool,
408    top_spans_per_item: u64,
409    include_fulltext_spans: bool,
410    top_k: u64,
411    output: String,
412}
413
414#[derive(Debug, Subcommand)]
415enum RagCommand {
416    /// Print supported embedding provider contracts.
417    #[command(name = "providers")]
418    Providers,
419    /// Execute an embedding provider request from JSON and emit vectors.
420    #[command(name = "embed")]
421    Embed {
422        #[arg(long)]
423        provider: String,
424        /// Path to an EmbeddingRequestInput JSON file, or "-" to read stdin.
425        #[arg(long)]
426        input: String,
427        /// Override the embedding endpoint.
428        #[arg(long)]
429        endpoint: Option<String>,
430        /// Override the embedding model.
431        #[arg(long)]
432        model: Option<String>,
433        /// Override provider input type, for example document or query.
434        #[arg(long = "input-type")]
435        input_type: Option<String>,
436        /// Environment variable containing the provider bearer token.
437        #[arg(long = "api-key-env")]
438        api_key_env: Option<String>,
439    },
440    /// Show index status for a collection.
441    Status {
442        #[arg(long)]
443        collection: String,
444        #[arg(long, default_value = DEFAULT_RPC_URL)]
445        url: String,
446    },
447    /// Emit academic-zh retrieval hits with item_key/title/text provenance.
448    #[command(name = "search")]
449    Search {
450        query: String,
451        #[arg(long)]
452        collection: Option<String>,
453        /// Limit retrieval to one or more Zotero item keys.
454        #[arg(long = "key", alias = "keys")]
455        keys: Vec<String>,
456        #[arg(long)]
457        zotero: bool,
458        #[arg(long = "top-spans-per-item", default_value_t = 3)]
459        top_spans_per_item: u64,
460        #[arg(long = "include-fulltext-spans")]
461        include_fulltext_spans: bool,
462        #[arg(long = "limit", alias = "top-k", default_value_t = 50)]
463        top_k: u64,
464        #[arg(long, default_value = "json", value_parser = ["json", "jsonl"])]
465        output: String,
466        #[arg(long, default_value = DEFAULT_RPC_URL)]
467        url: String,
468    },
469}
470
471#[derive(Debug, Subcommand)]
472enum SystemCommand {
473    /// Show XPI version and exposed method metadata.
474    Version {
475        #[arg(long, default_value = DEFAULT_RPC_URL)]
476        url: String,
477    },
478    /// List all libraries (user + groups).
479    Libraries {
480        #[arg(long, default_value = DEFAULT_RPC_URL)]
481        url: String,
482    },
483    /// Get statistics for the current (or specified) library.
484    #[command(name = "library-stats")]
485    LibraryStats {
486        #[arg(long)]
487        library: Option<i64>,
488        #[arg(long, default_value = DEFAULT_RPC_URL)]
489        url: String,
490    },
491    /// Show item type schema. Without --type, lists all types. With --type, shows fields and creator types.
492    Schema {
493        #[arg(long = "type")]
494        item_type: Option<String>,
495        #[arg(long, default_value = DEFAULT_RPC_URL)]
496        url: String,
497    },
498    /// Get the currently selected Zotero collection (or null).
499    #[command(name = "current-collection")]
500    CurrentCollection {
501        #[arg(long, default_value = DEFAULT_RPC_URL)]
502        url: String,
503    },
504    /// List all RPC methods exposed by the XPI.
505    #[command(name = "list-methods")]
506    ListMethods {
507        #[arg(long, default_value = DEFAULT_RPC_URL)]
508        url: String,
509    },
510    /// Describe one or all RPC methods (schema / signatures).
511    Describe {
512        method: Option<String>,
513        #[arg(long, default_value = DEFAULT_RPC_URL)]
514        url: String,
515    },
516}
517
518#[derive(Debug, clap::Args)]
519struct SearchArgs {
520    /// Search query (title/creator/year by default; PDF content with --fulltext).
521    query: Option<String>,
522    /// Search inside PDF full-text content instead of metadata.
523    #[arg(long)]
524    fulltext: bool,
525    /// Filter by author/creator name (contains match).
526    #[arg(long)]
527    author: Option<String>,
528    /// Filter by date after (YYYY or YYYY-MM-DD).
529    #[arg(long)]
530    after: Option<String>,
531    /// Filter by date before (YYYY or YYYY-MM-DD).
532    #[arg(long)]
533    before: Option<String>,
534    /// Filter by journal/publication title (contains match).
535    #[arg(long)]
536    journal: Option<String>,
537    /// Filter by tag (exact match).
538    #[arg(long)]
539    tag: Option<String>,
540    /// Find by DOI.
541    #[arg(long)]
542    doi: Option<String>,
543    /// Find by ISBN.
544    #[arg(long)]
545    isbn: Option<String>,
546    /// Find by ISSN.
547    #[arg(long)]
548    issn: Option<String>,
549    /// Limit results to a collection name or key.
550    #[arg(long)]
551    collection: Option<String>,
552    #[arg(long, default_value_t = 50)]
553    limit: u64,
554    #[arg(long, default_value_t = 0)]
555    offset: u64,
556    #[arg(long, default_value = DEFAULT_RPC_URL)]
557    url: String,
558    #[command(subcommand)]
559    management: Option<SearchManagementCommand>,
560}
561
562#[derive(Debug, Subcommand)]
563enum SearchManagementCommand {
564    /// List all saved searches in the library.
565    #[command(name = "saved-searches")]
566    SavedSearches {
567        #[arg(long, default_value = DEFAULT_RPC_URL)]
568        url: String,
569    },
570    /// Create a saved search with one or more conditions.
571    #[command(name = "create-saved")]
572    CreateSaved {
573        name: String,
574        #[arg(long = "condition", required = true)]
575        condition: Vec<String>,
576        #[arg(long)]
577        dry_run: bool,
578        #[arg(long, default_value = DEFAULT_RPC_URL)]
579        url: String,
580    },
581    /// Delete a saved search by key.
582    #[command(name = "delete-saved")]
583    DeleteSaved {
584        search_key: String,
585        #[arg(long)]
586        dry_run: bool,
587        #[arg(long, default_value = DEFAULT_RPC_URL)]
588        url: String,
589    },
590}
591
592#[derive(Debug, Subcommand)]
593enum ItemsCommand {
594    /// Add an item by DOI, ISBN, URL, or local file.
595    Add {
596        #[arg(long)]
597        doi: Option<String>,
598        #[arg(long)]
599        isbn: Option<String>,
600        /// Web page URL to add from.
601        #[arg(long = "from-url")]
602        from_url: Option<String>,
603        /// Local file path to add from.
604        #[arg(long)]
605        file: Option<String>,
606        #[arg(long)]
607        collection: Option<String>,
608        #[arg(long)]
609        dry_run: bool,
610        #[arg(long, default_value = DEFAULT_RPC_URL)]
611        url: String,
612    },
613    /// Create a new item of the given type.
614    Create {
615        #[arg(long = "type")]
616        item_type: String,
617        #[arg(long = "field")]
618        fields: Vec<String>,
619        #[arg(long)]
620        dry_run: bool,
621        #[arg(long, default_value = DEFAULT_RPC_URL)]
622        url: String,
623    },
624    /// Update fields on an existing item.
625    Update {
626        key: String,
627        #[arg(long = "field")]
628        fields: Vec<String>,
629        #[arg(long)]
630        dry_run: bool,
631        #[arg(long, default_value = DEFAULT_RPC_URL)]
632        url: String,
633    },
634    /// Permanently delete an item.
635    Delete {
636        key: String,
637        #[arg(long)]
638        dry_run: bool,
639        #[arg(long, default_value = DEFAULT_RPC_URL)]
640        url: String,
641    },
642    /// Move one or more items to trash.
643    Trash {
644        items: Vec<String>,
645        #[arg(long)]
646        dry_run: bool,
647        #[arg(long, default_value = DEFAULT_RPC_URL)]
648        url: String,
649    },
650    /// Restore a trashed item.
651    Restore {
652        item: String,
653        #[arg(long)]
654        dry_run: bool,
655        #[arg(long, default_value = DEFAULT_RPC_URL)]
656        url: String,
657    },
658    /// Merge a group of duplicate items.
659    #[command(name = "merge-duplicates")]
660    MergeDuplicates {
661        keys: Vec<String>,
662        #[arg(long)]
663        dry_run: bool,
664        #[arg(long, default_value = DEFAULT_RPC_URL)]
665        url: String,
666    },
667    /// Add a related-item link between two items.
668    #[command(name = "add-related")]
669    AddRelated {
670        key: String,
671        #[arg(long)]
672        target: String,
673        #[arg(long)]
674        dry_run: bool,
675        #[arg(long, default_value = DEFAULT_RPC_URL)]
676        url: String,
677    },
678    /// Remove a related-item link between two items.
679    #[command(name = "remove-related")]
680    RemoveRelated {
681        key: String,
682        #[arg(long)]
683        target: String,
684        #[arg(long)]
685        dry_run: bool,
686        #[arg(long, default_value = DEFAULT_RPC_URL)]
687        url: String,
688    },
689    /// Print the full serialization of an item by key.
690    Get {
691        item: String,
692        #[arg(long, default_value = DEFAULT_RPC_URL)]
693        url: String,
694    },
695    /// List items in the library with optional sorting and pagination.
696    List {
697        #[arg(long, default_value_t = 50)]
698        limit: u64,
699        #[arg(long, default_value_t = 0)]
700        offset: u64,
701        #[arg(long)]
702        sort: Option<String>,
703        #[arg(long, default_value = "asc")]
704        direction: String,
705        /// List trashed items instead of regular items.
706        #[arg(long)]
707        trash: bool,
708        #[arg(long, default_value = DEFAULT_RPC_URL)]
709        url: String,
710    },
711    /// Run Zotero's duplicate scan and print groups.
712    #[command(name = "find-duplicates")]
713    FindDuplicates {
714        #[arg(long, default_value = DEFAULT_RPC_URL)]
715        url: String,
716    },
717    /// List recently added or modified items.
718    Recent {
719        #[arg(long, default_value_t = 20)]
720        limit: u64,
721        #[arg(long, default_value_t = 0)]
722        offset: u64,
723        #[arg(long = "type", default_value = "added")]
724        recent_type: String,
725        #[arg(long, default_value = DEFAULT_RPC_URL)]
726        url: String,
727    },
728    /// Retrieve the full-text content of an item's attachment.
729    Fulltext {
730        key: String,
731        #[arg(long, default_value = DEFAULT_RPC_URL)]
732        url: String,
733    },
734    /// List items related to the given item.
735    Related {
736        key: String,
737        #[arg(long, default_value = DEFAULT_RPC_URL)]
738        url: String,
739    },
740    /// Get the citation key for an item.
741    #[command(name = "citation-key")]
742    CitationKey {
743        key: String,
744        #[arg(long, default_value = DEFAULT_RPC_URL)]
745        url: String,
746    },
747}
748
749#[derive(Debug, Subcommand)]
750enum SettingsCommand {
751    /// Get a single Zotero preference value.
752    Get {
753        key: String,
754        #[arg(long, default_value = DEFAULT_RPC_URL)]
755        url: String,
756    },
757    /// List all Zotero preferences as a key->value dict.
758    #[command(visible_alias = "get-all")]
759    List {
760        #[arg(long, default_value = DEFAULT_RPC_URL)]
761        url: String,
762    },
763    /// Set one or more Zotero preferences (key value pairs), or bulk-set from a JSON file.
764    Set {
765        /// key value key value ... (pairs of positional args)
766        pairs: Vec<String>,
767        /// Bulk-set from a JSON file.
768        #[arg(long)]
769        file: Option<String>,
770        #[arg(long)]
771        dry_run: bool,
772        #[arg(long, default_value = DEFAULT_RPC_URL)]
773        url: String,
774    },
775}
776
777#[derive(Debug, Subcommand)]
778enum TagsCommand {
779    /// List all tags in the library (flat).
780    List {
781        #[arg(long, default_value_t = 200)]
782        limit: u64,
783        #[arg(long, default_value = DEFAULT_RPC_URL)]
784        url: String,
785    },
786    /// Rename a tag across all items.
787    Rename {
788        old: String,
789        new: String,
790        #[arg(long)]
791        dry_run: bool,
792        #[arg(long, default_value = DEFAULT_RPC_URL)]
793        url: String,
794    },
795    /// Delete a tag library-wide.
796    Delete {
797        tag: String,
798        #[arg(long)]
799        dry_run: bool,
800        #[arg(long, default_value = DEFAULT_RPC_URL)]
801        url: String,
802    },
803    /// Add tags to one or more items.
804    Add {
805        keys: Vec<String>,
806        #[arg(long = "tag", required = true)]
807        tags: Vec<String>,
808        #[arg(long)]
809        dry_run: bool,
810        #[arg(long, default_value = DEFAULT_RPC_URL)]
811        url: String,
812    },
813    /// Remove tags from one or more items.
814    Remove {
815        keys: Vec<String>,
816        #[arg(long = "tag", required = true)]
817        tags: Vec<String>,
818        #[arg(long)]
819        dry_run: bool,
820        #[arg(long, default_value = DEFAULT_RPC_URL)]
821        url: String,
822    },
823}
824
825#[derive(Debug, clap::Args)]
826struct ExportArgs {
827    /// Item keys to export.
828    keys: Vec<String>,
829    /// Output format: bibtex, ris, csl-json, bibliography.
830    #[arg(long, default_value = "bibtex")]
831    format: String,
832    /// Export all items from this collection (name or key).
833    #[arg(long)]
834    collection: Option<String>,
835    /// Citation style URL (only for bibliography format).
836    #[arg(long, default_value = "http://www.zotero.org/styles/apa")]
837    style: String,
838    /// Output HTML instead of plain text (only for bibliography format).
839    #[arg(long)]
840    html: bool,
841    #[arg(long, default_value = DEFAULT_RPC_URL)]
842    url: String,
843}
844
845#[derive(Debug, Subcommand)]
846enum AnnotationsCommand {
847    /// List annotations on a PDF attachment.
848    List {
849        parent: String,
850        #[arg(long, default_value = DEFAULT_RPC_URL)]
851        url: String,
852    },
853    /// Create a new annotation on a PDF attachment.
854    Create {
855        parent: String,
856        #[arg(long = "type")]
857        annotation_type: Option<String>,
858        /// JSON annotation position, for example '{"pageIndex":0,"rects":[[10,20,30,40]]}'.
859        /// Not required when --quote is given.
860        #[arg(long)]
861        position: Option<String>,
862        /// Text to locate in the PDF and highlight. Resolves to rects automatically.
863        /// Locates text headlessly (no PDF viewer required).
864        /// Use with --dry-run for locate-only mode.
865        #[arg(long)]
866        quote: Option<String>,
867        /// Restrict quote search to a specific page (0-indexed).
868        #[arg(long)]
869        page: Option<u32>,
870        /// Zotero annotation sort index.
871        #[arg(long = "sort-index")]
872        sort_index: Option<String>,
873        #[arg(long)]
874        text: Option<String>,
875        #[arg(long)]
876        comment: Option<String>,
877        #[arg(long, default_value = "#ffd400")]
878        color: String,
879        #[arg(long)]
880        dry_run: bool,
881        #[arg(long, default_value = DEFAULT_RPC_URL)]
882        url: String,
883    },
884    /// Delete an annotation by key.
885    Delete {
886        annotation_key: String,
887        #[arg(long)]
888        dry_run: bool,
889        #[arg(long, default_value = DEFAULT_RPC_URL)]
890        url: String,
891    },
892}
893
894#[derive(Debug, Subcommand)]
895enum AttachmentsCommand {
896    /// List attachments belonging to a parent item.
897    List {
898        #[arg(long)]
899        parent: String,
900        #[arg(long, default_value_t = 50)]
901        limit: u64,
902        #[arg(long, default_value_t = 0)]
903        offset: u64,
904        #[arg(long, default_value = DEFAULT_RPC_URL)]
905        url: String,
906    },
907    /// Get a single attachment by key.
908    Get {
909        key: String,
910        #[arg(long, default_value = DEFAULT_RPC_URL)]
911        url: String,
912    },
913    /// Get full-text content of an attachment.
914    Fulltext {
915        key: String,
916        #[arg(long, default_value = DEFAULT_RPC_URL)]
917        url: String,
918    },
919    /// Get the local filesystem path of an attachment.
920    Path {
921        key: String,
922        #[arg(long, default_value = DEFAULT_RPC_URL)]
923        url: String,
924    },
925    /// Attach a local file or remote URL to an item.
926    Add {
927        #[arg(long)]
928        parent: String,
929        /// Local file path to attach.
930        #[arg(long)]
931        path: Option<String>,
932        /// Remote URL to attach.
933        #[arg(long = "from-url")]
934        from_url: Option<String>,
935        #[arg(long)]
936        title: Option<String>,
937        #[arg(long)]
938        dry_run: bool,
939        #[arg(long, default_value = DEFAULT_RPC_URL)]
940        url: String,
941    },
942    /// Delete an attachment.
943    Delete {
944        key: String,
945        #[arg(long, default_value = DEFAULT_RPC_URL)]
946        url: String,
947        #[arg(long)]
948        dry_run: bool,
949    },
950    /// Trigger Zotero's Find Available PDF for a parent item.
951    #[command(name = "find-pdf")]
952    FindPdf {
953        #[arg(long)]
954        parent: String,
955        #[arg(long, default_value = DEFAULT_RPC_URL)]
956        url: String,
957    },
958}
959
960#[derive(Debug, Subcommand)]
961enum NotesCommand {
962    /// List notes attached to a parent item.
963    List {
964        #[arg(long)]
965        parent: String,
966        #[arg(long, default_value_t = 50)]
967        limit: u64,
968        #[arg(long, default_value_t = 0)]
969        offset: u64,
970        #[arg(long, default_value = DEFAULT_RPC_URL)]
971        url: String,
972    },
973    /// Get a single note by key.
974    Get {
975        note_key: String,
976        #[arg(long, default_value = DEFAULT_RPC_URL)]
977        url: String,
978    },
979    /// Create a note attached to a parent item.
980    Create {
981        #[arg(long)]
982        parent: String,
983        #[arg(long)]
984        content: String,
985        #[arg(long = "tag")]
986        tags: Vec<String>,
987        #[arg(long)]
988        dry_run: bool,
989        #[arg(long, default_value = DEFAULT_RPC_URL)]
990        url: String,
991    },
992    /// Update the content of an existing note.
993    Update {
994        note_key: String,
995        #[arg(long)]
996        content: String,
997        #[arg(long)]
998        dry_run: bool,
999        #[arg(long, default_value = DEFAULT_RPC_URL)]
1000        url: String,
1001    },
1002    /// Delete a note by key.
1003    Delete {
1004        note_key: String,
1005        #[arg(long)]
1006        dry_run: bool,
1007        #[arg(long, default_value = DEFAULT_RPC_URL)]
1008        url: String,
1009    },
1010    /// Search notes by text content.
1011    Search {
1012        query: String,
1013        #[arg(long, default_value_t = 50)]
1014        limit: u64,
1015        #[arg(long, default_value = DEFAULT_RPC_URL)]
1016        url: String,
1017    },
1018}
1019
1020#[derive(Debug, Subcommand)]
1021enum CollectionsCommand {
1022    /// List all collections in the user library (flat).
1023    List {
1024        #[arg(long, default_value = DEFAULT_RPC_URL)]
1025        url: String,
1026    },
1027    /// Print the collection hierarchy as a tree.
1028    Tree {
1029        #[arg(long, default_value = DEFAULT_RPC_URL)]
1030        url: String,
1031    },
1032    /// Get a single collection's metadata.
1033    Get {
1034        name_or_id: String,
1035        #[arg(long, default_value = DEFAULT_RPC_URL)]
1036        url: String,
1037    },
1038    /// List all items in a collection.
1039    #[command(name = "get-items", visible_alias = "items")]
1040    GetItems {
1041        name_or_id: String,
1042        #[arg(long)]
1043        limit: Option<u64>,
1044        #[arg(long, default_value_t = 0)]
1045        offset: u64,
1046        #[arg(long, default_value = DEFAULT_RPC_URL)]
1047        url: String,
1048    },
1049    /// Show item/attachment/note/subcollection counts for a collection.
1050    Stats {
1051        name_or_id: String,
1052        #[arg(long, default_value = DEFAULT_RPC_URL)]
1053        url: String,
1054    },
1055    /// Rename a collection.
1056    Rename {
1057        old_name: String,
1058        new_name: String,
1059        #[arg(long, default_value = DEFAULT_RPC_URL)]
1060        url: String,
1061        #[arg(long)]
1062        dry_run: bool,
1063    },
1064    /// Create a collection, optionally nested under a parent.
1065    Create {
1066        name: String,
1067        #[arg(long)]
1068        parent: Option<String>,
1069        #[arg(long, default_value = DEFAULT_RPC_URL)]
1070        url: String,
1071        #[arg(long)]
1072        dry_run: bool,
1073    },
1074    /// Delete a collection.
1075    Delete {
1076        name_or_id: String,
1077        #[arg(long, default_value = DEFAULT_RPC_URL)]
1078        url: String,
1079        #[arg(long)]
1080        dry_run: bool,
1081    },
1082    /// Add existing items to a collection.
1083    #[command(name = "add-items")]
1084    AddItems {
1085        collection: String,
1086        item_keys: Vec<String>,
1087        #[arg(long, default_value = DEFAULT_RPC_URL)]
1088        url: String,
1089        #[arg(long)]
1090        dry_run: bool,
1091    },
1092    /// Remove items from a collection.
1093    #[command(name = "remove-items")]
1094    RemoveItems {
1095        collection: String,
1096        item_keys: Vec<String>,
1097        #[arg(long, default_value = DEFAULT_RPC_URL)]
1098        url: String,
1099        #[arg(long)]
1100        dry_run: bool,
1101    },
1102}
1103
1104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1105enum JsonStyle {
1106    /// Matches Python's top-level `ping` command (`json.dumps` defaults).
1107    PythonCompact,
1108    /// Matches namespace commands that route through Python `emit(..., indent=2)`.
1109    Pretty,
1110}
1111
1112enum ParseOutcome<T> {
1113    Command(T),
1114    Display(String),
1115}
1116
1117fn parse_cli<T>(
1118    args: impl IntoIterator<Item = impl Into<std::ffi::OsString> + Clone>,
1119) -> Result<ParseOutcome<T>, String>
1120where
1121    T: Parser,
1122{
1123    match T::try_parse_from(args) {
1124        Ok(cli) => Ok(ParseOutcome::Command(cli)),
1125        Err(err)
1126            if matches!(
1127                err.kind(),
1128                ErrorKind::DisplayHelp | ErrorKind::DisplayVersion
1129            ) =>
1130        {
1131            Ok(ParseOutcome::Display(err.to_string()))
1132        }
1133        Err(err) => Err(err.to_string()),
1134    }
1135}
1136
1137pub fn format_error_json(message: &str) -> String {
1138    let message = message.trim_end();
1139    let (code, message) = split_error_code(message).unwrap_or(("RUNTIME_ERROR", message));
1140    serde_json::json!({"error": {"code": code, "message": message}}).to_string()
1141}
1142
1143fn split_error_code(message: &str) -> Option<(&str, &str)> {
1144    let (code, rest) = message.split_once(':')?;
1145    if !code.is_empty()
1146        && code
1147            .chars()
1148            .all(|ch| ch.is_ascii_uppercase() || ch.is_ascii_digit() || ch == '_')
1149    {
1150        Some((code, rest.trim_start()))
1151    } else {
1152        None
1153    }
1154}
1155
1156pub fn run(
1157    args: impl IntoIterator<Item = impl Into<std::ffi::OsString> + Clone>,
1158) -> Result<String, String> {
1159    // Emit plugin hint for Claude Code discovery
1160    if std::env::var("CLAUDECODE").as_deref() == Ok("1") {
1161        eprintln!(r#"<claude-code-hint v="1" type="plugin" value="zotron@dianzuan/zotron" />"#);
1162    }
1163
1164    let cli = match parse_cli::<Cli>(args)? {
1165        ParseOutcome::Command(cli) => cli,
1166        ParseOutcome::Display(output) => return Ok(output),
1167    };
1168    let url = command_url(&cli.command);
1169    let mut client = ZoteroRpc::new(url);
1170    run_command(cli.command, &mut client)
1171}
1172
1173pub fn run_with_client(
1174    args: impl IntoIterator<Item = impl Into<std::ffi::OsString> + Clone>,
1175    client: &mut impl RpcCaller,
1176) -> Result<String, String> {
1177    let cli = match parse_cli::<Cli>(args)? {
1178        ParseOutcome::Command(cli) => cli,
1179        ParseOutcome::Display(output) => return Ok(output),
1180    };
1181    run_command(cli.command, client)
1182}
1183
1184fn rag_command_url(command: &RagCommand) -> String {
1185    match command {
1186        RagCommand::Providers => DEFAULT_RPC_URL.to_string(),
1187        RagCommand::Embed { .. } => DEFAULT_RPC_URL.to_string(),
1188        RagCommand::Status { url, .. } => url.clone(),
1189        RagCommand::Search { url, .. } => url.clone(),
1190    }
1191}
1192
1193fn command_url(command: &Command) -> String {
1194    match command {
1195        Command::Ping { url }
1196        | Command::Rpc { url, .. }
1197        | Command::Push { url, .. }
1198        | Command::FindPdfs { url, .. } => url.clone(),
1199        Command::Ocr { command } => match command {
1200            OcrCommand::Providers => DEFAULT_RPC_URL.to_string(),
1201            OcrCommand::Run { .. } => DEFAULT_RPC_URL.to_string(),
1202            OcrCommand::Status { url, .. } => url.clone(),
1203            OcrCommand::Process { url, .. } => url.clone(),
1204        },
1205        Command::Rag { command } => rag_command_url(command),
1206        Command::System { command } => match command {
1207            SystemCommand::Version { url }
1208            | SystemCommand::Libraries { url }
1209            | SystemCommand::LibraryStats { url, .. }
1210            | SystemCommand::Schema { url, .. }
1211            | SystemCommand::CurrentCollection { url }
1212            | SystemCommand::ListMethods { url }
1213            | SystemCommand::Describe { url, .. } => url.clone(),
1214        },
1215        Command::Search(ref args) => match &args.management {
1216            Some(SearchManagementCommand::SavedSearches { url })
1217            | Some(SearchManagementCommand::CreateSaved { url, .. })
1218            | Some(SearchManagementCommand::DeleteSaved { url, .. }) => url.clone(),
1219            None => args.url.clone(),
1220        },
1221        Command::Items { command } => match command {
1222            ItemsCommand::Add { url, .. }
1223            | ItemsCommand::Create { url, .. }
1224            | ItemsCommand::Update { url, .. }
1225            | ItemsCommand::Delete { url, .. }
1226            | ItemsCommand::Trash { url, .. }
1227            | ItemsCommand::Restore { url, .. }
1228            | ItemsCommand::MergeDuplicates { url, .. }
1229            | ItemsCommand::AddRelated { url, .. }
1230            | ItemsCommand::RemoveRelated { url, .. }
1231            | ItemsCommand::Get { url, .. }
1232            | ItemsCommand::List { url, .. }
1233            | ItemsCommand::FindDuplicates { url }
1234            | ItemsCommand::Recent { url, .. }
1235            | ItemsCommand::Fulltext { url, .. }
1236            | ItemsCommand::Related { url, .. }
1237            | ItemsCommand::CitationKey { url, .. } => url.clone(),
1238        },
1239        Command::Collections { command } => match command {
1240            CollectionsCommand::List { url }
1241            | CollectionsCommand::Tree { url }
1242            | CollectionsCommand::Get { url, .. }
1243            | CollectionsCommand::GetItems { url, .. }
1244            | CollectionsCommand::Stats { url, .. }
1245            | CollectionsCommand::Rename { url, .. }
1246            | CollectionsCommand::Create { url, .. }
1247            | CollectionsCommand::Delete { url, .. }
1248            | CollectionsCommand::AddItems { url, .. }
1249            | CollectionsCommand::RemoveItems { url, .. } => url.clone(),
1250        },
1251        Command::Notes { command } => match command {
1252            NotesCommand::List { url, .. }
1253            | NotesCommand::Get { url, .. }
1254            | NotesCommand::Create { url, .. }
1255            | NotesCommand::Update { url, .. }
1256            | NotesCommand::Delete { url, .. }
1257            | NotesCommand::Search { url, .. } => url.clone(),
1258        },
1259        Command::Attachments { command } => match command {
1260            AttachmentsCommand::List { url, .. }
1261            | AttachmentsCommand::Get { url, .. }
1262            | AttachmentsCommand::Fulltext { url, .. }
1263            | AttachmentsCommand::Path { url, .. }
1264            | AttachmentsCommand::Add { url, .. }
1265            | AttachmentsCommand::Delete { url, .. }
1266            | AttachmentsCommand::FindPdf { url, .. } => url.clone(),
1267        },
1268        Command::Settings { command } => match command {
1269            SettingsCommand::Get { url, .. }
1270            | SettingsCommand::List { url }
1271            | SettingsCommand::Set { url, .. } => url.clone(),
1272        },
1273        Command::Tags { command } => match command {
1274            TagsCommand::List { url, .. }
1275            | TagsCommand::Rename { url, .. }
1276            | TagsCommand::Delete { url, .. }
1277            | TagsCommand::Add { url, .. }
1278            | TagsCommand::Remove { url, .. } => url.clone(),
1279        },
1280        Command::Export(ref args) => args.url.clone(),
1281        Command::Annotations { command } => match command {
1282            AnnotationsCommand::List { url, .. }
1283            | AnnotationsCommand::Create { url, .. }
1284            | AnnotationsCommand::Delete { url, .. } => url.clone(),
1285        },
1286    }
1287}
1288
1289fn run_ocr_command(command: OcrCommand, client: &mut impl RpcCaller) -> Result<String, String> {
1290    if let OcrCommand::Providers = &command {
1291        return format_json(
1292            &serde_json::json!({ "providers": ocr_provider_specs() }),
1293            JsonStyle::Pretty,
1294        );
1295    }
1296    let value = match command {
1297        OcrCommand::Providers => unreachable!(),
1298        OcrCommand::Run {
1299            provider,
1300            input,
1301            file,
1302            item_key,
1303            attachment_key,
1304            mime_type,
1305            endpoint,
1306            api_key_env,
1307        } => run_ocr_run_command(OcrRunOptions {
1308            provider,
1309            input,
1310            file,
1311            item_key,
1312            attachment_key,
1313            mime_type,
1314            endpoint,
1315            api_key_env,
1316        })?,
1317        OcrCommand::Status { collection, .. } => run_ocr_status_command(client, collection)?,
1318        OcrCommand::Process {
1319            provider,
1320            parent,
1321            attachment,
1322            source_url,
1323            result_dir,
1324            result_zip,
1325            provider_endpoint,
1326            api_key_env,
1327            poll_interval_seconds,
1328            timeout_seconds,
1329            chunk_chars,
1330            ..
1331        } => run_ocr_process_command(
1332            client,
1333            OcrProcessOptions {
1334                provider,
1335                parent,
1336                attachment,
1337                source_url,
1338                result_dir,
1339                result_zip,
1340                provider_endpoint,
1341                api_key_env,
1342                poll_interval_seconds,
1343                timeout_seconds,
1344                chunk_chars,
1345            },
1346        )?,
1347    };
1348    format_json(&value, JsonStyle::PythonCompact)
1349}
1350
1351struct OcrProcessOptions {
1352    provider: String,
1353    parent: String,
1354    attachment: Option<String>,
1355    source_url: Option<String>,
1356    result_dir: Option<String>,
1357    result_zip: Option<String>,
1358    provider_endpoint: Option<String>,
1359    api_key_env: String,
1360    poll_interval_seconds: u64,
1361    timeout_seconds: u64,
1362    chunk_chars: usize,
1363}
1364
1365struct OcrRunOptions {
1366    provider: String,
1367    input: Option<String>,
1368    file: Option<String>,
1369    item_key: Option<String>,
1370    attachment_key: Option<String>,
1371    mime_type: Option<String>,
1372    endpoint: Option<String>,
1373    api_key_env: Option<String>,
1374}
1375
1376fn run_ocr_run_command(options: OcrRunOptions) -> Result<Value, String> {
1377    let input: OcrRequestInput = match (options.input, options.file) {
1378        (Some(input), None) => read_json_input(&input)?,
1379        (None, Some(file)) => ocr_input_from_file(
1380            file,
1381            options.item_key,
1382            options.attachment_key,
1383            options.mime_type,
1384        )?,
1385        (Some(_), Some(_)) => {
1386            return Err("INVALID_ARGS: use either --input or --file, not both".to_string())
1387        }
1388        (None, None) => return Err("INVALID_ARGS: provide --input JSON or --file".to_string()),
1389    };
1390    let request = build_ocr_provider_request(&options.provider, &input)?;
1391    let payload = if request.command.is_empty() {
1392        let method = request
1393            .method
1394            .ok_or_else(|| format!("OCR provider {} missing HTTP method", request.provider))?;
1395        let auth_scheme = raw_ocr_provider_spec(&options.provider)?.auth;
1396        let mut transport =
1397            provider_http_transport_with_auth(options.api_key_env.as_deref(), auth_scheme)?;
1398        transport.post_json(&ProviderHttpInvocation {
1399            provider: request.provider.to_string(),
1400            style: request.style.to_string(),
1401            method: method.to_string(),
1402            url: options
1403                .endpoint
1404                .or_else(|| request.url.map(ToString::to_string)),
1405            auth_header_name: request.auth_header.map(ToString::to_string),
1406            auth_header_value: None,
1407            body: request.body,
1408        })?
1409    } else {
1410        let mut command_runner = StdProviderCommandRunner;
1411        command_runner.run_json(&request.command)?
1412    };
1413    let blocks = match parse_ocr_provider_response(
1414        request.provider,
1415        &payload,
1416        &input.item_key,
1417        &input.attachment_key,
1418    ) {
1419        Ok(blocks) => blocks,
1420        Err(err) => {
1421            if let Some(task) = ocr_async_task_result(request.provider, &payload) {
1422                return Ok(task);
1423            }
1424            return Err(err);
1425        }
1426    };
1427
1428    Ok(serde_json::json!({
1429        "provider": request.provider,
1430        "blocks": blocks,
1431    }))
1432}
1433
1434fn run_ocr_process_command(
1435    client: &mut impl RpcCaller,
1436    mut options: OcrProcessOptions,
1437) -> Result<Value, String> {
1438    let spec = raw_ocr_provider_spec(&options.provider)?;
1439
1440    let attachment = match options.attachment.take() {
1441        Some(key) => key,
1442        None => resolve_first_pdf_attachment_key(client, &options.parent)?,
1443    };
1444    options.attachment = Some(attachment.clone());
1445
1446    let attachment_path = resolve_attachment_path(client, &attachment)?;
1447    let storage_dir = attachment_path
1448        .parent()
1449        .ok_or_else(|| {
1450            format!(
1451                "ATTACHMENT_PATH_INVALID: attachment path has no parent directory: {}",
1452                attachment_path.display()
1453            )
1454        })?
1455        .to_path_buf();
1456
1457    match spec.provider_key {
1458        "mineru" | "mineru-cli" => {
1459            if options.result_dir.is_some() && options.result_zip.is_some() {
1460                return Err("INVALID_ARGS: use either --result-dir or --result-zip, not both".to_string());
1461            }
1462            if options.source_url.is_some()
1463                && (options.result_dir.is_some() || options.result_zip.is_some())
1464            {
1465                return Err(
1466                    "INVALID_ARGS: --source-url cannot be combined with --result-dir/--result-zip"
1467                        .to_string(),
1468                );
1469            }
1470            let file_name = attachment_path
1471                .file_name()
1472                .and_then(|name| name.to_str())
1473                .unwrap_or("document.pdf")
1474                .to_string();
1475            let source = load_mineru_result_source(&options, &attachment_path, &file_name)?;
1476            let artifacts = persist_mineru_result_sidecars(
1477                &storage_dir, &options.parent, &attachment,
1478                &options.provider, &source, options.chunk_chars,
1479            )?;
1480            Ok(serde_json::json!({
1481                "provider": spec.provider_key,
1482                "status": "indexed",
1483                "item_key": options.parent,
1484                "attachment_key": attachment,
1485                "attachment_path": attachment_path,
1486                "storage_dir": storage_dir,
1487                "task_id": source.task_id,
1488                "state": source.state,
1489                "blocks": artifacts.block_count,
1490                "chunks": artifacts.chunk_count,
1491                "artifacts": artifacts.artifacts,
1492            }))
1493        }
1494        _ => {
1495            run_ocr_process_sync(
1496                client, &options, spec.provider_key,
1497                &attachment, &attachment_path, &storage_dir,
1498            )
1499        }
1500    }
1501}
1502
1503fn run_ocr_process_sync(
1504    client: &mut impl RpcCaller,
1505    options: &OcrProcessOptions,
1506    provider: &str,
1507    attachment_key: &str,
1508    attachment_path: &Path,
1509    storage_dir: &Path,
1510) -> Result<Value, String> {
1511    let api_url = if let Some(endpoint) = &options.provider_endpoint {
1512        endpoint.clone()
1513    } else {
1514        let settings = client.call("settings.getAll", None)?;
1515        settings.get("ocr.apiUrl")
1516            .and_then(Value::as_str)
1517            .unwrap_or("")
1518            .to_string()
1519    };
1520    if api_url.is_empty() {
1521        return Err(format!("MISSING_CONFIG: ocr.apiUrl not configured for provider {provider}"));
1522    }
1523
1524    let api_key = {
1525        let from_env = if !options.api_key_env.is_empty() {
1526            env::var(&options.api_key_env).ok().filter(|v| !v.is_empty())
1527        } else {
1528            None
1529        };
1530        from_env.unwrap_or_else(|| {
1531            client.call("settings.getRaw", Some(serde_json::json!({"key": "ocr.apiKey"})))
1532                .ok()
1533                .and_then(|raw| raw.get("ocr.apiKey").and_then(Value::as_str).map(String::from))
1534                .unwrap_or_default()
1535        })
1536    };
1537
1538    let pdf_bytes = fs::read(attachment_path)
1539        .map_err(|e| format!("READ_PDF_FAILED: {}: {e}", attachment_path.display()))?;
1540
1541    const MAX_PDF_SIZE: usize = 100 * 1024 * 1024; // 100 MB
1542    if pdf_bytes.len() > MAX_PDF_SIZE {
1543        return Err(format!(
1544            "PDF_TOO_LARGE: {} is {} MB, max {} MB",
1545            attachment_path.display(),
1546            pdf_bytes.len() / (1024 * 1024),
1547            MAX_PDF_SIZE / (1024 * 1024),
1548        ));
1549    }
1550
1551    let base64_pdf = format!("data:application/pdf;base64,{}", base64_encode(&pdf_bytes));
1552
1553    let input = OcrRequestInput {
1554        content_base64: base64_pdf,
1555        file_name: attachment_path
1556            .file_name()
1557            .and_then(|n| n.to_str())
1558            .unwrap_or("document.pdf")
1559            .to_string(),
1560        mime_type: "application/pdf".to_string(),
1561        item_key: options.parent.clone(),
1562        attachment_key: attachment_key.to_string(),
1563        source_url: None,
1564        local_path: Some(attachment_path.to_string_lossy().to_string()),
1565        output_dir: None,
1566    };
1567    let request = build_ocr_provider_request(provider, &input)?;
1568
1569    let payload = if request.command.is_empty() {
1570        let method = request
1571            .method
1572            .ok_or_else(|| format!("OCR provider {provider} missing HTTP method"))?;
1573        let spec = raw_ocr_provider_spec(provider)?;
1574
1575        let mut transport = if !api_key.is_empty() {
1576            match spec.auth {
1577                "bearer" => UreqProviderHttpTransport::with_bearer_token(&api_key),
1578                "token" => UreqProviderHttpTransport::with_api_key(format!("token {api_key}")),
1579                _ => UreqProviderHttpTransport::new(),
1580            }
1581        } else {
1582            UreqProviderHttpTransport::new()
1583        };
1584
1585        transport.post_json(&ProviderHttpInvocation {
1586            provider: request.provider.to_string(),
1587            style: request.style.to_string(),
1588            method: method.to_string(),
1589            url: Some(api_url),
1590            auth_header_name: request.auth_header.map(ToString::to_string),
1591            auth_header_value: None,
1592            body: request.body,
1593        })?
1594    } else {
1595        let mut runner = StdProviderCommandRunner;
1596        runner.run_json(&request.command)?
1597    };
1598
1599    let blocks = parse_ocr_provider_response(provider, &payload, &options.parent, attachment_key)?;
1600    let chunks = zotron_types::chunks_from_blocks(&blocks, options.chunk_chars);
1601
1602    let artifacts = vec![
1603        write_sidecar_json(
1604            storage_dir, &options.parent, attachment_key,
1605            MachineArtifactKind::OcrRaw, &payload,
1606        )?,
1607        write_sidecar_jsonl(
1608            storage_dir, &options.parent, attachment_key,
1609            MachineArtifactKind::Blocks, &blocks,
1610        )?,
1611        write_sidecar_jsonl(
1612            storage_dir, &options.parent, attachment_key,
1613            MachineArtifactKind::Chunks, &chunks,
1614        )?,
1615    ];
1616
1617    let embedding_count = embed_sidecar_chunks(client, storage_dir, &options.parent, attachment_key, &chunks);
1618
1619    Ok(serde_json::json!({
1620        "provider": provider,
1621        "status": "indexed",
1622        "item_key": options.parent,
1623        "attachment_key": attachment_key,
1624        "embeddings": embedding_count,
1625        "attachment_path": attachment_path,
1626        "storage_dir": storage_dir,
1627        "blocks": blocks.len(),
1628        "chunks": chunks.len(),
1629        "artifacts": artifacts,
1630    }))
1631}
1632
1633fn embed_sidecar_chunks(
1634    client: &mut impl RpcCaller,
1635    storage_dir: &Path,
1636    item_key: &str,
1637    _attachment_key: &str,
1638    chunks: &[zotron_types::StructureChunk],
1639) -> usize {
1640    let Ok((provider, model, api_url, api_key)) = fetch_embedding_settings(client) else {
1641        return 0;
1642    };
1643    if provider.is_empty() || (api_key.is_empty() && provider != "ollama") {
1644        return 0;
1645    }
1646    let emb_chunks: Vec<EmbeddingChunkInput> = chunks
1647        .iter()
1648        .map(|c| EmbeddingChunkInput {
1649            chunk_key: c.chunk_key.clone(),
1650            text: c.text.clone(),
1651        })
1652        .collect();
1653    if emb_chunks.is_empty() {
1654        return 0;
1655    }
1656    // Batch in groups of 20 to avoid API limits
1657    let batch_size = 20;
1658    let mut all_vectors: Vec<EmbeddingVector> = Vec::new();
1659    for batch in emb_chunks.chunks(batch_size) {
1660        let input = EmbeddingRequestInput {
1661            item_key: item_key.to_string(),
1662            chunks: batch.to_vec(),
1663            model: if model.is_empty() { None } else { Some(model.clone()) },
1664            url: if api_url.is_empty() { None } else { Some(api_url.clone()) },
1665            input_type: Some("document".to_string()),
1666        };
1667        let Ok(request) = build_embedding_provider_request(&provider, &input) else {
1668            break;
1669        };
1670        let Some(url) = request.url.as_deref() else { break };
1671        let mut http = ureq::post(url).set("Content-Type", "application/json");
1672        if let Some(auth) = request.auth_header {
1673            if !api_key.is_empty() {
1674                http = http.set(auth, &format!("Bearer {api_key}"));
1675            }
1676        }
1677        let Ok(resp) = http.send_json(&request.body) else { break };
1678        let Ok(payload): Result<Value, _> = resp.into_json() else { break };
1679        let Ok(vectors) = parse_embedding_provider_response(&provider, &payload, item_key, batch)
1680        else {
1681            break;
1682        };
1683        all_vectors.extend(vectors);
1684    }
1685    let count = all_vectors.len();
1686    if count > 0 {
1687        let filename = embedding_vector_filename(&provider, &model);
1688        let vectors_dir = storage_dir.join(".zotron").join("embeddings");
1689        let _ = fs::create_dir_all(&vectors_dir);
1690        let vectors_path = vectors_dir.join(&filename);
1691        let mut out = String::new();
1692        for v in &all_vectors {
1693            if let Ok(line) = serde_json::to_string(v) {
1694                out.push_str(&line);
1695                out.push('\n');
1696            }
1697        }
1698        let _ = fs::write(&vectors_path, &out);
1699    }
1700    count
1701}
1702
1703struct MineruResultSource {
1704    task_id: Option<String>,
1705    state: String,
1706    result_dir: PathBuf,
1707    raw_zip_bytes: Option<Vec<u8>>,
1708    task_status: Option<Value>,
1709    payload: Value,
1710    content_list_file: Option<PathBuf>,
1711    markdown: Option<String>,
1712}
1713
1714struct PersistedOcrArtifacts {
1715    block_count: usize,
1716    chunk_count: usize,
1717    artifacts: Vec<Value>,
1718}
1719
1720fn resolve_attachment_path(
1721    client: &mut impl RpcCaller,
1722    attachment_key: &str,
1723) -> Result<PathBuf, String> {
1724    let payload = client.call(
1725        "attachments.getPath",
1726        Some(serde_json::json!({"key": attachment_key})),
1727    )?;
1728    let raw_path = payload
1729        .get("path")
1730        .and_then(Value::as_str)
1731        .filter(|path| !path.trim().is_empty())
1732        .ok_or_else(|| {
1733            format!("ATTACHMENT_PATH_NOT_FOUND: attachment {attachment_key} has no local PDF path")
1734        })?;
1735    Ok(PathBuf::from(local_path_from_zotero_path(raw_path)))
1736}
1737
1738/// Resolve the first PDF attachment key for a parent item via `attachments.list`.
1739fn resolve_first_pdf_attachment_key(
1740    client: &mut impl RpcCaller,
1741    parent_key: &str,
1742) -> Result<String, String> {
1743    let response = client.call(
1744        "attachments.list",
1745        Some(serde_json::json!({"parentKey": parent_key})),
1746    )?;
1747    // The XPI returns {items: [...], total: N}.
1748    let attachments = response
1749        .get("items")
1750        .and_then(Value::as_array)
1751        .or_else(|| response.as_array())
1752        .ok_or_else(|| {
1753            format!("NO_PDF_ATTACHMENT: no attachments found for item {parent_key}")
1754        })?;
1755    for attachment in attachments {
1756        if is_pdf_attachment(attachment) {
1757            if let Some(key) = attachment.get("key").and_then(Value::as_str) {
1758                return Ok(key.to_string());
1759            }
1760        }
1761    }
1762    Err(format!(
1763        "NO_PDF_ATTACHMENT: no PDF attachment found for item {parent_key}"
1764    ))
1765}
1766
1767fn load_mineru_result_source(
1768    options: &OcrProcessOptions,
1769    attachment_path: &Path,
1770    file_name: &str,
1771) -> Result<MineruResultSource, String> {
1772    if let Some(result_dir) = options.result_dir.as_deref() {
1773        return mineru_result_source_from_dir(PathBuf::from(result_dir), None, None, None);
1774    }
1775    if let Some(result_zip) = options.result_zip.as_deref() {
1776        let zip_path = PathBuf::from(result_zip);
1777        let zip_bytes = fs::read(&zip_path)
1778            .map_err(|err| format!("read MinerU result zip {}: {err}", zip_path.display()))?;
1779        let result_dir = extract_zip_bytes_to_temp("zotron-mineru-result", &zip_bytes)?;
1780        return mineru_result_source_from_dir(result_dir, Some(zip_bytes), None, None);
1781    }
1782
1783    let Some(source_url) = options
1784        .source_url
1785        .as_deref()
1786        .filter(|value| !value.trim().is_empty())
1787    else {
1788        return submit_mineru_local_file(options, attachment_path, file_name);
1789    };
1790    let input = OcrRequestInput {
1791        item_key: options.parent.clone(),
1792        attachment_key: options.attachment.clone().expect("attachment resolved"),
1793        file_name: file_name.to_string(),
1794        mime_type: "application/pdf".to_string(),
1795        content_base64: format!("url:{source_url}"),
1796        source_url: Some(source_url.to_string()),
1797        local_path: None,
1798        output_dir: None,
1799    };
1800    let task = submit_mineru_task(
1801        &options.provider,
1802        &input,
1803        options.provider_endpoint.clone(),
1804        &options.api_key_env,
1805    )?;
1806    let task_id = task
1807        .get("data")
1808        .and_then(|data| data.get("task_id"))
1809        .and_then(Value::as_str)
1810        .ok_or_else(|| "MinerU submit response missing data.task_id".to_string())?
1811        .to_string();
1812    let auth_header = provider_auth_header_value(&options.api_key_env, "bearer")?;
1813    let status = poll_mineru_task(
1814        options.provider_endpoint.as_deref(),
1815        &task_id,
1816        &auth_header,
1817        options.poll_interval_seconds,
1818        options.timeout_seconds,
1819    )?;
1820    let zip_url = status
1821        .pointer("/data/full_zip_url")
1822        .or_else(|| status.pointer("/data/result/full_zip_url"))
1823        .and_then(Value::as_str)
1824        .ok_or_else(|| "MinerU completed task missing data.full_zip_url".to_string())?;
1825    let zip_bytes = download_bytes(zip_url)?;
1826    let result_dir = extract_zip_bytes_to_temp("zotron-mineru-result", &zip_bytes)?;
1827    mineru_result_source_from_dir(result_dir, Some(zip_bytes), Some(status), Some(task_id))
1828}
1829
1830fn submit_mineru_local_file(
1831    options: &OcrProcessOptions,
1832    attachment_path: &Path,
1833    file_name: &str,
1834) -> Result<MineruResultSource, String> {
1835    let auth_header = provider_auth_header_value(&options.api_key_env, "bearer")?;
1836    let upload_request = create_mineru_file_upload(
1837        options.provider_endpoint.as_deref(),
1838        file_name,
1839        options.attachment.as_deref().expect("attachment resolved"),
1840        &auth_header,
1841    )?;
1842    let upload_url = upload_request
1843        .pointer("/data/file_urls/0")
1844        .or_else(|| upload_request.pointer("/data/fileUrls/0"))
1845        .and_then(Value::as_str)
1846        .ok_or_else(|| "MinerU upload URL response missing data.file_urls[0]".to_string())?;
1847    let batch_id = upload_request
1848        .pointer("/data/batch_id")
1849        .or_else(|| upload_request.pointer("/data/batchId"))
1850        .and_then(Value::as_str)
1851        .ok_or_else(|| "MinerU upload URL response missing data.batch_id".to_string())?
1852        .to_string();
1853    let bytes = fs::read(attachment_path)
1854        .map_err(|err| format!("read attachment PDF {}: {err}", attachment_path.display()))?;
1855    put_bytes(upload_url, &bytes)?;
1856    let status = poll_mineru_batch(
1857        options.provider_endpoint.as_deref(),
1858        &batch_id,
1859        &auth_header,
1860        options.poll_interval_seconds,
1861        options.timeout_seconds,
1862    )?;
1863    let zip_url = mineru_batch_zip_url(&status)
1864        .ok_or_else(|| "MinerU completed batch missing full_zip_url".to_string())?;
1865    let zip_bytes = download_bytes(&zip_url)?;
1866    let result_dir = extract_zip_bytes_to_temp("zotron-mineru-result", &zip_bytes)?;
1867    mineru_result_source_from_dir(result_dir, Some(zip_bytes), Some(status), Some(batch_id))
1868}
1869
1870fn create_mineru_file_upload(
1871    endpoint: Option<&str>,
1872    file_name: &str,
1873    data_id: &str,
1874    auth_header: &str,
1875) -> Result<Value, String> {
1876    let url = mineru_file_urls_url(endpoint);
1877    let body = serde_json::json!({
1878        "files": [{"name": file_name, "data_id": data_id}],
1879        "model_version": "vlm",
1880        "is_ocr": false,
1881        "enable_formula": true,
1882        "enable_table": true,
1883        "language": "ch",
1884        "page_ranges": "1-200",
1885    });
1886    ureq::post(&url)
1887        .set("Authorization", auth_header)
1888        .send_json(body)
1889        .map_err(|err| format!("POST {url} failed: {err}"))?
1890        .into_json::<Value>()
1891        .map_err(|err| format!("POST {url} returned invalid JSON: {err}"))
1892}
1893
1894fn put_bytes(url: &str, bytes: &[u8]) -> Result<(), String> {
1895    ureq::put(url)
1896        .send_bytes(bytes)
1897        .map_err(|err| format!("PUT {url} failed: {err}"))?;
1898    Ok(())
1899}
1900
1901fn submit_mineru_task(
1902    provider: &str,
1903    input: &OcrRequestInput,
1904    endpoint: Option<String>,
1905    api_key_env: &str,
1906) -> Result<Value, String> {
1907    let request = build_ocr_provider_request(provider, input)?;
1908    let method = request
1909        .method
1910        .ok_or_else(|| "MinerU provider missing HTTP method".to_string())?;
1911    let mut transport = provider_http_transport_with_auth(Some(api_key_env), "bearer")?;
1912    transport.post_json(&ProviderHttpInvocation {
1913        provider: request.provider.to_string(),
1914        style: request.style.to_string(),
1915        method: method.to_string(),
1916        url: endpoint.or_else(|| request.url.map(ToString::to_string)),
1917        auth_header_name: request.auth_header.map(ToString::to_string),
1918        auth_header_value: None,
1919        body: request.body,
1920    })
1921}
1922
1923fn poll_mineru_task(
1924    endpoint: Option<&str>,
1925    task_id: &str,
1926    auth_header: &str,
1927    poll_interval_seconds: u64,
1928    timeout_seconds: u64,
1929) -> Result<Value, String> {
1930    let url = mineru_task_status_url(endpoint, task_id);
1931    let started = Instant::now();
1932    loop {
1933        let status = get_json_with_auth(&url, auth_header)?;
1934        let state = status
1935            .pointer("/data/state")
1936            .or_else(|| status.pointer("/data/status"))
1937            .and_then(Value::as_str)
1938            .unwrap_or("unknown");
1939        match state {
1940            "done" | "finished" | "success" => return Ok(status),
1941            "failed" | "error" => return Err(format!("MinerU task {task_id} failed: {status}")),
1942            _ => {
1943                if started.elapsed() >= Duration::from_secs(timeout_seconds) {
1944                    return Err(format!(
1945                        "MinerU task {task_id} timed out after {timeout_seconds}s with state {state}"
1946                    ));
1947                }
1948                thread::sleep(Duration::from_secs(poll_interval_seconds.max(1)));
1949            }
1950        }
1951    }
1952}
1953
1954fn mineru_task_status_url(endpoint: Option<&str>, task_id: &str) -> String {
1955    let base = endpoint
1956        .unwrap_or("https://mineru.net/api/v4/extract/task")
1957        .trim_end_matches('/');
1958    if base.ends_with("/extract/task") {
1959        format!("{base}/{task_id}")
1960    } else {
1961        format!("{base}/extract/task/{task_id}")
1962    }
1963}
1964
1965fn mineru_file_urls_url(endpoint: Option<&str>) -> String {
1966    let base = mineru_api_base(endpoint);
1967    format!("{base}/file-urls/batch")
1968}
1969
1970fn mineru_batch_status_url(endpoint: Option<&str>, batch_id: &str) -> String {
1971    let base = mineru_api_base(endpoint);
1972    format!("{base}/extract-results/batch/{batch_id}")
1973}
1974
1975fn mineru_api_base(endpoint: Option<&str>) -> String {
1976    let base = endpoint
1977        .unwrap_or("https://mineru.net/api/v4/extract/task")
1978        .trim_end_matches('/');
1979    if let Some(stripped) = base.strip_suffix("/extract/task") {
1980        return stripped.to_string();
1981    }
1982    if let Some(stripped) = base.strip_suffix("/extract") {
1983        return stripped.to_string();
1984    }
1985    base.to_string()
1986}
1987
1988fn poll_mineru_batch(
1989    endpoint: Option<&str>,
1990    batch_id: &str,
1991    auth_header: &str,
1992    poll_interval_seconds: u64,
1993    timeout_seconds: u64,
1994) -> Result<Value, String> {
1995    let url = mineru_batch_status_url(endpoint, batch_id);
1996    let started = Instant::now();
1997    loop {
1998        let status = get_json_with_auth(&url, auth_header)?;
1999        let state = mineru_batch_state(&status).unwrap_or("unknown");
2000        match state {
2001            "done" | "finished" | "success" => return Ok(status),
2002            "failed" | "error" => return Err(format!("MinerU batch {batch_id} failed: {status}")),
2003            _ => {
2004                if started.elapsed() >= Duration::from_secs(timeout_seconds) {
2005                    return Err(format!(
2006                        "MinerU batch {batch_id} timed out after {timeout_seconds}s with state {state}"
2007                    ));
2008                }
2009                thread::sleep(Duration::from_secs(poll_interval_seconds.max(1)));
2010            }
2011        }
2012    }
2013}
2014
2015fn mineru_batch_state(status: &Value) -> Option<&str> {
2016    status
2017        .pointer("/data/extract_result/0/state")
2018        .or_else(|| status.pointer("/data/extractResult/0/state"))
2019        .or_else(|| status.pointer("/data/state"))
2020        .and_then(Value::as_str)
2021}
2022
2023fn mineru_batch_zip_url(status: &Value) -> Option<String> {
2024    status
2025        .pointer("/data/extract_result/0/full_zip_url")
2026        .or_else(|| status.pointer("/data/extractResult/0/full_zip_url"))
2027        .or_else(|| status.pointer("/data/full_zip_url"))
2028        .and_then(Value::as_str)
2029        .map(ToString::to_string)
2030}
2031
2032fn provider_auth_header_value(api_key_env: &str, auth_scheme: &str) -> Result<String, String> {
2033    let token = env::var(api_key_env)
2034        .map_err(|_| format!("missing provider credential env var {api_key_env}"))?;
2035    let token = token.trim();
2036    if token.is_empty() {
2037        return Err(format!(
2038            "provider credential env var {api_key_env} is empty"
2039        ));
2040    }
2041    Ok(match auth_scheme {
2042        "bearer" if token.starts_with("Bearer ") => token.to_string(),
2043        "bearer" => format!("Bearer {token}"),
2044        "token" if token.starts_with("token ") => token.to_string(),
2045        "token" => format!("token {token}"),
2046        _ => token.to_string(),
2047    })
2048}
2049
2050fn get_json_with_auth(url: &str, auth_header: &str) -> Result<Value, String> {
2051    ureq::get(url)
2052        .set("Authorization", auth_header)
2053        .call()
2054        .map_err(|err| format!("GET {url} failed: {err}"))?
2055        .into_json::<Value>()
2056        .map_err(|err| format!("GET {url} returned invalid JSON: {err}"))
2057}
2058
2059fn download_bytes(url: &str) -> Result<Vec<u8>, String> {
2060    let response = ureq::get(url)
2061        .call()
2062        .map_err(|err| format!("download {url} failed: {err}"))?;
2063    let mut bytes = Vec::new();
2064    response
2065        .into_reader()
2066        .read_to_end(&mut bytes)
2067        .map_err(|err| format!("read download {url}: {err}"))?;
2068    Ok(bytes)
2069}
2070
2071fn extract_zip_bytes_to_temp(prefix: &str, zip_bytes: &[u8]) -> Result<PathBuf, String> {
2072    let dir = unique_temp_path(prefix);
2073    fs::create_dir_all(&dir).map_err(|err| format!("create temp dir {}: {err}", dir.display()))?;
2074    let zip_path = dir.with_extension("zip");
2075    fs::write(&zip_path, zip_bytes)
2076        .map_err(|err| format!("write temp zip {}: {err}", zip_path.display()))?;
2077    let output = ProcessCommand::new("unzip")
2078        .arg("-q")
2079        .arg("-o")
2080        .arg(&zip_path)
2081        .arg("-d")
2082        .arg(&dir)
2083        .output()
2084        .map_err(|err| format!("run unzip: {err}"))?;
2085    if !output.status.success() {
2086        return Err(format!(
2087            "unzip {} failed: {}",
2088            zip_path.display(),
2089            String::from_utf8_lossy(&output.stderr).trim()
2090        ));
2091    }
2092    Ok(dir)
2093}
2094
2095fn unique_temp_path(prefix: &str) -> PathBuf {
2096    let nanos = SystemTime::now()
2097        .duration_since(UNIX_EPOCH)
2098        .map(|duration| duration.as_nanos())
2099        .unwrap_or(0);
2100    env::temp_dir().join(format!("{prefix}-{}-{nanos}", std::process::id()))
2101}
2102
2103fn mineru_result_source_from_dir(
2104    result_dir: PathBuf,
2105    raw_zip_bytes: Option<Vec<u8>>,
2106    task_status: Option<Value>,
2107    task_id: Option<String>,
2108) -> Result<MineruResultSource, String> {
2109    let (payload, content_list_file) = mineru_payload_from_result_dir(&result_dir)?;
2110    let markdown = find_first_file_by_name(&result_dir, "full.md")
2111        .map(|path| {
2112            fs::read_to_string(&path)
2113                .map_err(|err| format!("read native markdown {}: {err}", path.display()))
2114        })
2115        .transpose()?;
2116    Ok(MineruResultSource {
2117        task_id,
2118        state: "done".to_string(),
2119        result_dir,
2120        raw_zip_bytes,
2121        task_status,
2122        payload,
2123        content_list_file,
2124        markdown,
2125    })
2126}
2127
2128fn mineru_payload_from_result_dir(result_dir: &Path) -> Result<(Value, Option<PathBuf>), String> {
2129    let v2 = find_first_file_with_suffix(result_dir, "_content_list_v2.json");
2130    if let Some(path) = v2 {
2131        let value = read_json_file(&path)?;
2132        return Ok((serde_json::json!({"content_list_v2": value}), Some(path)));
2133    }
2134    let content_list = find_first_file_with_suffix(result_dir, "_content_list.json");
2135    if let Some(path) = content_list {
2136        let value = read_json_file(&path)?;
2137        return Ok((serde_json::json!({"content_list": value}), Some(path)));
2138    }
2139    let layout = find_first_file_by_name(result_dir, "layout.json");
2140    if let Some(path) = layout {
2141        return Ok((read_json_file(&path)?, Some(path)));
2142    }
2143    let markdown = find_first_file_by_name(result_dir, "full.md");
2144    if let Some(path) = markdown {
2145        let text = fs::read_to_string(&path)
2146            .map_err(|err| format!("read native markdown {}: {err}", path.display()))?;
2147        return Ok((serde_json::json!({"result": text}), Some(path)));
2148    }
2149    Err(format!(
2150        "MinerU result directory {} missing content_list_v2/content_list/layout/full.md",
2151        result_dir.display()
2152    ))
2153}
2154
2155fn read_json_file(path: &Path) -> Result<Value, String> {
2156    let raw = fs::read_to_string(path).map_err(|err| format!("read {}: {err}", path.display()))?;
2157    serde_json::from_str(&raw).map_err(|err| format!("parse JSON {}: {err}", path.display()))
2158}
2159
2160fn persist_mineru_result_sidecars(
2161    storage_dir: &Path,
2162    item_key: &str,
2163    attachment_key: &str,
2164    provider: &str,
2165    source: &MineruResultSource,
2166    chunk_chars: usize,
2167) -> Result<PersistedOcrArtifacts, String> {
2168    let blocks = parse_ocr_provider_response(provider, &source.payload, item_key, attachment_key)?;
2169    let chunks = zotron_types::chunks_from_blocks(&blocks, chunk_chars);
2170    let assets = copy_mineru_assets(&source.result_dir, storage_dir)?;
2171    let raw_bundle = serde_json::json!({
2172        "provider": provider,
2173        "item_key": item_key,
2174        "attachment_key": attachment_key,
2175        "task_id": source.task_id,
2176        "state": source.state,
2177        "task_status": source.task_status,
2178        "content_list_file": source.content_list_file,
2179        "payload": source.payload,
2180    });
2181
2182    let mut artifacts = Vec::new();
2183    artifacts.push(write_sidecar_json(
2184        storage_dir,
2185        item_key,
2186        attachment_key,
2187        MachineArtifactKind::OcrRaw,
2188        &raw_bundle,
2189    )?);
2190    artifacts.push(write_sidecar_jsonl(
2191        storage_dir,
2192        item_key,
2193        attachment_key,
2194        MachineArtifactKind::Blocks,
2195        &blocks,
2196    )?);
2197    artifacts.push(write_sidecar_jsonl(
2198        storage_dir,
2199        item_key,
2200        attachment_key,
2201        MachineArtifactKind::Chunks,
2202        &chunks,
2203    )?);
2204    if let Some(markdown) = source.markdown.as_deref() {
2205        artifacts.push(write_sidecar_bytes(
2206            storage_dir,
2207            item_key,
2208            attachment_key,
2209            MachineArtifactKind::OcrNativeMarkdown,
2210            markdown.as_bytes(),
2211        )?);
2212    }
2213    artifacts.push(write_sidecar_json(
2214        storage_dir,
2215        item_key,
2216        attachment_key,
2217        MachineArtifactKind::OcrNativeAssets,
2218        &assets,
2219    )?);
2220    if let Some(bytes) = source.raw_zip_bytes.as_deref() {
2221        artifacts.push(write_extra_sidecar_bytes(
2222            storage_dir,
2223            ".zotron/ocr/latest.raw.zip",
2224            bytes,
2225        )?);
2226    }
2227
2228    Ok(PersistedOcrArtifacts {
2229        block_count: blocks.len(),
2230        chunk_count: chunks.len(),
2231        artifacts,
2232    })
2233}
2234
2235fn write_sidecar_json(
2236    storage_dir: &Path,
2237    item_key: &str,
2238    attachment_key: &str,
2239    kind: MachineArtifactKind,
2240    value: &Value,
2241) -> Result<Value, String> {
2242    let bytes = serde_json::to_vec_pretty(value).map_err(|err| err.to_string())?;
2243    write_sidecar_bytes(storage_dir, item_key, attachment_key, kind, &bytes)
2244}
2245
2246fn write_sidecar_jsonl<T: serde::Serialize>(
2247    storage_dir: &Path,
2248    item_key: &str,
2249    attachment_key: &str,
2250    kind: MachineArtifactKind,
2251    values: &[T],
2252) -> Result<Value, String> {
2253    let mut out = String::new();
2254    for value in values {
2255        out.push_str(&serde_json::to_string(value).map_err(|err| err.to_string())?);
2256        out.push('\n');
2257    }
2258    write_sidecar_bytes(storage_dir, item_key, attachment_key, kind, out.as_bytes())
2259}
2260
2261fn write_sidecar_bytes(
2262    storage_dir: &Path,
2263    item_key: &str,
2264    attachment_key: &str,
2265    kind: MachineArtifactKind,
2266    bytes: &[u8],
2267) -> Result<Value, String> {
2268    let record = write_machine_artifact_sidecar(storage_dir, item_key, attachment_key, kind, bytes)
2269        .map_err(|err| format!("write sidecar {:?}: {err}", kind))?;
2270    Ok(serde_json::json!({
2271        "kind": kind,
2272        "relative_path": record.relative_path,
2273        "absolute_path": record.absolute_path,
2274    }))
2275}
2276
2277fn write_extra_sidecar_bytes(
2278    storage_dir: &Path,
2279    relative_path: &str,
2280    bytes: &[u8],
2281) -> Result<Value, String> {
2282    let absolute_path = storage_dir.join(relative_path);
2283    if let Some(parent) = absolute_path.parent() {
2284        fs::create_dir_all(parent).map_err(|err| format!("create {}: {err}", parent.display()))?;
2285    }
2286    fs::write(&absolute_path, bytes)
2287        .map_err(|err| format!("write sidecar {}: {err}", absolute_path.display()))?;
2288    Ok(serde_json::json!({
2289        "kind": "ocr_raw_zip",
2290        "relative_path": relative_path,
2291        "absolute_path": absolute_path,
2292    }))
2293}
2294
2295fn copy_mineru_assets(result_dir: &Path, storage_dir: &Path) -> Result<Value, String> {
2296    let mut images = Vec::new();
2297    for file in collect_files(result_dir)? {
2298        if !is_image_file(&file) {
2299            continue;
2300        }
2301        let relative = file.strip_prefix(result_dir).unwrap_or(&file).to_path_buf();
2302        let destination = storage_dir.join(".zotron").join("ocr").join(&relative);
2303        if let Some(parent) = destination.parent() {
2304            fs::create_dir_all(parent)
2305                .map_err(|err| format!("create {}: {err}", parent.display()))?;
2306        }
2307        fs::copy(&file, &destination).map_err(|err| {
2308            format!(
2309                "copy MinerU asset {} to {}: {err}",
2310                file.display(),
2311                destination.display()
2312            )
2313        })?;
2314        images.push(serde_json::json!({
2315            "source_relative": relative,
2316            "sidecar_relative": PathBuf::from(".zotron").join("ocr").join(&relative),
2317            "absolute_path": destination,
2318        }));
2319    }
2320    Ok(serde_json::json!({
2321        "provider": "mineru",
2322        "images": images,
2323    }))
2324}
2325
2326fn is_image_file(path: &Path) -> bool {
2327    matches!(
2328        path.extension()
2329            .and_then(|ext| ext.to_str())
2330            .unwrap_or_default()
2331            .to_ascii_lowercase()
2332            .as_str(),
2333        "png" | "jpg" | "jpeg" | "webp" | "gif"
2334    )
2335}
2336
2337fn find_first_file_with_suffix(root: &Path, suffix: &str) -> Option<PathBuf> {
2338    collect_files(root).ok()?.into_iter().find(|path| {
2339        path.file_name()
2340            .and_then(|name| name.to_str())
2341            .is_some_and(|name| name.ends_with(suffix))
2342    })
2343}
2344
2345fn find_first_file_by_name(root: &Path, name: &str) -> Option<PathBuf> {
2346    collect_files(root).ok()?.into_iter().find(|path| {
2347        path.file_name()
2348            .and_then(|file_name| file_name.to_str())
2349            .is_some_and(|file_name| file_name == name)
2350    })
2351}
2352
2353fn collect_files(root: &Path) -> Result<Vec<PathBuf>, String> {
2354    let mut files = Vec::new();
2355    collect_files_into(root, &mut files)?;
2356    files.sort();
2357    Ok(files)
2358}
2359
2360fn collect_files_into(root: &Path, files: &mut Vec<PathBuf>) -> Result<(), String> {
2361    for entry in fs::read_dir(root).map_err(|err| format!("read dir {}: {err}", root.display()))? {
2362        let entry = entry.map_err(|err| format!("read dir entry {}: {err}", root.display()))?;
2363        let path = entry.path();
2364        let file_type = entry
2365            .file_type()
2366            .map_err(|err| format!("stat {}: {err}", path.display()))?;
2367        if file_type.is_dir() {
2368            collect_files_into(&path, files)?;
2369        } else if file_type.is_file() {
2370            files.push(path);
2371        }
2372    }
2373    Ok(())
2374}
2375
2376fn ocr_async_task_result(provider: &str, payload: &Value) -> Option<Value> {
2377    let data = payload.get("data")?;
2378    let task_id = data.get("task_id").and_then(Value::as_str)?;
2379    Some(serde_json::json!({
2380        "provider": provider,
2381        "status": "submitted",
2382        "task_id": task_id,
2383        "state": data.get("state").and_then(Value::as_str).unwrap_or("submitted"),
2384        "result_url": data.get("full_zip_url").or_else(|| data.get("markdown_url")).cloned(),
2385        "raw": payload,
2386    }))
2387}
2388
2389fn ocr_input_from_file(
2390    file: String,
2391    item_key: Option<String>,
2392    attachment_key: Option<String>,
2393    mime_type: Option<String>,
2394) -> Result<OcrRequestInput, String> {
2395    let item_key = item_key
2396        .ok_or_else(|| "INVALID_ARGS: --item-key is required when using --file".to_string())?;
2397    let attachment_key = attachment_key.ok_or_else(|| {
2398        "INVALID_ARGS: --attachment-key is required when using --file".to_string()
2399    })?;
2400    let path = PathBuf::from(&file);
2401    let bytes = fs::read(&path).map_err(|err| format!("read {file}: {err}"))?;
2402    let file_name = path
2403        .file_name()
2404        .and_then(|name| name.to_str())
2405        .unwrap_or("document.pdf")
2406        .to_string();
2407    let mime_type = mime_type.unwrap_or_else(|| guess_mime_type(&path).to_string());
2408    Ok(OcrRequestInput {
2409        item_key,
2410        attachment_key,
2411        file_name,
2412        mime_type,
2413        content_base64: base64_encode(&bytes),
2414        source_url: None,
2415        local_path: Some(file),
2416        output_dir: None,
2417    })
2418}
2419
2420fn guess_mime_type(path: &Path) -> &'static str {
2421    match path
2422        .extension()
2423        .and_then(|ext| ext.to_str())
2424        .unwrap_or_default()
2425        .to_ascii_lowercase()
2426        .as_str()
2427    {
2428        "png" => "image/png",
2429        "jpg" | "jpeg" => "image/jpeg",
2430        "webp" => "image/webp",
2431        _ => "application/pdf",
2432    }
2433}
2434
2435fn base64_encode(bytes: &[u8]) -> String {
2436    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2437    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
2438    for chunk in bytes.chunks(3) {
2439        let b0 = chunk[0];
2440        let b1 = *chunk.get(1).unwrap_or(&0);
2441        let b2 = *chunk.get(2).unwrap_or(&0);
2442        out.push(TABLE[(b0 >> 2) as usize] as char);
2443        out.push(TABLE[(((b0 & 0b0000_0011) << 4) | (b1 >> 4)) as usize] as char);
2444        if chunk.len() > 1 {
2445            out.push(TABLE[(((b1 & 0b0000_1111) << 2) | (b2 >> 6)) as usize] as char);
2446        } else {
2447            out.push('=');
2448        }
2449        if chunk.len() > 2 {
2450            out.push(TABLE[(b2 & 0b0011_1111) as usize] as char);
2451        } else {
2452            out.push('=');
2453        }
2454    }
2455    out
2456}
2457
2458fn run_ocr_status_command(
2459    client: &mut impl RpcCaller,
2460    collection: String,
2461) -> Result<Value, String> {
2462    let collection_key = find_collection_in_tree(client, &collection)?
2463        .and_then(|node| node.get("key").cloned())
2464        .ok_or_else(|| format!("COLLECTION_NOT_FOUND: Collection not found: {collection:?}"))?;
2465    let raw = paginate_rpc(
2466        client,
2467        "collections.getItems",
2468        serde_json::json!({"key": collection_key}),
2469        500,
2470    )?;
2471    let items = raw
2472        .get("items")
2473        .and_then(Value::as_array)
2474        .or_else(|| raw.as_array())
2475        .ok_or_else(|| "collections.getItems returned non-array/non-items result".to_string())?
2476        .clone();
2477
2478    let mut has_ocr = 0usize;
2479    for item in &items {
2480        let item_key = item.get("key").cloned().unwrap_or(Value::Null);
2481        if has_ocr_artifact(client, &item_key)? || has_ocr_note(client, &item_key)? {
2482            has_ocr += 1;
2483        }
2484    }
2485
2486    Ok(serde_json::json!({
2487        "collection": collection,
2488        "total": items.len(),
2489        "has_ocr": has_ocr,
2490        "missing_ocr": items.len() - has_ocr,
2491    }))
2492}
2493
2494fn has_ocr_artifact(client: &mut impl RpcCaller, item_key: &Value) -> Result<bool, String> {
2495    if let Some(item_key) = item_key.as_str() {
2496        // Legacy external store lookup for artifacts produced before the
2497        // per-attachment hidden sidecar became the default.
2498        if machine_artifact_exists_for_item(
2499            machine_artifact_store_root(),
2500            item_key,
2501            MachineArtifactKind::Chunks,
2502        ) {
2503            return Ok(true);
2504        }
2505    }
2506
2507    let attachments = client.call(
2508        "attachments.list",
2509        Some(serde_json::json!({"parentKey": item_key.clone()})),
2510    )?;
2511    Ok(attachments.as_array().is_some_and(|attachments| {
2512        attachments.iter().any(|attachment| {
2513            let has_sidecar_chunks = attachment
2514                .get("path")
2515                .and_then(Value::as_str)
2516                .map(local_path_from_zotero_path)
2517                .as_deref()
2518                .map(Path::new)
2519                .and_then(Path::parent)
2520                .is_some_and(|dir| {
2521                    machine_artifact_exists_in_sidecar(dir, MachineArtifactKind::Chunks)
2522                });
2523            if has_sidecar_chunks {
2524                return true;
2525            }
2526
2527            // Read-only fallback for old Zotero-visible artifact attachments.
2528            attachment
2529                .get("title")
2530                .and_then(Value::as_str)
2531                .is_some_and(|title| title.ends_with("zotron-chunks.jsonl"))
2532        })
2533    }))
2534}
2535
2536fn local_path_from_zotero_path(path: &str) -> String {
2537    if is_wsl() && path.as_bytes().get(1) == Some(&b':') {
2538        return ProcessCommand::new("wslpath")
2539            .arg("-u")
2540            .arg(path)
2541            .output()
2542            .ok()
2543            .filter(|output| output.status.success())
2544            .and_then(|output| String::from_utf8(output.stdout).ok())
2545            .map(|converted| converted.trim().to_string())
2546            .filter(|converted| !converted.is_empty())
2547            .unwrap_or_else(|| path.to_string());
2548    }
2549    path.to_string()
2550}
2551
2552fn has_ocr_note(client: &mut impl RpcCaller, item_key: &Value) -> Result<bool, String> {
2553    let notes = client.call(
2554        "notes.list",
2555        Some(serde_json::json!({"parentKey": item_key.clone()})),
2556    )?;
2557    Ok(notes.as_array().is_some_and(|notes| {
2558        notes.iter().any(|note| {
2559            note.get("tags")
2560                .and_then(Value::as_array)
2561                .is_some_and(|tags| tags.iter().any(tag_is_ocr))
2562        })
2563    }))
2564}
2565
2566fn tag_is_ocr(tag: &Value) -> bool {
2567    tag.as_str() == Some("ocr")
2568        || tag
2569            .get("tag")
2570            .and_then(Value::as_str)
2571            .is_some_and(|tag| tag == "ocr")
2572}
2573
2574fn find_collection_in_tree(
2575    client: &mut impl RpcCaller,
2576    collection: &str,
2577) -> Result<Option<Value>, String> {
2578    let tree = client.call("collections.tree", None)?;
2579    let nodes = tree
2580        .as_array()
2581        .ok_or_else(|| "collections.tree returned non-array result".to_string())?;
2582    Ok(search_collection_tree(nodes, collection).cloned())
2583}
2584
2585fn search_collection_tree<'a>(nodes: &'a [Value], collection: &str) -> Option<&'a Value> {
2586    for node in nodes {
2587        if node.get("key").and_then(Value::as_str) == Some(collection)
2588            || node.get("name").and_then(Value::as_str) == Some(collection)
2589        {
2590            return Some(node);
2591        }
2592        if let Some(children) = node.get("children").and_then(Value::as_array) {
2593            if let Some(found) = search_collection_tree(children, collection) {
2594                return Some(found);
2595            }
2596        }
2597    }
2598    None
2599}
2600
2601fn run_command(command: Command, client: &mut impl RpcCaller) -> Result<String, String> {
2602    if let Command::Export(args) = command {
2603        return run_export(args, client);
2604    }
2605
2606    let (value, style) = match command {
2607        Command::Ping { .. } => (
2608            call_json(client, "system.ping", None)?,
2609            JsonStyle::PythonCompact,
2610        ),
2611        Command::Rpc {
2612            method,
2613            params_json,
2614            paginate,
2615            page_size,
2616            ..
2617        } => {
2618            let params = serde_json::from_str::<Value>(&params_json)
2619                .map_err(|err| format!("INVALID_JSON: params must be a JSON object: {err}"))?;
2620            if !params.is_object() {
2621                return Err("INVALID_JSON: params must be a JSON object".to_string());
2622            }
2623            if paginate {
2624                (
2625                    paginate_rpc(client, &method, params, page_size)?,
2626                    JsonStyle::Pretty,
2627                )
2628            } else {
2629                (call_json(client, &method, Some(params))?, JsonStyle::Pretty)
2630            }
2631        }
2632        Command::Push {
2633            json_file,
2634            pdf,
2635            collection,
2636            on_duplicate,
2637            dry_run,
2638            ..
2639        } => return run_push_command(json_file, pdf, collection, on_duplicate, dry_run, client),
2640        Command::System { command } => run_system_command(command, client)?,
2641        Command::Search(args) => {
2642            if let Some(mgmt) = args.management {
2643                run_search_management_command(mgmt, client)?
2644            } else {
2645                run_search(args, client)?
2646            }
2647        }
2648        Command::Items { command } => run_items_command(command, client)?,
2649        Command::Collections { command } => run_collections_command(command, client)?,
2650        Command::Notes { command } => run_notes_command(command, client)?,
2651        Command::Attachments { command } => run_attachments_command(command, client)?,
2652        Command::Settings { command } => run_settings_command(command, client)?,
2653        Command::Tags { command } => run_tags_command(command, client)?,
2654        Command::Annotations { command } => run_annotations_command(command, client)?,
2655        Command::Ocr { command } => {
2656            return run_ocr_command(command, client);
2657        }
2658        Command::Rag { command } => {
2659            return run_rag_command(command, client);
2660        }
2661        Command::Export(_) => unreachable!("export commands return raw output above"),
2662        Command::FindPdfs {
2663            collection, limit, ..
2664        } => run_find_pdfs_command(client, collection, limit)?,
2665    };
2666
2667    format_json(&value, style)
2668}
2669
2670fn run_rag_command(command: RagCommand, client: &mut impl RpcCaller) -> Result<String, String> {
2671    match command {
2672        RagCommand::Providers => format_json(
2673            &serde_json::json!({
2674                "providers": [
2675                    embedding_provider_spec("volcengine")?,
2676                    embedding_provider_spec("alibaba")?,
2677                    embedding_provider_spec("custom")?,
2678                ],
2679            }),
2680            JsonStyle::Pretty,
2681        ),
2682        RagCommand::Embed {
2683            provider,
2684            input,
2685            endpoint,
2686            model,
2687            input_type,
2688            api_key_env,
2689        } => {
2690            let value = run_embedding_provider_json_command(
2691                provider,
2692                input,
2693                endpoint,
2694                model,
2695                input_type,
2696                api_key_env,
2697            )?;
2698            format_json(&value, JsonStyle::PythonCompact)
2699        }
2700        RagCommand::Status { collection, .. } => {
2701            let value = rag_status_value(client, &collection)?;
2702            format_json(&value, JsonStyle::PythonCompact)
2703        }
2704        RagCommand::Search {
2705            query,
2706            collection,
2707            keys,
2708            zotero,
2709            top_spans_per_item,
2710            include_fulltext_spans,
2711            top_k,
2712            output,
2713            ..
2714        } => run_rag_search_command(
2715            client,
2716            RagSearchOptions {
2717                query,
2718                collection,
2719                keys,
2720                zotero,
2721                top_spans_per_item,
2722                include_fulltext_spans,
2723                top_k,
2724                output,
2725            },
2726        ),
2727    }
2728}
2729
2730fn run_embedding_provider_json_command(
2731    provider: String,
2732    input: String,
2733    endpoint: Option<String>,
2734    model: Option<String>,
2735    input_type: Option<String>,
2736    api_key_env: Option<String>,
2737) -> Result<Value, String> {
2738    let mut input: EmbeddingRequestInput = read_json_input(&input)?;
2739    if endpoint.is_some() {
2740        input.url = endpoint;
2741    }
2742    if model.is_some() {
2743        input.model = model;
2744    }
2745    if input_type.is_some() {
2746        input.input_type = input_type;
2747    }
2748    let mut transport = provider_http_transport(api_key_env.as_deref())?;
2749    let vectors = execute_embedding_provider_request(&provider, &input, &mut transport)?;
2750
2751    Ok(serde_json::json!({
2752        "provider": provider,
2753        "vectors": vectors,
2754    }))
2755}
2756
2757fn provider_http_transport(api_key_env: Option<&str>) -> Result<UreqProviderHttpTransport, String> {
2758    provider_http_transport_with_auth(api_key_env, "bearer")
2759}
2760
2761fn provider_http_transport_with_auth(
2762    api_key_env: Option<&str>,
2763    auth_scheme: &str,
2764) -> Result<UreqProviderHttpTransport, String> {
2765    let Some(env_name) = api_key_env else {
2766        return Ok(UreqProviderHttpTransport::new());
2767    };
2768    let token = env::var(env_name)
2769        .map_err(|_| format!("missing provider credential env var {env_name}"))?;
2770    if token.trim().is_empty() {
2771        return Err(format!("provider credential env var {env_name} is empty"));
2772    }
2773    let token = token.trim();
2774    match auth_scheme {
2775        "token" if token.starts_with("token ") => {
2776            Ok(UreqProviderHttpTransport::with_api_key(token.to_string()))
2777        }
2778        "token" => Ok(UreqProviderHttpTransport::with_api_key(format!(
2779            "token {token}"
2780        ))),
2781        "bearer" if token.starts_with("Bearer ") => {
2782            Ok(UreqProviderHttpTransport::with_api_key(token.to_string()))
2783        }
2784        "bearer" => Ok(UreqProviderHttpTransport::with_bearer_token(token)),
2785        "none" => Ok(UreqProviderHttpTransport::new()),
2786        other => Err(format!("unsupported provider auth scheme {other}")),
2787    }
2788}
2789
2790fn read_json_input<T: serde::de::DeserializeOwned>(path: &str) -> Result<T, String> {
2791    let payload = if path == "-" {
2792        let mut input = String::new();
2793        io::stdin()
2794            .read_to_string(&mut input)
2795            .map_err(|err| format!("read stdin: {err}"))?;
2796        input
2797    } else {
2798        fs::read_to_string(path).map_err(|err| format!("read {path}: {err}"))?
2799    };
2800    serde_json::from_str::<T>(&payload)
2801        .map_err(|err| format!("INVALID_JSON: Could not parse JSON: {err}"))
2802}
2803
2804fn fetch_embedding_settings(
2805    client: &mut impl RpcCaller,
2806) -> Result<(String, String, String, String), String> {
2807    let settings = client.call("settings.getAll", None)?;
2808    let provider = settings
2809        .get("embedding.provider")
2810        .and_then(Value::as_str)
2811        .unwrap_or("ollama")
2812        .to_string();
2813    let model = settings
2814        .get("embedding.model")
2815        .and_then(Value::as_str)
2816        .unwrap_or("")
2817        .to_string();
2818    let api_url = settings
2819        .get("embedding.apiUrl")
2820        .and_then(Value::as_str)
2821        .unwrap_or("")
2822        .to_string();
2823    let raw = client.call("settings.getRaw", Some(serde_json::json!({"key": "embedding.apiKey"})))?;
2824    let api_key = raw
2825        .get("embedding.apiKey")
2826        .and_then(Value::as_str)
2827        .unwrap_or("")
2828        .to_string();
2829    Ok((provider, model, api_url, api_key))
2830}
2831
2832fn fetch_retrieval_mode(client: &mut impl RpcCaller) -> String {
2833    client
2834        .call(
2835            "settings.get",
2836            Some(serde_json::json!({"key": "rag.retrievalMode"})),
2837        )
2838        .ok()
2839        .and_then(|v| {
2840            v.get("rag.retrievalMode")
2841                .and_then(Value::as_str)
2842                .map(String::from)
2843        })
2844        .unwrap_or_else(|| "hybrid".to_string())
2845}
2846
2847fn resolve_sidecar_paths(
2848    client: &mut impl RpcCaller,
2849    collection: Option<&str>,
2850    keys: &[String],
2851) -> Result<Vec<(String, String, PathBuf)>, String> {
2852    let items = if !keys.is_empty() {
2853        let mut items = Vec::new();
2854        for key in keys {
2855            let item = client.call("items.get", Some(serde_json::json!({"key": key})))?;
2856            items.push(item);
2857        }
2858        items
2859    } else if let Some(col) = collection {
2860        let col_key = resolve_collection(client, col)?;
2861        let response = client.call(
2862            "collections.getItems",
2863            Some(serde_json::json!({"key": col_key})),
2864        )?;
2865        collection_items(&response)
2866    } else {
2867        return Err("INVALID_ARGS: --collection or --key required".into());
2868    };
2869
2870    let mut results = Vec::new();
2871    for item in &items {
2872        let item_key = item.get("key").and_then(Value::as_str).unwrap_or_default();
2873        let attachments = client.call(
2874            "attachments.list",
2875            Some(serde_json::json!({"parentKey": item_key})),
2876        )?;
2877        let att_list = attachments
2878            .get("items")
2879            .and_then(Value::as_array)
2880            .or_else(|| attachments.as_array())
2881            .cloned()
2882            .unwrap_or_default();
2883        for att in &att_list {
2884            let content_type = att
2885                .get("contentType")
2886                .and_then(Value::as_str)
2887                .unwrap_or("");
2888            if content_type != "application/pdf" {
2889                continue;
2890            }
2891            let att_key = att.get("key").and_then(Value::as_str).unwrap_or_default();
2892            let path = att.get("path").and_then(Value::as_str).unwrap_or_default();
2893            if path.is_empty() {
2894                continue;
2895            }
2896            let local_path = local_path_from_zotero_path(path);
2897            let pdf_path = PathBuf::from(&local_path);
2898            if let Some(parent) = pdf_path.parent() {
2899                let sidecar_root = parent.join(".zotron");
2900                if sidecar_root.exists() {
2901                    results.push((item_key.to_string(), att_key.to_string(), sidecar_root));
2902                }
2903            }
2904        }
2905    }
2906    Ok(results)
2907}
2908
2909fn load_sidecar_chunks(sidecar_root: &Path) -> Vec<StructureChunk> {
2910    let chunks_path = sidecar_root.join("chunks").join("chunks.v1.jsonl");
2911    let Ok(content) = fs::read_to_string(&chunks_path) else {
2912        return Vec::new();
2913    };
2914    content
2915        .lines()
2916        .filter(|line| !line.trim().is_empty())
2917        .filter_map(|line| serde_json::from_str::<StructureChunk>(line).ok())
2918        .collect()
2919}
2920
2921fn embedding_vector_filename(provider: &str, model: &str) -> String {
2922    let p = provider.trim().to_lowercase().replace('/', "-");
2923    let m = model.trim().to_lowercase().replace('/', "-");
2924    if p.is_empty() && m.is_empty() {
2925        return "vectors.jsonl".to_string();
2926    }
2927    format!("{p}--{m}.jsonl")
2928}
2929
2930fn load_sidecar_vectors(sidecar_root: &Path, provider: &str, model: &str) -> Vec<EmbeddingVector> {
2931    let embeddings_dir = sidecar_root.join("embeddings");
2932    let target = embedding_vector_filename(provider, model);
2933    let target_path = embeddings_dir.join(&target);
2934    if let Ok(content) = fs::read_to_string(&target_path) {
2935        let vecs: Vec<EmbeddingVector> = content
2936            .lines()
2937            .filter(|line| !line.trim().is_empty())
2938            .filter_map(|line| serde_json::from_str(line).ok())
2939            .collect();
2940        if !vecs.is_empty() {
2941            return vecs;
2942        }
2943    }
2944    // Fallback: try legacy vectors.v1.jsonl / vectors.jsonl with provider match
2945    for legacy in &["vectors.v1.jsonl", "vectors.jsonl"] {
2946        let path = embeddings_dir.join(legacy);
2947        if let Ok(content) = fs::read_to_string(&path) {
2948            let vecs: Vec<EmbeddingVector> = content
2949                .lines()
2950                .filter(|line| !line.trim().is_empty())
2951                .filter_map(|line| serde_json::from_str::<EmbeddingVector>(line).ok())
2952                .filter(|v| v.source_provider == provider || provider.is_empty())
2953                .collect();
2954            if !vecs.is_empty() {
2955                return vecs;
2956            }
2957        }
2958    }
2959    Vec::new()
2960}
2961
2962fn embed_query_text(
2963    query: &str,
2964    provider: &str,
2965    model: &str,
2966    api_url: &str,
2967    api_key: &str,
2968) -> Result<Vec<f64>, String> {
2969    let input = EmbeddingRequestInput {
2970        item_key: "query".to_string(),
2971        chunks: vec![EmbeddingChunkInput {
2972            chunk_key: "q0".to_string(),
2973            text: query.to_string(),
2974        }],
2975        model: if model.is_empty() {
2976            None
2977        } else {
2978            Some(model.to_string())
2979        },
2980        url: if api_url.is_empty() {
2981            None
2982        } else {
2983            Some(api_url.to_string())
2984        },
2985        input_type: Some("query".to_string()),
2986    };
2987    let request = build_embedding_provider_request(provider, &input)?;
2988    let url = request
2989        .url
2990        .as_deref()
2991        .ok_or("no embedding URL configured")?;
2992    let mut http = ureq::post(url).set("Content-Type", "application/json");
2993    if let Some(auth) = request.auth_header {
2994        if !api_key.is_empty() {
2995            http = http.set(auth, &format!("Bearer {api_key}"));
2996        }
2997    }
2998    let resp = http
2999        .send_json(&request.body)
3000        .map_err(|e| format!("embedding request failed: {e}"))?;
3001    let payload: Value = resp
3002        .into_json()
3003        .map_err(|e| format!("embedding response parse: {e}"))?;
3004    let vectors =
3005        parse_embedding_provider_response(provider, &payload, "query", &input.chunks)?;
3006    vectors
3007        .into_iter()
3008        .next()
3009        .map(|v| v.vector)
3010        .ok_or_else(|| "no embedding vector returned".to_string())
3011}
3012
3013fn run_rag_search_xpi_fallback(
3014    client: &mut impl RpcCaller,
3015    options: &RagSearchOptions,
3016) -> Result<String, String> {
3017    let mut params = serde_json::json!({
3018        "query": options.query,
3019        "limit": options.top_k,
3020        "top_spans_per_item": options.top_spans_per_item,
3021        "include_fulltext_spans": options.include_fulltext_spans,
3022    });
3023    if let Some(map) = params.as_object_mut() {
3024        if let Some(col) = &options.collection {
3025            map.insert("collection".into(), Value::String(col.clone()));
3026        }
3027        if !options.keys.is_empty() {
3028            map.insert(
3029                "keys".into(),
3030                Value::Array(options.keys.iter().map(|k| Value::String(k.clone())).collect()),
3031            );
3032        }
3033    }
3034    let payload = client.call("rag.searchHits", Some(params))?;
3035    let hits = payload
3036        .get("hits")
3037        .and_then(Value::as_array)
3038        .cloned()
3039        .unwrap_or_default();
3040    if options.output == "jsonl" {
3041        let mut out = String::new();
3042        for hit in &hits {
3043            out.push_str(&serde_json::to_string(hit).map_err(|e| e.to_string())?);
3044            out.push('\n');
3045        }
3046        Ok(out)
3047    } else {
3048        let total = hits.len() as u64;
3049        format_json(
3050            &normalize_list_envelope(
3051                serde_json::json!({"items": hits, "total": total}),
3052                "items",
3053                Some(options.top_k),
3054                0,
3055            ),
3056            JsonStyle::Pretty,
3057        )
3058    }
3059}
3060
3061fn run_rag_search_command(
3062    client: &mut impl RpcCaller,
3063    options: RagSearchOptions,
3064) -> Result<String, String> {
3065    // When --zotero is explicitly passed, use XPI fallback directly (backward compat).
3066    if options.zotero {
3067        if options.collection.is_none() && options.keys.is_empty() {
3068            return Err(
3069                "INVALID_ARGS: --collection or --key is required".to_string(),
3070            );
3071        }
3072        return run_rag_search_xpi_fallback(client, &options);
3073    }
3074
3075    // Hybrid path: require scope.
3076    if options.collection.is_none() && options.keys.is_empty() {
3077        return Err("INVALID_ARGS: --collection or --key required".to_string());
3078    }
3079
3080    // Step 1: resolve sidecar paths from collection/keys.
3081    let sidecars = resolve_sidecar_paths(
3082        client,
3083        options.collection.as_deref(),
3084        &options.keys,
3085    );
3086
3087    // If sidecar resolution fails or returns empty, fall back to XPI.
3088    // But propagate COLLECTION_NOT_FOUND errors directly instead of masking them.
3089    let sidecars = match sidecars {
3090        Ok(ref s) if !s.is_empty() => s,
3091        Err(ref e) if e.contains("COLLECTION_NOT_FOUND") => return Err(e.clone()),
3092        _ => return run_rag_search_xpi_fallback(client, &options),
3093    };
3094
3095    // Step 2: load all chunks and vectors from sidecars.
3096    let (emb_provider, emb_model, emb_url, emb_key) = fetch_embedding_settings(client)?;
3097    let mut all_chunks: Vec<StructureChunk> = Vec::new();
3098    let mut all_vectors: Vec<EmbeddingVector> = Vec::new();
3099    for (_item_key, _att_key, sidecar_root) in sidecars {
3100        all_chunks.extend(load_sidecar_chunks(sidecar_root));
3101        all_vectors.extend(load_sidecar_vectors(sidecar_root, &emb_provider, &emb_model));
3102    }
3103
3104    if all_chunks.is_empty() {
3105        return run_rag_search_xpi_fallback(client, &options);
3106    }
3107
3108    // Step 3: determine retrieval mode.
3109    let mode = fetch_retrieval_mode(client);
3110
3111    // Step 4: BM25 scoring (unless mode is "dense").
3112    let bm25_ranked = if mode != "dense" {
3113        bm25_score_chunks(&all_chunks, &options.query, 1.2, 0.75)
3114    } else {
3115        Vec::new()
3116    };
3117
3118    // Step 5: dense vector scoring (unless mode is "lexical" or no vectors).
3119    let dense_ranked = if mode != "lexical" && !all_vectors.is_empty() {
3120        match embed_query_text(&options.query, &emb_provider, &emb_model, &emb_url, &emb_key) {
3121            Ok(query_vec) => {
3122                let vec_map: std::collections::HashMap<&str, &[f64]> = all_vectors
3123                    .iter()
3124                    .map(|v| (v.chunk_key.as_str(), v.vector.as_slice()))
3125                    .collect();
3126                let mut scores: Vec<(usize, f64)> = all_chunks
3127                    .iter()
3128                    .enumerate()
3129                    .filter_map(|(i, chunk)| {
3130                        vec_map.get(chunk.chunk_key.as_str()).map(|stored| {
3131                            (i, cosine_similarity(&query_vec, stored))
3132                        })
3133                    })
3134                    .filter(|(_, s)| *s > 0.0)
3135                    .collect();
3136                scores.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
3137                scores
3138            }
3139            Err(_) => Vec::new(),
3140        }
3141    } else {
3142        Vec::new()
3143    };
3144
3145    // Step 6: merge results.
3146    let limit = options.top_k as usize;
3147    let ranked = if !bm25_ranked.is_empty() && !dense_ranked.is_empty() {
3148        rrf_merge(&bm25_ranked, &dense_ranked, 60.0, limit)
3149    } else if !bm25_ranked.is_empty() {
3150        bm25_ranked.into_iter().take(limit).collect()
3151    } else {
3152        dense_ranked.into_iter().take(limit).collect()
3153    };
3154
3155    // Step 7: apply per-item span limit.
3156    let mut per_item_count: std::collections::HashMap<&str, u64> =
3157        std::collections::HashMap::new();
3158    let mut selected: Vec<(usize, f64)> = Vec::new();
3159    for (idx, score) in &ranked {
3160        let item_key = all_chunks[*idx].item_key.as_str();
3161        let count = per_item_count.entry(item_key).or_insert(0);
3162        if *count < options.top_spans_per_item {
3163            *count += 1;
3164            selected.push((*idx, *score));
3165        }
3166    }
3167
3168    // Step 8: enrich hits with item metadata.
3169    let mut meta_cache: std::collections::HashMap<String, Value> =
3170        std::collections::HashMap::new();
3171    let mut hits: Vec<Value> = Vec::new();
3172    for (idx, score) in &selected {
3173        let chunk = &all_chunks[*idx];
3174        let meta = if let Some(cached) = meta_cache.get(&chunk.item_key) {
3175            cached.clone()
3176        } else {
3177            let fetched = client
3178                .call(
3179                    "items.get",
3180                    Some(serde_json::json!({"key": chunk.item_key})),
3181                )
3182                .unwrap_or(Value::Null);
3183            meta_cache.insert(chunk.item_key.clone(), fetched.clone());
3184            fetched
3185        };
3186        let title = meta
3187            .get("title")
3188            .and_then(Value::as_str)
3189            .unwrap_or("")
3190            .to_string();
3191        let authors = meta
3192            .get("creators")
3193            .and_then(Value::as_array)
3194            .map(|creators| {
3195                creators
3196                    .iter()
3197                    .filter_map(|c| {
3198                        let last = c.get("lastName").and_then(Value::as_str).unwrap_or("");
3199                        let first = c.get("firstName").and_then(Value::as_str).unwrap_or("");
3200                        if last.is_empty() && first.is_empty() {
3201                            None
3202                        } else {
3203                            Some(format!("{last}{first}"))
3204                        }
3205                    })
3206                    .collect::<Vec<_>>()
3207                    .join(", ")
3208            })
3209            .unwrap_or_default();
3210        let year = meta.get("date").and_then(Value::as_str).unwrap_or("");
3211        let mut hit = serde_json::json!({
3212            "item_key": chunk.item_key,
3213            "chunk_key": chunk.chunk_key,
3214            "title": title,
3215            "authors": authors,
3216            "year": year,
3217            "text": chunk.text,
3218            "page_range": chunk.page_range,
3219            "section_path": chunk.section_path,
3220            "score": score,
3221        });
3222        if options.include_fulltext_spans {
3223            hit.as_object_mut().unwrap().insert(
3224                "attachment_key".to_string(),
3225                Value::String(chunk.attachment_key.clone()),
3226            );
3227        }
3228        hits.push(hit);
3229    }
3230
3231    // Step 9: format output.
3232    if options.output == "jsonl" {
3233        let mut out = String::new();
3234        for hit in &hits {
3235            out.push_str(&serde_json::to_string(hit).map_err(|e| e.to_string())?);
3236            out.push('\n');
3237        }
3238        Ok(out)
3239    } else {
3240        let total = hits.len() as u64;
3241        format_json(
3242            &normalize_list_envelope(
3243                serde_json::json!({"items": hits, "total": total}),
3244                "items",
3245                Some(options.top_k),
3246                0,
3247            ),
3248            JsonStyle::Pretty,
3249        )
3250    }
3251}
3252
3253fn rag_status_value(client: &mut impl RpcCaller, collection: &str) -> Result<Value, String> {
3254    let raw_store_path = rag_store_path(collection);
3255    if raw_store_path.exists() {
3256        return rag_status_from_store(collection, &raw_store_path);
3257    }
3258
3259    let mut store_candidates = Vec::new();
3260    let collection_match = find_collection_in_tree(client, collection)?;
3261    if let Some(collection_node) = collection_match.as_ref() {
3262        if let Some(name) = collection_node.get("name").and_then(Value::as_str) {
3263            store_candidates.push(rag_store_path(name));
3264        }
3265        if let Some(key) = collection_node.get("key").and_then(Value::as_str) {
3266            store_candidates.push(rag_store_path(key));
3267        }
3268    }
3269    for store_path in unique_paths(store_candidates) {
3270        if store_path.exists() {
3271            return rag_status_from_store(collection, &store_path);
3272        }
3273    }
3274
3275    rag_status_from_zotero_sidecars(client, collection, collection_match)
3276}
3277
3278fn unique_paths(paths: Vec<PathBuf>) -> Vec<PathBuf> {
3279    let mut unique = Vec::new();
3280    for path in paths {
3281        if !unique.iter().any(|seen| seen == &path) {
3282            unique.push(path);
3283        }
3284    }
3285    unique
3286}
3287
3288fn rag_status_from_store(collection: &str, store_path: &Path) -> Result<Value, String> {
3289    let raw = fs::read_to_string(store_path)
3290        .map_err(|err| format!("read RAG store {}: {err}", store_path.display()))?;
3291    let store: Value = serde_json::from_str(&raw)
3292        .map_err(|err| format!("parse RAG store {}: {err}", store_path.display()))?;
3293    let chunks = store
3294        .get("chunks")
3295        .and_then(Value::as_array)
3296        .cloned()
3297        .unwrap_or_default();
3298    let mut item_keys = Vec::<Value>::new();
3299    for chunk in &chunks {
3300        let Some(item_key) = chunk.get("item_key") else {
3301            continue;
3302        };
3303        if !item_keys.iter().any(|seen| seen == item_key) {
3304            item_keys.push(item_key.clone());
3305        }
3306    }
3307    Ok(serde_json::json!({
3308        "status": "indexed",
3309        "collection": store.get("collection").and_then(Value::as_str).unwrap_or(collection),
3310        "collection_key": store.get("collection_key").cloned().unwrap_or(Value::Null),
3311        "model": store.get("model").cloned().unwrap_or(Value::String("unknown".to_string())),
3312        "total_chunks": chunks.len(),
3313        "total_items": item_keys.len(),
3314        "store_path": store_path.to_string_lossy(),
3315    }))
3316}
3317
3318fn rag_status_from_zotero_sidecars(
3319    client: &mut impl RpcCaller,
3320    collection: &str,
3321    collection_match: Option<Value>,
3322) -> Result<Value, String> {
3323    let collection_key = collection_match
3324        .as_ref()
3325        .and_then(|node| node.get("key").cloned())
3326        .ok_or_else(|| format!("COLLECTION_NOT_FOUND: Collection not found: {collection:?}"))?;
3327    let raw = paginate_rpc(
3328        client,
3329        "collections.getItems",
3330        serde_json::json!({"key": collection_key}),
3331        500,
3332    )?;
3333    let items = raw
3334        .get("items")
3335        .and_then(Value::as_array)
3336        .or_else(|| raw.as_array())
3337        .ok_or_else(|| "collections.getItems returned non-array/non-items result".to_string())?
3338        .clone();
3339
3340    let mut indexed_items = 0usize;
3341    let mut total_chunks = 0usize;
3342    for item in &items {
3343        let item_key = item.get("key").cloned().unwrap_or(Value::Null);
3344        let chunk_count = sidecar_chunk_count_for_item(client, &item_key)?;
3345        if chunk_count > 0 {
3346            indexed_items += 1;
3347            total_chunks += chunk_count;
3348        }
3349    }
3350
3351    if indexed_items == 0 {
3352        return Ok(serde_json::json!({
3353            "status": "not indexed",
3354            "collection": collection,
3355            "total_items": items.len(),
3356            "indexed_items": 0,
3357        }));
3358    }
3359
3360    Ok(serde_json::json!({
3361        "status": "indexed",
3362        "collection": collection,
3363        "total_chunks": total_chunks,
3364        "total_items": indexed_items,
3365        "collection_items": items.len(),
3366        "source": "zotero-sidecar",
3367    }))
3368}
3369
3370fn sidecar_chunk_count_for_item(
3371    client: &mut impl RpcCaller,
3372    item_key: &Value,
3373) -> Result<usize, String> {
3374    let attachments = client.call(
3375        "attachments.list",
3376        Some(serde_json::json!({"parentKey": item_key.clone()})),
3377    )?;
3378    let Some(attachments) = attachments.as_array() else {
3379        return Ok(0);
3380    };
3381
3382    let mut count = 0usize;
3383    for attachment in attachments {
3384        let Some(path) = attachment.get("path").and_then(Value::as_str) else {
3385            continue;
3386        };
3387        let local = local_path_from_zotero_path(path);
3388        let Some(dir) = Path::new(&local).parent() else {
3389            continue;
3390        };
3391        let Ok(bytes) = read_machine_artifact_sidecar(dir, MachineArtifactKind::Chunks) else {
3392            continue;
3393        };
3394        let text = String::from_utf8_lossy(&bytes);
3395        count += text.lines().filter(|line| !line.trim().is_empty()).count();
3396    }
3397    Ok(count)
3398}
3399
3400fn rag_store_path(collection: &str) -> PathBuf {
3401    rag_store_root().join(format!("{collection}.json"))
3402}
3403
3404fn rag_store_root() -> PathBuf {
3405    let xdg_data_home = env::var_os("XDG_DATA_HOME")
3406        .filter(|path| !path.is_empty())
3407        .map(PathBuf::from);
3408    let appdata = env::var_os("APPDATA")
3409        .filter(|path| !path.is_empty())
3410        .map(PathBuf::from);
3411    let userprofile = env::var_os("USERPROFILE")
3412        .filter(|path| !path.is_empty())
3413        .map(PathBuf::from);
3414    let home = env::var_os("HOME")
3415        .filter(|path| !path.is_empty())
3416        .map(PathBuf::from);
3417
3418    rag_store_root_for_platform(
3419        ArtifactStorePlatform::current(),
3420        xdg_data_home.as_deref(),
3421        appdata.as_deref(),
3422        userprofile.as_deref(),
3423        home.as_deref(),
3424    )
3425}
3426
3427fn rag_store_root_for_platform(
3428    platform: ArtifactStorePlatform,
3429    xdg_data_home: Option<&Path>,
3430    appdata: Option<&Path>,
3431    userprofile: Option<&Path>,
3432    home: Option<&Path>,
3433) -> PathBuf {
3434    match platform {
3435        ArtifactStorePlatform::Windows => {
3436            if let Some(path) = appdata {
3437                return path.join("Zotron").join("rag");
3438            }
3439            if let Some(path) = userprofile {
3440                return path
3441                    .join("AppData")
3442                    .join("Roaming")
3443                    .join("Zotron")
3444                    .join("rag");
3445            }
3446            if let Some(path) = home {
3447                return path
3448                    .join("AppData")
3449                    .join("Roaming")
3450                    .join("Zotron")
3451                    .join("rag");
3452            }
3453            PathBuf::from(".zotron").join("rag")
3454        }
3455        ArtifactStorePlatform::Macos => {
3456            if let Some(path) = home {
3457                return path
3458                    .join("Library")
3459                    .join("Application Support")
3460                    .join("Zotron")
3461                    .join("rag");
3462            }
3463            if let Some(path) = xdg_data_home {
3464                return path.join("zotron").join("rag");
3465            }
3466            PathBuf::from(".zotron").join("rag")
3467        }
3468        ArtifactStorePlatform::Linux | ArtifactStorePlatform::Other => xdg_data_home
3469            .map(|path| path.join("zotron").join("rag"))
3470            .or_else(|| {
3471                home.map(|path| path.join(".local").join("share").join("zotron").join("rag"))
3472            })
3473            .unwrap_or_else(|| PathBuf::from(".zotron").join("rag")),
3474    }
3475}
3476
3477fn run_push_command(
3478    json_file: String,
3479    pdf: Option<String>,
3480    collection: Option<String>,
3481    on_duplicate: String,
3482    dry_run: bool,
3483    client: &mut impl RpcCaller,
3484) -> Result<String, String> {
3485    if !matches!(on_duplicate.as_str(), "skip" | "update" | "create") {
3486        return Err(format!(
3487            "INVALID_ARGS: --on-duplicate must be skip|update|create, got {on_duplicate:?}"
3488        ));
3489    }
3490
3491    let payload = if json_file == "-" {
3492        let mut input = String::new();
3493        io::stdin()
3494            .read_to_string(&mut input)
3495            .map_err(|err| format!("read stdin: {err}"))?;
3496        input
3497    } else {
3498        fs::read_to_string(&json_file).map_err(|err| format!("read {json_file}: {err}"))?
3499    };
3500    let item_json = serde_json::from_str::<Value>(&payload)
3501        .map_err(|err| format!("INVALID_JSON: Could not parse JSON: {err}"))?;
3502
3503    // Validate required fields
3504    match item_json.get("itemType").and_then(Value::as_str) {
3505        Some(s) if !s.is_empty() => {}
3506        _ => return Err("INVALID_ARGS: input JSON must include a non-empty \"itemType\" field".to_string()),
3507    }
3508
3509    if dry_run {
3510        let collection_key = collection
3511            .as_deref()
3512            .map(|name| resolve_collection(client, name))
3513            .transpose()?;
3514        return format_json(
3515            &serde_json::json!({
3516                "ok": true,
3517                "dryRun": true,
3518                "wouldPush": {
3519                    "title": item_json.get("title").cloned().unwrap_or(Value::Null),
3520                    "itemType": item_json.get("itemType").cloned().unwrap_or(Value::Null),
3521                    "collectionKey": collection_key,
3522                    "pdfPath": pdf,
3523                    "onDuplicate": on_duplicate,
3524                }
3525            }),
3526            JsonStyle::PythonCompact,
3527        );
3528    }
3529
3530    let result = push_item(
3531        client,
3532        &item_json,
3533        pdf.as_deref(),
3534        collection.as_deref(),
3535        &on_duplicate,
3536    )?;
3537    format_json(&result, JsonStyle::PythonCompact)
3538}
3539
3540fn push_item(
3541    client: &mut impl RpcCaller,
3542    item_json: &Value,
3543    pdf_path: Option<&str>,
3544    collection: Option<&str>,
3545    on_duplicate: &str,
3546) -> Result<Value, String> {
3547    let pdf_size = if let Some(path) = pdf_path {
3548        validate_pdf_magic(path)?
3549    } else {
3550        0
3551    };
3552
3553    let collection_key = match collection {
3554        Some(name) => resolve_collection(client, name)?,
3555        None => resolve_current_collection(client)?,
3556    };
3557
3558    let dup_id = find_duplicate(client, item_json)?;
3559    if let Some(dup_id) = dup_id.as_deref().filter(|_| on_duplicate == "skip") {
3560        if !is_library_root(&collection_key) {
3561            client.call(
3562                "collections.addItems",
3563                Some(serde_json::json!({"key": collection_key, "keys": [dup_id]})),
3564            )?;
3565        }
3566        let mut pdf_attached = false;
3567        if let Some(path) = pdf_path {
3568            if !item_has_pdf_attachment(client, dup_id)? {
3569                attach_pdf(client, dup_id, path)?;
3570                pdf_attached = true;
3571            }
3572        }
3573        return Ok(push_result(
3574            "skipped_duplicate",
3575            Some(dup_id.to_string()),
3576            pdf_attached,
3577            if pdf_attached { pdf_size } else { 0 },
3578            Value::Null,
3579        ));
3580    }
3581
3582    let xpi_payload = to_xpi_payload(item_json, Some(&collection_key));
3583    let (item_key, status) =
3584        if let Some(dup_id) = dup_id.as_deref().filter(|_| on_duplicate == "update") {
3585            let mut params = serde_json::Map::new();
3586            params.insert("key".to_string(), Value::String(dup_id.to_string()));
3587            params.insert(
3588                "fields".to_string(),
3589                xpi_payload
3590                    .get("fields")
3591                    .cloned()
3592                    .unwrap_or_else(|| serde_json::json!({})),
3593            );
3594            if let Some(creators) = xpi_payload.get("creators") {
3595                params.insert("creators".to_string(), creators.clone());
3596            }
3597            if let Some(tags) = xpi_payload.get("tags") {
3598                params.insert("tags".to_string(), tags.clone());
3599            }
3600            client.call("items.update", Some(Value::Object(params)))?;
3601            (dup_id.to_string(), "updated")
3602        } else {
3603            let created = client.call("items.create", Some(xpi_payload))?;
3604            let key = created
3605                .get("key")
3606                .and_then(Value::as_str)
3607                .ok_or_else(|| format!("items.create returned unexpected shape: {created:?}"))?;
3608            (key.to_string(), "created")
3609        };
3610
3611    let mut pdf_attached = false;
3612    if let Some(path) = pdf_path {
3613        if status != "updated" || !item_has_pdf_attachment(client, &item_key)? {
3614            attach_pdf(client, &item_key, path)?;
3615            pdf_attached = true;
3616        }
3617    }
3618
3619    if status == "updated" && !is_library_root(&collection_key) {
3620        client.call(
3621            "collections.addItems",
3622            Some(serde_json::json!({"key": collection_key, "keys": [item_key]})),
3623        )?;
3624    }
3625
3626    Ok(push_result(
3627        status,
3628        Some(item_key),
3629        pdf_attached,
3630        if pdf_attached { pdf_size } else { 0 },
3631        Value::Null,
3632    ))
3633}
3634
3635fn validate_pdf_magic(path: &str) -> Result<u64, String> {
3636    let bytes = fs::read(path)
3637        .map_err(|_| format!("INVALID_PDF: {path} does not start with %PDF- magic bytes"))?;
3638    if !bytes.starts_with(b"%PDF-") {
3639        return Err(format!(
3640            "INVALID_PDF: {path} does not start with %PDF- magic bytes"
3641        ));
3642    }
3643    Ok(bytes.len() as u64)
3644}
3645
3646fn resolve_current_collection(client: &mut impl RpcCaller) -> Result<Value, String> {
3647    let selected = client.call("system.currentCollection", None)?;
3648    Ok(selected
3649        .get("key")
3650        .cloned()
3651        .unwrap_or_else(|| Value::Number(0.into())))
3652}
3653
3654fn find_duplicate(
3655    client: &mut impl RpcCaller,
3656    item_json: &Value,
3657) -> Result<Option<String>, String> {
3658    if let Some(doi) = item_json
3659        .get("DOI")
3660        .and_then(Value::as_str)
3661        .filter(|doi| !doi.is_empty())
3662    {
3663        let hits = client.call("search.byIdentifier", Some(serde_json::json!({"doi": doi})))?;
3664        if let Some(key) = first_hit_key(&hits) {
3665            return Ok(Some(key));
3666        }
3667    }
3668
3669    if let Some(title) = item_json
3670        .get("title")
3671        .and_then(Value::as_str)
3672        .filter(|title| title.len() >= 10)
3673    {
3674        let hits = client.call(
3675            "search.quick",
3676            Some(serde_json::json!({"query": title, "limit": 20})),
3677        )?;
3678        if let Some(items) = response_items(&hits) {
3679            for item in items {
3680                if item.get("title").and_then(Value::as_str) == Some(title) {
3681                    if let Some(key) = item.get("key").and_then(Value::as_str) {
3682                        return Ok(Some(key.to_string()));
3683                    }
3684                }
3685            }
3686        }
3687    }
3688
3689    Ok(None)
3690}
3691
3692fn first_hit_key(response: &Value) -> Option<String> {
3693    response_items(response)?
3694        .first()?
3695        .get("key")?
3696        .as_str()
3697        .map(ToString::to_string)
3698}
3699
3700fn response_items(response: &Value) -> Option<&Vec<Value>> {
3701    response
3702        .get("items")
3703        .and_then(Value::as_array)
3704        .or_else(|| response.as_array())
3705}
3706
3707fn to_xpi_payload(item_json: &Value, collection_key: Option<&Value>) -> Value {
3708    const NON_FIELD_KEYS: &[&str] = &[
3709        "itemType",
3710        "creators",
3711        "tags",
3712        "collections",
3713        "attachments",
3714        "relations",
3715        "notes",
3716        "id",
3717        "key",
3718        "version",
3719    ];
3720
3721    let mut fields = serde_json::Map::new();
3722    if let Some(item) = item_json.as_object() {
3723        for (key, value) in item {
3724            if !NON_FIELD_KEYS.contains(&key.as_str()) && !value.is_null() && value != "" {
3725                fields.insert(key.clone(), value.clone());
3726            }
3727        }
3728    }
3729
3730    let mut payload = serde_json::Map::new();
3731    payload.insert(
3732        "itemType".to_string(),
3733        item_json
3734            .get("itemType")
3735            .cloned()
3736            .unwrap_or_else(|| Value::String("journalArticle".to_string())),
3737    );
3738    payload.insert("fields".to_string(), Value::Object(fields));
3739
3740    if let Some(creators) = item_json.get("creators").and_then(Value::as_array) {
3741        if !creators.is_empty() {
3742            payload.insert(
3743                "creators".to_string(),
3744                Value::Array(
3745                    creators
3746                        .iter()
3747                        .map(|creator| {
3748                            serde_json::json!({
3749                                "firstName": creator.get("firstName").and_then(Value::as_str).unwrap_or(""),
3750                                "lastName": creator.get("lastName").and_then(Value::as_str).unwrap_or(""),
3751                                "creatorType": creator.get("creatorType").and_then(Value::as_str).unwrap_or("author"),
3752                            })
3753                        })
3754                        .collect(),
3755                ),
3756            );
3757        }
3758    }
3759
3760    if let Some(tags) = item_json.get("tags").and_then(Value::as_array) {
3761        if !tags.is_empty() {
3762            payload.insert(
3763                "tags".to_string(),
3764                Value::Array(
3765                    tags.iter()
3766                        .map(|tag| tag.get("tag").cloned().unwrap_or_else(|| tag.clone()))
3767                        .collect(),
3768                ),
3769            );
3770        }
3771    }
3772
3773    if let Some(collection_key) = collection_key.filter(|key| !is_library_root(key)) {
3774        payload.insert(
3775            "collections".to_string(),
3776            Value::Array(vec![collection_key.clone()]),
3777        );
3778    }
3779
3780    Value::Object(payload)
3781}
3782
3783fn item_has_pdf_attachment(client: &mut impl RpcCaller, item_key: &str) -> Result<bool, String> {
3784    let attachments = client.call(
3785        "attachments.list",
3786        Some(serde_json::json!({"parentKey": item_key})),
3787    )?;
3788    Ok(has_pdf_attachment(&attachments))
3789}
3790
3791fn attach_pdf(client: &mut impl RpcCaller, item_key: &str, path: &str) -> Result<(), String> {
3792    client.call(
3793        "attachments.add",
3794        Some(serde_json::json!({
3795            "parentKey": item_key,
3796            "path": zotero_path(path),
3797            "title": "Full Text PDF",
3798        })),
3799    )?;
3800    Ok(())
3801}
3802
3803fn zotero_path(path: &str) -> String {
3804    let path = Path::new(path)
3805        .canonicalize()
3806        .unwrap_or_else(|_| Path::new(path).to_path_buf())
3807        .to_string_lossy()
3808        .into_owned();
3809    if is_wsl() {
3810        return ProcessCommand::new("wslpath")
3811            .arg("-w")
3812            .arg(&path)
3813            .output()
3814            .ok()
3815            .filter(|output| output.status.success())
3816            .and_then(|output| String::from_utf8(output.stdout).ok())
3817            .map(|converted| converted.trim().to_string())
3818            .filter(|converted| !converted.is_empty())
3819            .unwrap_or(path);
3820    }
3821    path
3822}
3823
3824fn is_wsl() -> bool {
3825    if env::var_os("WSL_DISTRO_NAME").is_some() {
3826        return true;
3827    }
3828    fs::read_to_string("/proc/sys/kernel/osrelease")
3829        .map(|release| release.to_ascii_lowercase().contains("microsoft"))
3830        .unwrap_or(false)
3831}
3832
3833fn is_library_root(value: &Value) -> bool {
3834    value.as_i64() == Some(0) || value.as_u64() == Some(0)
3835}
3836
3837fn push_result(
3838    status: &str,
3839    zotero_item_key: Option<String>,
3840    pdf_attached: bool,
3841    pdf_size_bytes: u64,
3842    error: Value,
3843) -> Value {
3844    serde_json::json!({
3845        "status": status,
3846        "zotero_item_key": zotero_item_key,
3847        "pdf_attached": pdf_attached,
3848        "pdf_size_bytes": pdf_size_bytes,
3849        "error": error,
3850    })
3851}
3852
3853fn run_search(
3854    args: SearchArgs,
3855    client: &mut impl RpcCaller,
3856) -> Result<(Value, JsonStyle), String> {
3857    let SearchArgs {
3858        query, fulltext, author, after, before, journal, tag,
3859        doi, isbn, issn, collection, limit, offset, ..
3860    } = args;
3861
3862    let has_identifier = doi.is_some() || isbn.is_some() || issn.is_some();
3863    if has_identifier {
3864        let mut params = serde_json::Map::new();
3865        if let Some(doi) = doi { params.insert("doi".into(), Value::String(doi)); }
3866        if let Some(isbn) = isbn { params.insert("isbn".into(), Value::String(isbn)); }
3867        if let Some(issn) = issn { params.insert("issn".into(), Value::String(issn)); }
3868        let value = client.call("search.byIdentifier", Some(Value::Object(params)))?;
3869        return Ok((normalize_list_envelope(value, "items", None, 0), JsonStyle::Pretty));
3870    }
3871
3872    if fulltext {
3873        let query = query.ok_or("INVALID_ARGS: --fulltext requires a search query")?;
3874        let mut params = serde_json::json!({"query": query, "limit": limit});
3875        if let (Some(col), Some(map)) = (collection, params.as_object_mut()) {
3876            map.insert("collection".into(), resolve_collection(client, &col)?);
3877        }
3878        let value = client.call("search.fulltext", Some(params))?;
3879        return Ok((normalize_list_envelope(value, "items", Some(limit), 0), JsonStyle::Pretty));
3880    }
3881
3882    let has_filters = author.is_some() || after.is_some() || before.is_some()
3883        || journal.is_some() || tag.is_some();
3884    if has_filters {
3885        let mut conditions: Vec<Value> = Vec::new();
3886        if let Some(query) = &query {
3887            conditions.push(serde_json::json!({
3888                "field": "quicksearch-titleCreatorYear",
3889                "operator": "contains",
3890                "value": query,
3891            }));
3892        }
3893        if let Some(author) = author {
3894            conditions.push(serde_json::json!({
3895                "field": "creator", "operator": "contains", "value": author,
3896            }));
3897        }
3898        if let Some(after) = after {
3899            conditions.push(serde_json::json!({
3900                "field": "date", "operator": "isAfter", "value": after,
3901            }));
3902        }
3903        if let Some(before) = before {
3904            conditions.push(serde_json::json!({
3905                "field": "date", "operator": "isBefore", "value": before,
3906            }));
3907        }
3908        if let Some(journal) = journal {
3909            conditions.push(serde_json::json!({
3910                "field": "publicationTitle", "operator": "contains", "value": journal,
3911            }));
3912        }
3913        if let Some(tag) = tag {
3914            conditions.push(serde_json::json!({
3915                "field": "tag", "operator": "is", "value": tag,
3916            }));
3917        }
3918        let value = client.call(
3919            "search.advanced",
3920            Some(serde_json::json!({
3921                "conditions": conditions,
3922                "operator": "and",
3923                "limit": limit,
3924                "offset": offset,
3925            })),
3926        )?;
3927        return Ok((normalize_list_envelope(value, "items", Some(limit), offset), JsonStyle::Pretty));
3928    }
3929
3930    let query = query.ok_or(
3931        "INVALID_ARGS: provide a search query, or use --doi/--isbn/--issn for identifier lookup"
3932    )?;
3933    let value = if let Some(col) = collection {
3934        let key = resolve_collection(client, &col)?;
3935        let response = client.call(
3936            "collections.getItems",
3937            Some(serde_json::json!({"key": key})),
3938        )?;
3939        collection_quick_search_response(&response, &query, limit)
3940    } else {
3941        filter_search_artifacts(client.call(
3942            "search.quick",
3943            Some(serde_json::json!({"query": query, "limit": limit})),
3944        )?)
3945    };
3946    Ok((normalize_list_envelope(value, "items", Some(limit), 0), JsonStyle::Pretty))
3947}
3948
3949fn run_search_management_command(
3950    command: SearchManagementCommand,
3951    client: &mut impl RpcCaller,
3952) -> Result<(Value, JsonStyle), String> {
3953    match command {
3954        SearchManagementCommand::SavedSearches { .. } => Ok((
3955            normalize_list_envelope(client.call("search.savedSearches", None)?, "items", None, 0),
3956            JsonStyle::Pretty,
3957        )),
3958        SearchManagementCommand::CreateSaved {
3959            name, condition, dry_run, ..
3960        } => {
3961            let conditions = condition
3962                .iter()
3963                .map(|raw| parse_search_condition(raw))
3964                .collect::<Result<Vec<_>, _>>()?;
3965            let params = serde_json::json!({"name": name, "conditions": conditions});
3966            if dry_run {
3967                Ok((dry_run_value("search.createSavedSearch", params), JsonStyle::PythonCompact))
3968            } else {
3969                Ok((client.call("search.createSavedSearch", Some(params))?, JsonStyle::PythonCompact))
3970            }
3971        }
3972        SearchManagementCommand::DeleteSaved {
3973            search_key, dry_run, ..
3974        } => {
3975            let params = serde_json::json!({"key": search_key});
3976            if dry_run {
3977                Ok((dry_run_value("search.deleteSavedSearch", params), JsonStyle::PythonCompact))
3978            } else {
3979                Ok((client.call("search.deleteSavedSearch", Some(params))?, JsonStyle::PythonCompact))
3980            }
3981        }
3982    }
3983}
3984
3985fn filter_search_artifacts(mut value: Value) -> Value {
3986    let Some(items) = value.get_mut("items").and_then(Value::as_array_mut) else {
3987        return value;
3988    };
3989    items.retain(|item| match item.get("title").and_then(Value::as_str) {
3990        Some(title) => !is_zotron_evidence_artifact(title),
3991        None => true,
3992    });
3993    let total_items = items.len() as u64;
3994    if let Some(total) = value.get_mut("total") {
3995        *total = Value::from(total_items);
3996    }
3997    value
3998}
3999
4000fn collection_quick_search_response(response: &Value, query: &str, limit: u64) -> Value {
4001    let mut matched = collection_items(response)
4002        .into_iter()
4003        .filter(|item| !item_is_evidence_artifact(item))
4004        .filter(|item| quick_item_matches(item, query))
4005        .collect::<Vec<_>>();
4006    let total = matched.len() as u64;
4007    let limit = usize::try_from(limit).unwrap_or(usize::MAX);
4008    if matched.len() > limit {
4009        matched.truncate(limit);
4010    }
4011    serde_json::json!({"items": matched, "total": total})
4012}
4013
4014fn item_is_evidence_artifact(item: &Value) -> bool {
4015    item.get("title")
4016        .and_then(Value::as_str)
4017        .is_some_and(is_zotron_evidence_artifact)
4018}
4019
4020fn quick_item_matches(item: &Value, query: &str) -> bool {
4021    let terms = query
4022        .split_whitespace()
4023        .map(|term| term.to_lowercase())
4024        .filter(|term| !term.is_empty())
4025        .collect::<Vec<_>>();
4026    if terms.is_empty() {
4027        return true;
4028    }
4029    let mut haystack = String::new();
4030    append_search_text(item, &mut haystack);
4031    let haystack = haystack.to_lowercase();
4032    terms.iter().all(|term| haystack.contains(term))
4033}
4034
4035fn append_search_text(value: &Value, out: &mut String) {
4036    match value {
4037        Value::String(text) => {
4038            out.push(' ');
4039            out.push_str(text);
4040        }
4041        Value::Number(number) => {
4042            out.push(' ');
4043            out.push_str(&number.to_string());
4044        }
4045        Value::Bool(value) => {
4046            out.push(' ');
4047            out.push_str(if *value { "true" } else { "false" });
4048        }
4049        Value::Array(items) => {
4050            for item in items {
4051                append_search_text(item, out);
4052            }
4053        }
4054        Value::Object(map) => {
4055            for item in map.values() {
4056                append_search_text(item, out);
4057            }
4058        }
4059        Value::Null => {}
4060    }
4061}
4062
4063fn parse_search_condition(raw: &str) -> Result<Value, String> {
4064    let mut parts = raw.split_whitespace();
4065    let field = parts.next();
4066    let operator = parts.next();
4067    let value = parts.collect::<Vec<_>>().join(" ");
4068    match (field, operator, value.is_empty()) {
4069        (Some(field), Some(operator), false) => Ok(serde_json::json!({
4070            "field": field,
4071            "operator": operator,
4072            "value": value,
4073        })),
4074        _ => Err(format!(
4075            "INVALID_ARGS: --condition must be 'field operator value', got: {raw:?}"
4076        )),
4077    }
4078}
4079
4080fn normalize_list_envelope(value: Value, list_key: &str, limit: Option<u64>, offset: u64) -> Value {
4081    if let Value::Array(arr) = value {
4082        let total = arr.len() as u64;
4083        let mut obj = serde_json::Map::new();
4084        obj.insert(list_key.to_string(), Value::Array(arr));
4085        obj.insert("total".to_string(), Value::from(total));
4086        if let Some(limit) = limit {
4087            obj.insert("limit".to_string(), Value::from(limit));
4088        }
4089        obj.insert("offset".to_string(), Value::from(offset));
4090        obj.insert("hasMore".to_string(), Value::Bool(false));
4091        return Value::Object(obj);
4092    }
4093
4094    let mut obj = match value {
4095        Value::Object(obj) if obj.contains_key(list_key) => obj,
4096        other => return other,
4097    };
4098
4099    let items_len = obj
4100        .get(list_key)
4101        .and_then(Value::as_array)
4102        .map_or(0, |a| a.len()) as u64;
4103    let total = obj
4104        .get("total")
4105        .and_then(Value::as_u64)
4106        .unwrap_or(items_len);
4107
4108    obj.insert("total".to_string(), Value::from(total));
4109    if let Some(limit) = limit {
4110        obj.insert("limit".to_string(), Value::from(limit));
4111    }
4112    obj.insert("offset".to_string(), Value::from(offset));
4113    obj.insert(
4114        "hasMore".to_string(),
4115        Value::Bool(offset + items_len < total),
4116    );
4117
4118    Value::Object(obj)
4119}
4120
4121const RPC_PAGINATION_SAFETY_CAP: usize = 10_000;
4122const RPC_PAGE_LIST_KEYS: [&str; 4] = ["items", "tags", "results", "data"];
4123
4124fn paginate_rpc(
4125    client: &mut impl RpcCaller,
4126    method: &str,
4127    params: Value,
4128    page_size: usize,
4129) -> Result<Value, String> {
4130    let base = params
4131        .as_object()
4132        .ok_or_else(|| "params must be a JSON object".to_string())?;
4133    let mut out = Vec::new();
4134    let mut prev_page: Option<Vec<Value>> = None;
4135    let mut offset = 0usize;
4136
4137    loop {
4138        let mut page_params = base.clone();
4139        page_params.insert("offset".to_string(), Value::Number(offset.into()));
4140        page_params.insert("limit".to_string(), Value::Number(page_size.into()));
4141        let response = client.call(method, Some(Value::Object(page_params)))?;
4142
4143        let page = match extract_page(&response) {
4144            Some(page) => page,
4145            None if out.is_empty() => return Ok(response),
4146            None if response.is_object() => {
4147                return Err(format!(
4148                    "paginate: {method:?} returned a non-paginated dict after {} accumulated rows; aborting",
4149                    out.len()
4150                ));
4151            }
4152            None => {
4153                return Err(format!(
4154                    "paginate: {method:?} returned non-list/non-dict shape after {} accumulated rows; aborting",
4155                    out.len()
4156                ));
4157            }
4158        };
4159
4160        if prev_page.as_ref() == Some(&page) {
4161            return Err(format!(
4162                "paginate: {method:?} returned identical pages — method likely ignores offset; aborting after {} rows",
4163                out.len()
4164            ));
4165        }
4166
4167        let page_len = page.len();
4168        out.extend(page.clone());
4169        if page_len < page_size {
4170            return Ok(Value::Array(out));
4171        }
4172        if out.len() >= RPC_PAGINATION_SAFETY_CAP {
4173            out.truncate(RPC_PAGINATION_SAFETY_CAP);
4174            return Ok(Value::Array(out));
4175        }
4176        prev_page = Some(page);
4177        offset += page_size;
4178    }
4179}
4180
4181fn extract_page(response: &Value) -> Option<Vec<Value>> {
4182    if let Some(page) = response.as_array() {
4183        return Some(page.clone());
4184    }
4185    let object = response.as_object()?;
4186    for key in RPC_PAGE_LIST_KEYS {
4187        if let Some(page) = object.get(key).and_then(Value::as_array) {
4188            return Some(page.clone());
4189        }
4190    }
4191    None
4192}
4193
4194fn run_find_pdfs_command(
4195    client: &mut impl RpcCaller,
4196    collection: String,
4197    limit: usize,
4198) -> Result<(Value, JsonStyle), String> {
4199    let collection_key = resolve_collection(client, &collection)?;
4200    let response = client.call(
4201        "collections.getItems",
4202        Some(serde_json::json!({"key": collection_key})),
4203    )?;
4204    let items = collection_items(&response);
4205
4206    let mut missing = Vec::new();
4207    for item in &items {
4208        let Some(item_key) = item.get("key").and_then(Value::as_str) else {
4209            continue;
4210        };
4211        let attachments = client.call(
4212            "attachments.list",
4213            Some(serde_json::json!({"parentKey": item_key})),
4214        )?;
4215        if !has_pdf_attachment(&attachments) {
4216            missing.push(item.clone());
4217        }
4218        if limit > 0 && missing.len() >= limit {
4219            break;
4220        }
4221    }
4222
4223    let mut results = Vec::new();
4224    for item in &missing {
4225        let item_key = item
4226            .get("key")
4227            .and_then(Value::as_str)
4228            .ok_or_else(|| "missing item lacks key".to_string())?;
4229        let response = client.call(
4230            "attachments.findPDF",
4231            Some(serde_json::json!({"parentKey": item_key})),
4232        )?;
4233        let attachment = response.get("attachment").filter(|value| !value.is_null());
4234        results.push(serde_json::json!({
4235            "item_key": item_key,
4236            "title": item.get("title").cloned().unwrap_or(Value::Null),
4237            "found": attachment.is_some(),
4238            "attachment_key": attachment
4239                .and_then(|attachment| attachment.get("key"))
4240                .cloned()
4241                .unwrap_or(Value::Null),
4242        }));
4243    }
4244
4245    Ok((
4246        serde_json::json!({
4247            "scanned": items.len(),
4248            "attempted": missing.len(),
4249            "results": results,
4250        }),
4251        JsonStyle::Pretty,
4252    ))
4253}
4254
4255fn collection_items(response: &Value) -> Vec<Value> {
4256    if let Some(items) = response.get("items").and_then(Value::as_array) {
4257        return items.clone();
4258    }
4259    response.as_array().cloned().unwrap_or_default()
4260}
4261
4262fn has_pdf_attachment(attachments: &Value) -> bool {
4263    attachments
4264        .as_array()
4265        .is_some_and(|attachments| attachments.iter().any(is_pdf_attachment))
4266}
4267
4268fn is_pdf_attachment(attachment: &Value) -> bool {
4269    let content_type = attachment
4270        .get("contentType")
4271        .and_then(Value::as_str)
4272        .unwrap_or_default()
4273        .to_lowercase();
4274    let path = attachment
4275        .get("path")
4276        .and_then(Value::as_str)
4277        .unwrap_or_default()
4278        .to_lowercase();
4279    matches!(
4280        content_type.as_str(),
4281        "application/pdf" | "application/x-pdf"
4282    ) || path.ends_with(".pdf")
4283}
4284
4285fn call_json(
4286    client: &mut impl RpcCaller,
4287    method: &str,
4288    params: Option<Value>,
4289) -> Result<Value, String> {
4290    client.call(method, params)
4291}
4292
4293fn run_system_command(
4294    command: SystemCommand,
4295    client: &mut impl RpcCaller,
4296) -> Result<(Value, JsonStyle), String> {
4297    let value = match command {
4298        SystemCommand::Version { .. } => client.call("system.version", None)?,
4299        SystemCommand::Libraries { .. } => client.call("system.libraries", None)?,
4300        SystemCommand::LibraryStats { library, .. } => {
4301            let params = library.map(|id| serde_json::json!({"id": id}));
4302            client.call("system.libraryStats", params)?
4303        }
4304        SystemCommand::Schema { item_type, .. } => {
4305            if let Some(item_type) = item_type {
4306                let fields = client.call("system.itemFields", Some(serde_json::json!({"itemType": item_type})))?;
4307                let creators = client.call("system.creatorTypes", Some(serde_json::json!({"itemType": item_type})))?;
4308                let field_names: Vec<Value> = fields.as_array().unwrap_or(&vec![])
4309                    .iter()
4310                    .filter_map(|f| f.get("field").cloned())
4311                    .collect();
4312                let creator_names: Vec<Value> = creators.as_array().unwrap_or(&vec![])
4313                    .iter()
4314                    .filter_map(|c| c.get("creatorType").cloned())
4315                    .collect();
4316                serde_json::json!({
4317                    "itemType": item_type,
4318                    "fields": field_names,
4319                    "creatorTypes": creator_names,
4320                })
4321            } else {
4322                let types = client.call("system.itemTypes", None)?;
4323                let type_names: Vec<Value> = types.as_array().unwrap_or(&vec![])
4324                    .iter()
4325                    .filter_map(|t| t.get("itemType").cloned())
4326                    .collect();
4327                Value::Array(type_names)
4328            }
4329        }
4330        SystemCommand::CurrentCollection { .. } => client.call("system.currentCollection", None)?,
4331        SystemCommand::ListMethods { .. } => client.call("system.listMethods", None)?,
4332        SystemCommand::Describe { method, .. } => {
4333            let params = method.map(|method| serde_json::json!({"method": method}));
4334            client.call("system.describe", params)?
4335        }
4336    };
4337    Ok((value, JsonStyle::Pretty))
4338}
4339
4340fn run_items_command(
4341    command: ItemsCommand,
4342    client: &mut impl RpcCaller,
4343) -> Result<(Value, JsonStyle), String> {
4344    let (value, style) = match command {
4345        ItemsCommand::Add {
4346            doi,
4347            isbn,
4348            from_url,
4349            file,
4350            collection,
4351            dry_run,
4352            ..
4353        } => {
4354            if let Some(doi) = doi {
4355                run_add_identifier_command(client, "items.addByDOI", "doi", doi, collection, dry_run)?
4356            } else if let Some(isbn) = isbn {
4357                run_add_identifier_command(client, "items.addByISBN", "isbn", isbn, collection, dry_run)?
4358            } else if let Some(from_url) = from_url {
4359                run_add_identifier_command(client, "items.addByURL", "url", from_url, collection, dry_run)?
4360            } else if let Some(file) = file {
4361                let mut params = serde_json::json!({"path": zotero_path(&file)});
4362                maybe_insert_collection(client, &mut params, collection)?;
4363                run_mutation_command(client, "items.addFromFile", params, dry_run)?
4364            } else {
4365                return Err("INVALID_ARGS: provide one of --doi, --isbn, --from-url, or --file".into());
4366            }
4367        }
4368        ItemsCommand::Create {
4369            item_type,
4370            fields,
4371            dry_run,
4372            ..
4373        } => {
4374            let parsed_fields = parse_field_options(&fields)?;
4375            let mut params = serde_json::json!({"itemType": item_type});
4376            if !parsed_fields.is_empty() {
4377                if let Some(map) = params.as_object_mut() {
4378                    map.insert("fields".to_string(), Value::Object(parsed_fields));
4379                }
4380            }
4381            run_mutation_command(client, "items.create", params, dry_run)?
4382        }
4383        ItemsCommand::Update {
4384            key,
4385            fields,
4386            dry_run,
4387            ..
4388        } => {
4389            let parsed_fields = parse_field_options(&fields)?;
4390            let mut params = serde_json::json!({"key": key});
4391            if !parsed_fields.is_empty() {
4392                if let Some(map) = params.as_object_mut() {
4393                    map.insert("fields".to_string(), Value::Object(parsed_fields));
4394                }
4395            }
4396            run_mutation_command(client, "items.update", params, dry_run)?
4397        }
4398        ItemsCommand::Delete { key, dry_run, .. } => run_mutation_command(
4399            client,
4400            "items.delete",
4401            serde_json::json!({"key": key}),
4402            dry_run,
4403        )?,
4404        ItemsCommand::Trash {
4405            items, dry_run, ..
4406        } => {
4407            if items.len() == 1 {
4408                run_mutation_command(
4409                    client,
4410                    "items.trash",
4411                    serde_json::json!({"key": items[0]}),
4412                    dry_run,
4413                )?
4414            } else {
4415                run_mutation_command(
4416                    client,
4417                    "items.batchTrash",
4418                    serde_json::json!({"keys": items}),
4419                    dry_run,
4420                )?
4421            }
4422        }
4423        ItemsCommand::Restore { item, dry_run, .. } => run_mutation_command(
4424            client,
4425            "items.restore",
4426            serde_json::json!({"key": item}),
4427            dry_run,
4428        )?,
4429        ItemsCommand::MergeDuplicates { keys, dry_run, .. } => {
4430            if keys.len() < 2 {
4431                return Err("INVALID_ARGS: need at least 2 keys to merge".to_string());
4432            }
4433            run_mutation_command(
4434                client,
4435                "items.mergeDuplicates",
4436                serde_json::json!({"keys": keys}),
4437                dry_run,
4438            )?
4439        }
4440        ItemsCommand::AddRelated {
4441            key,
4442            target,
4443            dry_run,
4444            ..
4445        } => run_mutation_command(
4446            client,
4447            "items.addRelated",
4448            serde_json::json!({"key": key, "targetKey": target}),
4449            dry_run,
4450        )?,
4451        ItemsCommand::RemoveRelated {
4452            key,
4453            target,
4454            dry_run,
4455            ..
4456        } => run_mutation_command(
4457            client,
4458            "items.removeRelated",
4459            serde_json::json!({"key": key, "targetKey": target}),
4460            dry_run,
4461        )?,
4462        ItemsCommand::Get { item, .. } => (
4463            client.call("items.get", Some(serde_json::json!({"key": item})))?,
4464            JsonStyle::Pretty,
4465        ),
4466        ItemsCommand::List {
4467            limit,
4468            offset,
4469            sort,
4470            direction,
4471            trash,
4472            ..
4473        } => {
4474            if trash {
4475                let value = client.call(
4476                    "items.getTrash",
4477                    Some(serde_json::json!({"limit": limit, "offset": offset})),
4478                )?;
4479                (normalize_list_envelope(value, "items", Some(limit), offset), JsonStyle::Pretty)
4480            } else {
4481                let mut params = serde_json::json!({
4482                    "limit": limit,
4483                    "offset": offset,
4484                    "direction": direction,
4485                });
4486                if let (Some(sort), Some(map)) = (sort, params.as_object_mut()) {
4487                    map.insert("sort".to_string(), Value::String(sort));
4488                }
4489                let value = client.call("items.list", Some(params))?;
4490                (normalize_list_envelope(value, "items", Some(limit), offset), JsonStyle::Pretty)
4491            }
4492        }
4493        ItemsCommand::FindDuplicates { .. } => (
4494            client.call("items.findDuplicates", None)?,
4495            JsonStyle::Pretty,
4496        ),
4497        ItemsCommand::Recent {
4498            limit,
4499            offset,
4500            recent_type,
4501            ..
4502        } => {
4503            if recent_type != "added" && recent_type != "modified" {
4504                return Err(format!(
4505                    "--type must be added or modified, got {recent_type:?}"
4506                ));
4507            }
4508            let value = client.call(
4509                "items.getRecent",
4510                Some(
4511                    serde_json::json!({"limit": limit, "offset": offset, "type": recent_type}),
4512                ),
4513            )?;
4514            (normalize_list_envelope(value, "items", Some(limit), offset), JsonStyle::Pretty)
4515        }
4516        ItemsCommand::Fulltext { key, .. } => (
4517            client.call("items.getFullText", Some(serde_json::json!({"key": key})))?,
4518            JsonStyle::Pretty,
4519        ),
4520        ItemsCommand::Related { key, .. } => (
4521            normalize_list_envelope(
4522                client.call("items.getRelated", Some(serde_json::json!({"key": key})))?,
4523                "items",
4524                None,
4525                0,
4526            ),
4527            JsonStyle::Pretty,
4528        ),
4529        ItemsCommand::CitationKey { key, .. } => (
4530            client.call("items.citationKey", Some(serde_json::json!({"key": key})))?,
4531            JsonStyle::Pretty,
4532        ),
4533    };
4534    Ok((value, style))
4535}
4536
4537fn run_add_identifier_command(
4538    client: &mut impl RpcCaller,
4539    method: &str,
4540    param_name: &str,
4541    param_value: String,
4542    collection: Option<String>,
4543    dry_run: bool,
4544) -> Result<(Value, JsonStyle), String> {
4545    let mut params = Value::Object(serde_json::Map::from_iter([(
4546        param_name.to_string(),
4547        Value::String(param_value),
4548    )]));
4549    maybe_insert_collection(client, &mut params, collection)?;
4550    run_mutation_command(client, method, params, dry_run)
4551}
4552
4553fn run_mutation_command(
4554    client: &mut impl RpcCaller,
4555    method: &str,
4556    params: Value,
4557    dry_run: bool,
4558) -> Result<(Value, JsonStyle), String> {
4559    let value = if dry_run {
4560        serde_json::json!({
4561            "ok": true,
4562            "dryRun": true,
4563            "wouldCall": method,
4564            "wouldCallParams": params,
4565        })
4566    } else {
4567        client.call(method, Some(params))?
4568    };
4569    Ok((value, JsonStyle::PythonCompact))
4570}
4571
4572fn parse_field_options(fields: &[String]) -> Result<serde_json::Map<String, Value>, String> {
4573    let mut parsed = serde_json::Map::new();
4574    for field in fields {
4575        let (key, value) = field
4576            .split_once('=')
4577            .ok_or_else(|| format!("INVALID_ARGS: --field must be key=value, got: {field:?}"))?;
4578        parsed.insert(key.to_string(), Value::String(value.to_string()));
4579    }
4580    Ok(parsed)
4581}
4582
4583fn maybe_insert_collection(
4584    client: &mut impl RpcCaller,
4585    params: &mut Value,
4586    collection: Option<String>,
4587) -> Result<(), String> {
4588    let Some(collection) = collection else {
4589        return Ok(());
4590    };
4591    let collection = resolve_collection(client, &collection)?;
4592    let include = match &collection {
4593        Value::Null => false,
4594        Value::Number(number) => number.as_i64() != Some(0),
4595        _ => true,
4596    };
4597    if include {
4598        params
4599            .as_object_mut()
4600            .expect("mutation params are always objects")
4601            .insert("collection".to_string(), collection);
4602    }
4603    Ok(())
4604}
4605
4606fn run_settings_command(
4607    command: SettingsCommand,
4608    client: &mut impl RpcCaller,
4609) -> Result<(Value, JsonStyle), String> {
4610    let (value, style) = match command {
4611        SettingsCommand::Get { key, .. } => (
4612            client.call("settings.get", Some(serde_json::json!({"key": key})))?,
4613            JsonStyle::Pretty,
4614        ),
4615        SettingsCommand::List { .. } => (client.call("settings.getAll", None)?, JsonStyle::Pretty),
4616        SettingsCommand::Set {
4617            pairs,
4618            file,
4619            dry_run,
4620            ..
4621        } => {
4622            if let Some(file) = file {
4623                // --file mode: read JSON and call settings.setAll
4624                let raw = fs::read_to_string(&file)
4625                    .map_err(|err| format!("INVALID_JSON: Could not read JSON: {err}"))?;
4626                let settings: Value = serde_json::from_str(&raw)
4627                    .map_err(|err| format!("INVALID_JSON: Could not parse JSON: {err}"))?;
4628                if dry_run {
4629                    (
4630                        dry_run_value("settings.setAll", settings),
4631                        JsonStyle::PythonCompact,
4632                    )
4633                } else {
4634                    (
4635                        client.call("settings.setAll", Some(settings))?,
4636                        JsonStyle::PythonCompact,
4637                    )
4638                }
4639            } else if pairs.len() == 2 {
4640                // Single key=value: settings.set
4641                let key = &pairs[0];
4642                let value = &pairs[1];
4643                let parsed_value = serde_json::from_str::<Value>(value)
4644                    .unwrap_or(Value::String(value.clone()));
4645                let params = serde_json::json!({"key": key, "value": parsed_value});
4646                if dry_run {
4647                    (
4648                        dry_run_value("settings.set", params),
4649                        JsonStyle::PythonCompact,
4650                    )
4651                } else {
4652                    (
4653                        client.call("settings.set", Some(params))?,
4654                        JsonStyle::PythonCompact,
4655                    )
4656                }
4657            } else if pairs.len() > 2 && pairs.len() % 2 == 0 {
4658                // Multiple pairs: build a map and call settings.setAll
4659                let mut map = serde_json::Map::new();
4660                for chunk in pairs.chunks(2) {
4661                    let parsed = serde_json::from_str::<Value>(&chunk[1])
4662                        .unwrap_or(Value::String(chunk[1].clone()));
4663                    map.insert(chunk[0].clone(), parsed);
4664                }
4665                let settings = Value::Object(map);
4666                if dry_run {
4667                    (
4668                        dry_run_value("settings.setAll", settings),
4669                        JsonStyle::PythonCompact,
4670                    )
4671                } else {
4672                    (
4673                        client.call("settings.setAll", Some(settings))?,
4674                        JsonStyle::PythonCompact,
4675                    )
4676                }
4677            } else {
4678                return Err(
4679                    "INVALID_ARGS: provide key value pairs (even number of args) or --file".into(),
4680                );
4681            }
4682        }
4683    };
4684    Ok((value, style))
4685}
4686
4687fn run_tags_command(
4688    command: TagsCommand,
4689    client: &mut impl RpcCaller,
4690) -> Result<(Value, JsonStyle), String> {
4691    let (value, style) = match command {
4692        TagsCommand::List { limit, .. } => {
4693            let value = client.call("tags.list", Some(serde_json::json!({"limit": limit})))?;
4694            (normalize_list_envelope(value, "items", Some(limit), 0), JsonStyle::Pretty)
4695        }
4696        TagsCommand::Rename {
4697            old, new, dry_run, ..
4698        } => run_tag_mutation(
4699            client,
4700            "tags.rename",
4701            serde_json::json!({"oldName": old, "newName": new}),
4702            dry_run,
4703        )?,
4704        TagsCommand::Delete { tag, dry_run, .. } => run_tag_mutation(
4705            client,
4706            "tags.delete",
4707            serde_json::json!({"tag": tag}),
4708            dry_run,
4709        )?,
4710        TagsCommand::Add {
4711            keys, tags, dry_run, ..
4712        } => {
4713            if keys.len() == 1 {
4714                run_tag_mutation(
4715                    client,
4716                    "tags.add",
4717                    serde_json::json!({"key": keys[0], "tags": tags}),
4718                    dry_run,
4719                )?
4720            } else {
4721                run_tag_mutation(
4722                    client,
4723                    "tags.batchUpdate",
4724                    serde_json::json!({"keys": keys, "add": tags}),
4725                    dry_run,
4726                )?
4727            }
4728        }
4729        TagsCommand::Remove {
4730            keys, tags, dry_run, ..
4731        } => {
4732            if keys.len() == 1 {
4733                run_tag_mutation(
4734                    client,
4735                    "tags.remove",
4736                    serde_json::json!({"key": keys[0], "tags": tags}),
4737                    dry_run,
4738                )?
4739            } else {
4740                run_tag_mutation(
4741                    client,
4742                    "tags.batchUpdate",
4743                    serde_json::json!({"keys": keys, "remove": tags}),
4744                    dry_run,
4745                )?
4746            }
4747        }
4748    };
4749    Ok((value, style))
4750}
4751
4752fn run_tag_mutation(
4753    client: &mut impl RpcCaller,
4754    method: &str,
4755    params: Value,
4756    dry_run: bool,
4757) -> Result<(Value, JsonStyle), String> {
4758    if dry_run {
4759        Ok((dry_run_value(method, params), JsonStyle::PythonCompact))
4760    } else {
4761        Ok((client.call(method, Some(params))?, JsonStyle::PythonCompact))
4762    }
4763}
4764
4765fn dry_run_value(method: &str, params: Value) -> Value {
4766    serde_json::json!({
4767        "ok": true,
4768        "dryRun": true,
4769        "wouldCall": method,
4770        "wouldCallParams": params,
4771    })
4772}
4773
4774fn run_annotations_command(
4775    command: AnnotationsCommand,
4776    client: &mut impl RpcCaller,
4777) -> Result<(Value, JsonStyle), String> {
4778    let (value, style) = match command {
4779        AnnotationsCommand::List { parent, .. } => {
4780            let value = client.call(
4781                "annotations.list",
4782                Some(serde_json::json!({"parentKey": parent})),
4783            )?;
4784            let total = value
4785                .get("items")
4786                .and_then(Value::as_array)
4787                .map_or(0, |a| a.len()) as u64;
4788            (normalize_list_envelope(value, "items", Some(total), 0), JsonStyle::Pretty)
4789        }
4790        AnnotationsCommand::Create {
4791            parent,
4792            annotation_type,
4793            position,
4794            quote,
4795            page,
4796            sort_index,
4797            text,
4798            comment,
4799            color,
4800            dry_run,
4801            ..
4802        } => {
4803            let annotation_type = annotation_type.unwrap_or_else(|| "highlight".to_string());
4804            if !matches!(
4805                annotation_type.as_str(),
4806                "highlight" | "note" | "underline" | "image" | "ink"
4807            ) {
4808                return Err(format!(
4809                    "INVALID_ARGS: --type must be highlight|note|underline|image|ink, got {annotation_type:?}"
4810                ));
4811            }
4812            let mut params = serde_json::Map::new();
4813            params.insert("parentKey".to_string(), Value::String(parent));
4814            params.insert("type".to_string(), Value::String(annotation_type.clone()));
4815            params.insert("color".to_string(), Value::String(color));
4816
4817            if let Some(ref quote_text) = quote {
4818                if !matches!(annotation_type.as_str(), "highlight" | "underline") {
4819                    return Err(format!(
4820                        "INVALID_ARGS: --quote is only valid for highlight|underline, got {annotation_type:?}"
4821                    ));
4822                }
4823                params.insert("quote".to_string(), Value::String(quote_text.clone()));
4824                if let Some(page_idx) = page {
4825                    params.insert(
4826                        "pageIndex".to_string(),
4827                        Value::Number(page_idx.into()),
4828                    );
4829                }
4830                // When --quote is given, --position is optional
4831                if let Some(raw) = position {
4832                    let pos = serde_json::from_str::<Value>(&raw)
4833                        .map_err(|err| format!("INVALID_JSON: Could not parse --position: {err}"))?;
4834                    validate_annotation_position(annotation_type.as_str(), &pos)?;
4835                    params.insert("position".to_string(), pos);
4836                }
4837            } else {
4838                let position = position
4839                    .ok_or_else(|| "INVALID_ARGS: --position JSON is required (or use --quote)".to_string())
4840                    .and_then(|raw| {
4841                        serde_json::from_str::<Value>(&raw)
4842                            .map_err(|err| format!("INVALID_JSON: Could not parse --position: {err}"))
4843                    })?;
4844                validate_annotation_position(annotation_type.as_str(), &position)?;
4845                params.insert("position".to_string(), position);
4846            }
4847
4848            if let Some(sort_index) = sort_index {
4849                params.insert(
4850                    "sortIndex".to_string(),
4851                    parse_annotation_sort_index(sort_index)?,
4852                );
4853            }
4854            if let Some(text) = text {
4855                params.insert("text".to_string(), Value::String(text));
4856            }
4857            if let Some(comment) = comment {
4858                params.insert("comment".to_string(), Value::String(comment));
4859            }
4860            run_mutating_command(client, "annotations.create", Value::Object(params), dry_run)?
4861        }
4862        AnnotationsCommand::Delete {
4863            annotation_key,
4864            dry_run,
4865            ..
4866        } => run_mutating_command(
4867            client,
4868            "annotations.delete",
4869            serde_json::json!({"key": annotation_key}),
4870            dry_run,
4871        )?,
4872    };
4873    Ok((value, style))
4874}
4875
4876fn validate_annotation_position(annotation_type: &str, position: &Value) -> Result<(), String> {
4877    position
4878        .get("pageIndex")
4879        .and_then(Value::as_i64)
4880        .filter(|value| *value >= 0)
4881        .ok_or_else(|| {
4882            "INVALID_ARGS: --position must include a non-negative integer pageIndex".to_string()
4883        })?;
4884
4885    if annotation_type == "ink" {
4886        let has_paths = position
4887            .get("paths")
4888            .and_then(Value::as_array)
4889            .is_some_and(|paths| !paths.is_empty());
4890        if !has_paths {
4891            return Err("INVALID_ARGS: ink --position must include non-empty paths".to_string());
4892        }
4893        return Ok(());
4894    }
4895
4896    let valid_rects = position
4897        .get("rects")
4898        .and_then(Value::as_array)
4899        .is_some_and(|rects| !rects.is_empty() && rects.iter().all(is_annotation_rect));
4900    if !valid_rects {
4901        return Err(
4902            "INVALID_ARGS: --position must include non-empty rects of [x1, y1, x2, y2]".to_string(),
4903        );
4904    }
4905    Ok(())
4906}
4907
4908fn is_annotation_rect(value: &Value) -> bool {
4909    value.as_array().is_some_and(|coords| {
4910        coords.len() == 4
4911            && coords
4912                .iter()
4913                .all(|coord| coord.as_f64().is_some_and(f64::is_finite))
4914    })
4915}
4916
4917fn parse_annotation_sort_index(raw: String) -> Result<Value, String> {
4918    let parsed = serde_json::from_str::<Value>(&raw).unwrap_or_else(|_| Value::String(raw));
4919    let valid = match &parsed {
4920        Value::Number(number) => number.as_f64().is_some_and(f64::is_finite),
4921        Value::String(value) => {
4922            is_zotero_pdf_sort_index(value.trim())
4923                || (!value.trim().is_empty()
4924                    && value.trim().parse::<f64>().is_ok_and(f64::is_finite))
4925        }
4926        _ => false,
4927    };
4928    if valid {
4929        Ok(parsed)
4930    } else {
4931        Err(format!(
4932            "INVALID_ARGS: --sort-index must be a finite number or numeric string, got {parsed}"
4933        ))
4934    }
4935}
4936
4937fn is_zotero_pdf_sort_index(value: &str) -> bool {
4938    let mut parts = value.split('|');
4939    matches!(
4940        (parts.next(), parts.next(), parts.next(), parts.next()),
4941        (Some(page), Some(offset), Some(y), None)
4942            if page.len() == 5
4943                && offset.len() == 6
4944                && y.len() == 5
4945                && page.chars().all(|ch| ch.is_ascii_digit())
4946                && offset.chars().all(|ch| ch.is_ascii_digit())
4947                && y.chars().all(|ch| ch.is_ascii_digit())
4948    )
4949}
4950
4951fn run_attachments_command(
4952    command: AttachmentsCommand,
4953    client: &mut impl RpcCaller,
4954) -> Result<(Value, JsonStyle), String> {
4955    let value = match command {
4956        AttachmentsCommand::List {
4957            parent,
4958            limit,
4959            offset,
4960            ..
4961        } => normalize_list_envelope(
4962            client.call(
4963                "attachments.list",
4964                Some(serde_json::json!({"parentKey": parent})),
4965            )?,
4966            "items",
4967            Some(limit),
4968            offset,
4969        ),
4970        AttachmentsCommand::Get { key, .. } => {
4971            client.call("attachments.get", Some(serde_json::json!({"key": key})))?
4972        }
4973        AttachmentsCommand::Fulltext { key, .. } => client.call(
4974            "attachments.getFulltext",
4975            Some(serde_json::json!({"key": key})),
4976        )?,
4977        AttachmentsCommand::Path { key, .. } => localize_attachment_path_response(
4978            client.call("attachments.getPath", Some(serde_json::json!({"key": key})))?,
4979        ),
4980        AttachmentsCommand::Add {
4981            parent,
4982            path,
4983            from_url,
4984            title,
4985            dry_run,
4986            ..
4987        } => {
4988            match (path, from_url) {
4989                (Some(p), None) => {
4990                    let mut params = serde_json::json!({"parentKey": parent, "path": zotero_path(&p)});
4991                    insert_optional_string(&mut params, "title", title);
4992                    if dry_run {
4993                        return Ok((
4994                            dry_run_value("attachments.add", params),
4995                            JsonStyle::PythonCompact,
4996                        ));
4997                    }
4998                    return Ok((
4999                        client.call("attachments.add", Some(params))?,
5000                        JsonStyle::PythonCompact,
5001                    ));
5002                }
5003                (None, Some(u)) => {
5004                    let mut params = serde_json::json!({"parentKey": parent, "url": u});
5005                    insert_optional_string(&mut params, "title", title);
5006                    if dry_run {
5007                        return Ok((
5008                            dry_run_value("attachments.addByURL", params),
5009                            JsonStyle::PythonCompact,
5010                        ));
5011                    }
5012                    return Ok((
5013                        client.call("attachments.addByURL", Some(params))?,
5014                        JsonStyle::PythonCompact,
5015                    ));
5016                }
5017                (Some(_), Some(_)) => {
5018                    return Err("INVALID_ARGS: --path and --from-url are mutually exclusive".to_string());
5019                }
5020                (None, None) => {
5021                    return Err("INVALID_ARGS: either --path or --from-url is required".to_string());
5022                }
5023            }
5024        }
5025        AttachmentsCommand::Delete { key, dry_run, .. } => {
5026            let params = serde_json::json!({"key": key});
5027            if dry_run {
5028                return Ok((
5029                    dry_run_value("attachments.delete", params),
5030                    JsonStyle::PythonCompact,
5031                ));
5032            }
5033            return Ok((
5034                client.call("attachments.delete", Some(params))?,
5035                JsonStyle::PythonCompact,
5036            ));
5037        }
5038        AttachmentsCommand::FindPdf { parent, .. } => client.call(
5039            "attachments.findPDF",
5040            Some(serde_json::json!({"parentKey": parent})),
5041        )?,
5042    };
5043    Ok((value, JsonStyle::Pretty))
5044}
5045
5046fn localize_attachment_path_response(mut value: Value) -> Value {
5047    if let Some(path) = value.get("path").and_then(Value::as_str) {
5048        let local = local_path_from_zotero_path(path);
5049        if let Some(map) = value.as_object_mut() {
5050            map.insert("path".to_string(), Value::String(local));
5051        }
5052    }
5053    value
5054}
5055
5056fn run_notes_command(
5057    command: NotesCommand,
5058    client: &mut impl RpcCaller,
5059) -> Result<(Value, JsonStyle), String> {
5060    let (value, style) = match command {
5061        NotesCommand::List {
5062            parent,
5063            limit,
5064            offset,
5065            ..
5066        } => {
5067            let value = client.call(
5068                "notes.list",
5069                Some(serde_json::json!({"parentKey": parent})),
5070            )?;
5071            (normalize_list_envelope(value, "items", Some(limit), offset), JsonStyle::Pretty)
5072        }
5073        NotesCommand::Get { note_key, .. } => {
5074            let value = client.call("notes.get", Some(serde_json::json!({"key": note_key})))?;
5075            (value, JsonStyle::Pretty)
5076        }
5077        NotesCommand::Create {
5078            parent,
5079            content,
5080            tags,
5081            dry_run,
5082            ..
5083        } => {
5084            let mut params = serde_json::Map::new();
5085            params.insert("parentKey".to_string(), Value::String(parent));
5086            params.insert("content".to_string(), Value::String(content));
5087            if !tags.is_empty() {
5088                params.insert(
5089                    "tags".to_string(),
5090                    Value::Array(tags.into_iter().map(Value::String).collect()),
5091                );
5092            }
5093            run_mutating_command(client, "notes.create", Value::Object(params), dry_run)?
5094        }
5095        NotesCommand::Update {
5096            note_key,
5097            content,
5098            dry_run,
5099            ..
5100        } => run_mutating_command(
5101            client,
5102            "notes.update",
5103            serde_json::json!({"key": note_key, "content": content}),
5104            dry_run,
5105        )?,
5106        NotesCommand::Delete {
5107            note_key, dry_run, ..
5108        } => {
5109            // Python CLI intentionally routes note deletion through items.delete.
5110            run_mutating_command(
5111                client,
5112                "items.delete",
5113                serde_json::json!({"key": note_key}),
5114                dry_run,
5115            )?
5116        }
5117        NotesCommand::Search { query, limit, .. } => {
5118            let value = client.call(
5119                "notes.search",
5120                Some(serde_json::json!({"query": query, "limit": limit})),
5121            )?;
5122            (normalize_list_envelope(value, "items", Some(limit), 0), JsonStyle::Pretty)
5123        }
5124    };
5125    Ok((value, style))
5126}
5127
5128fn run_mutating_command(
5129    client: &mut impl RpcCaller,
5130    method: &str,
5131    params: Value,
5132    dry_run: bool,
5133) -> Result<(Value, JsonStyle), String> {
5134    if dry_run {
5135        Ok((
5136            serde_json::json!({
5137                "ok": true,
5138                "dryRun": true,
5139                "wouldCall": method,
5140                "wouldCallParams": params,
5141            }),
5142            JsonStyle::PythonCompact,
5143        ))
5144    } else {
5145        client
5146            .call(method, Some(params))
5147            .map(|value| (value, JsonStyle::PythonCompact))
5148    }
5149}
5150
5151fn run_collections_command(
5152    command: CollectionsCommand,
5153    client: &mut impl RpcCaller,
5154) -> Result<(Value, JsonStyle), String> {
5155    let value = match command {
5156        CollectionsCommand::List { .. } => normalize_list_envelope(
5157            client.call("collections.list", None)?,
5158            "items",
5159            None,
5160            0,
5161        ),
5162        CollectionsCommand::Tree { .. } => client.call("collections.tree", None)?,
5163        CollectionsCommand::Get { name_or_id, .. } => {
5164            let key = resolve_collection(client, &name_or_id)?;
5165            client.call("collections.get", Some(serde_json::json!({"key": key})))?
5166        }
5167        CollectionsCommand::GetItems {
5168            name_or_id,
5169            limit,
5170            offset,
5171            ..
5172        } => {
5173            let key = resolve_collection(client, &name_or_id)?;
5174            let mut params = serde_json::json!({"key": key});
5175            if let Some(map) = params.as_object_mut() {
5176                if let Some(limit) = limit {
5177                    map.insert("limit".to_string(), Value::Number(limit.into()));
5178                }
5179                if offset > 0 {
5180                    map.insert("offset".to_string(), Value::Number(offset.into()));
5181                }
5182            }
5183            normalize_list_envelope(
5184                client.call("collections.getItems", Some(params))?,
5185                "items",
5186                limit,
5187                offset,
5188            )
5189        }
5190        CollectionsCommand::Stats { name_or_id, .. } => {
5191            let key = resolve_collection(client, &name_or_id)?;
5192            client.call("collections.stats", Some(serde_json::json!({"key": key})))?
5193        }
5194        CollectionsCommand::Rename {
5195            old_name,
5196            new_name,
5197            dry_run,
5198            ..
5199        } => {
5200            let key = resolve_mutable_collection(client, &old_name, "rename")?;
5201            let params = serde_json::json!({"key": key, "name": new_name});
5202            if dry_run {
5203                return Ok((
5204                    dry_run_value("collections.rename", params),
5205                    JsonStyle::PythonCompact,
5206                ));
5207            }
5208            return Ok((
5209                client.call("collections.rename", Some(params))?,
5210                JsonStyle::PythonCompact,
5211            ));
5212        }
5213        CollectionsCommand::Create {
5214            name,
5215            parent,
5216            dry_run,
5217            ..
5218        } => {
5219            let mut params = serde_json::json!({"name": name});
5220            if let Some(parent) = parent {
5221                let parent_key = resolve_mutable_collection(client, &parent, "use as parent")?;
5222                if let Some(map) = params.as_object_mut() {
5223                    map.insert("parentKey".to_string(), parent_key);
5224                }
5225            }
5226            if dry_run {
5227                return Ok((
5228                    dry_run_value("collections.create", params),
5229                    JsonStyle::PythonCompact,
5230                ));
5231            }
5232            return Ok((
5233                client.call("collections.create", Some(params))?,
5234                JsonStyle::PythonCompact,
5235            ));
5236        }
5237        CollectionsCommand::Delete {
5238            name_or_id,
5239            dry_run,
5240            ..
5241        } => {
5242            let key = resolve_mutable_collection(client, &name_or_id, "delete")?;
5243            let params = serde_json::json!({"key": key});
5244            if dry_run {
5245                return Ok((
5246                    dry_run_value("collections.delete", params),
5247                    JsonStyle::PythonCompact,
5248                ));
5249            }
5250            return Ok((
5251                client.call("collections.delete", Some(params))?,
5252                JsonStyle::PythonCompact,
5253            ));
5254        }
5255        CollectionsCommand::AddItems {
5256            collection,
5257            item_keys,
5258            dry_run,
5259            ..
5260        } => {
5261            let key = resolve_mutable_collection(client, &collection, "add to")?;
5262            let params = serde_json::json!({"key": key, "keys": item_keys});
5263            if dry_run {
5264                return Ok((
5265                    dry_run_value("collections.addItems", params),
5266                    JsonStyle::PythonCompact,
5267                ));
5268            }
5269            return Ok((
5270                client.call("collections.addItems", Some(params))?,
5271                JsonStyle::PythonCompact,
5272            ));
5273        }
5274        CollectionsCommand::RemoveItems {
5275            collection,
5276            item_keys,
5277            dry_run,
5278            ..
5279        } => {
5280            let key = resolve_mutable_collection(client, &collection, "operate on")?;
5281            let params = serde_json::json!({"key": key, "keys": item_keys});
5282            if dry_run {
5283                return Ok((
5284                    dry_run_value("collections.removeItems", params),
5285                    JsonStyle::PythonCompact,
5286                ));
5287            }
5288            return Ok((
5289                client.call("collections.removeItems", Some(params))?,
5290                JsonStyle::PythonCompact,
5291            ));
5292        }
5293    };
5294    Ok((value, JsonStyle::Pretty))
5295}
5296
5297fn resolve_export_keys(
5298    client: &mut impl RpcCaller,
5299    mut keys: Vec<String>,
5300    collection: Option<String>,
5301) -> Result<Vec<String>, String> {
5302    if let Some(name) = collection {
5303        let col_key = resolve_collection(client, &name)?;
5304        let response = client.call(
5305            "collections.getItems",
5306            Some(serde_json::json!({"key": col_key})),
5307        )?;
5308        let items = collection_items(&response);
5309        for item in items {
5310            if let Some(key) = item.get("key").and_then(Value::as_str) {
5311                if !keys.contains(&key.to_string()) {
5312                    keys.push(key.to_string());
5313                }
5314            }
5315        }
5316    }
5317    if keys.is_empty() {
5318        return Err("No item keys provided. Pass positional keys and/or --collection.".to_string());
5319    }
5320    Ok(keys)
5321}
5322
5323fn run_export(args: ExportArgs, client: &mut impl RpcCaller) -> Result<String, String> {
5324    let keys = resolve_export_keys(client, args.keys, args.collection)?;
5325    match args.format.as_str() {
5326        "bibtex" => run_export_content_command(client, "export.bibtex", keys),
5327        "ris" => run_export_content_command(client, "export.ris", keys),
5328        "csl-json" => {
5329            let response =
5330                client.call("export.cslJson", Some(serde_json::json!({"keys": keys})))?;
5331            if let Some(content) = response.get("content") {
5332                format_json(content, JsonStyle::Pretty)
5333            } else {
5334                format_json(&response, JsonStyle::PythonCompact)
5335            }
5336        }
5337        "bibliography" => {
5338            let response = client.call(
5339                "export.bibliography",
5340                Some(serde_json::json!({"keys": keys, "style": args.style})),
5341            )?;
5342            if let Some(object) = response.as_object() {
5343                let field = if args.html { "html" } else { "text" };
5344                if object.contains_key("html") || object.contains_key("text") {
5345                    return raw_value_output(
5346                        object.get(field).unwrap_or(&Value::String(String::new())),
5347                    );
5348                }
5349            }
5350            format_json(&response, JsonStyle::PythonCompact)
5351        }
5352        other => Err(format!(
5353            "INVALID_ARGS: unknown format {other:?}, expected bibtex/ris/csl-json/bibliography"
5354        )),
5355    }
5356}
5357
5358fn run_export_content_command(
5359    client: &mut impl RpcCaller,
5360    method: &str,
5361    keys: Vec<String>,
5362) -> Result<String, String> {
5363    let response = client.call(method, Some(serde_json::json!({"keys": keys})))?;
5364    if let Some(content) = response.get("content") {
5365        raw_value_output(content)
5366    } else {
5367        format_json(&response, JsonStyle::PythonCompact)
5368    }
5369}
5370
5371fn raw_value_output(value: &Value) -> Result<String, String> {
5372    let mut out = match value {
5373        Value::Null => String::new(),
5374        Value::String(content) => content.clone(),
5375        other => to_python_repr(other),
5376    };
5377    out.push('\n');
5378    Ok(out)
5379}
5380
5381fn to_python_repr(value: &Value) -> String {
5382    match value {
5383        Value::Null => "None".to_string(),
5384        Value::Bool(value) => {
5385            if *value {
5386                "True".to_string()
5387            } else {
5388                "False".to_string()
5389            }
5390        }
5391        Value::Number(value) => value.to_string(),
5392        Value::String(value) => format!("'{}'", value.replace('\\', "\\\\").replace('\'', "\\'")),
5393        Value::Array(values) => {
5394            let inner = values
5395                .iter()
5396                .map(to_python_repr)
5397                .collect::<Vec<_>>()
5398                .join(", ");
5399            format!("[{inner}]")
5400        }
5401        Value::Object(entries) => {
5402            let inner = entries
5403                .iter()
5404                .map(|(key, value)| {
5405                    format!("'{}': {}", key.replace('\'', "\\'"), to_python_repr(value))
5406                })
5407                .collect::<Vec<_>>()
5408                .join(", ");
5409            format!("{{{inner}}}")
5410        }
5411    }
5412}
5413
5414fn resolve_collection(client: &mut impl RpcCaller, name_or_id: &str) -> Result<Value, String> {
5415    let trimmed = name_or_id.trim();
5416    if let Ok(id) = trimmed.parse::<i64>() {
5417        return Ok(Value::Number(id.into()));
5418    }
5419
5420    let collections = client.call("collections.list", None)?;
5421    let items = collections
5422        .get("items")
5423        .and_then(Value::as_array)
5424        .or_else(|| collections.as_array())
5425        .ok_or_else(|| "collections.list returned non-array result".to_string())?;
5426
5427    if let Some(collection) = items
5428        .iter()
5429        .find(|collection| collection.get("key").and_then(Value::as_str) == Some(trimmed))
5430    {
5431        return collection_key(collection);
5432    }
5433
5434    let exact = items
5435        .iter()
5436        .filter(|collection| collection.get("name").and_then(Value::as_str) == Some(trimmed))
5437        .collect::<Vec<_>>();
5438    if exact.len() == 1 {
5439        return collection_key(exact[0]);
5440    }
5441
5442    let needle = normalize_collection_name(trimmed);
5443    let fuzzy = items
5444        .iter()
5445        .filter(|collection| {
5446            collection
5447                .get("name")
5448                .and_then(Value::as_str)
5449                .map(normalize_collection_name)
5450                .is_some_and(|name| name.contains(&needle))
5451        })
5452        .collect::<Vec<_>>();
5453
5454    match fuzzy.len() {
5455        1 => collection_key(fuzzy[0]),
5456        0 => Err(format!(
5457            "COLLECTION_NOT_FOUND: No collection named {trimmed:?}"
5458        )),
5459        _ => Err(format!(
5460            "COLLECTION_AMBIGUOUS: Multiple collections match {trimmed:?}"
5461        )),
5462    }
5463}
5464
5465fn collection_key(collection: &Value) -> Result<Value, String> {
5466    collection
5467        .get("key")
5468        .cloned()
5469        .ok_or_else(|| "collection result is missing key".to_string())
5470}
5471
5472fn resolve_mutable_collection(
5473    client: &mut impl RpcCaller,
5474    name_or_id: &str,
5475    operation: &str,
5476) -> Result<Value, String> {
5477    let key = resolve_collection(client, name_or_id)?;
5478    if key.as_i64() == Some(0) {
5479        return Err(format!(
5480            "COLLECTION_NOT_FOUND: {name_or_id:?} resolved to library root (cannot {operation})"
5481        ));
5482    }
5483    Ok(key)
5484}
5485
5486fn insert_optional_string(value: &mut Value, key: &str, maybe: Option<String>) {
5487    if let (Some(map), Some(content)) = (value.as_object_mut(), maybe) {
5488        map.insert(key.to_string(), Value::String(content));
5489    }
5490}
5491
5492fn normalize_collection_name(name: &str) -> String {
5493    name.split_whitespace()
5494        .collect::<Vec<_>>()
5495        .join(" ")
5496        .to_lowercase()
5497}
5498
5499fn format_json(value: &Value, style: JsonStyle) -> Result<String, String> {
5500    let mut out = match style {
5501        JsonStyle::PythonCompact => to_python_compact_json(value),
5502        JsonStyle::Pretty => serde_json::to_string_pretty(value).map_err(|err| err.to_string())?,
5503    };
5504    out.push('\n');
5505    Ok(out)
5506}
5507
5508fn to_python_compact_json(value: &Value) -> String {
5509    match value {
5510        Value::Null => "null".to_string(),
5511        Value::Bool(value) => value.to_string(),
5512        Value::Number(value) => value.to_string(),
5513        Value::String(value) => {
5514            serde_json::to_string(value).expect("string serialization cannot fail")
5515        }
5516        Value::Array(values) => {
5517            let inner = values
5518                .iter()
5519                .map(to_python_compact_json)
5520                .collect::<Vec<_>>()
5521                .join(", ");
5522            format!("[{inner}]")
5523        }
5524        Value::Object(entries) => {
5525            let inner = entries
5526                .iter()
5527                .map(|(key, value)| {
5528                    let key = serde_json::to_string(key).expect("string serialization cannot fail");
5529                    format!("{key}: {}", to_python_compact_json(value))
5530                })
5531                .collect::<Vec<_>>()
5532                .join(", ");
5533            format!("{{{inner}}}")
5534        }
5535    }
5536}