xberg-cli 1.3.0

Command-line interface for Xberg document intelligence
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
//! Cache command - Manage cache operations
//!
//! This module provides commands for cache management including statistics,
//! clearing, manifest generation, and model warming.

use anyhow::{Context, Result};
use serde_json::json;
#[cfg(any(
    feature = "embeddings",
    feature = "layout-detection",
    feature = "paddle-ocr",
    feature = "tree-sitter",
    feature = "ner-onnx"
))]
use std::path::Path;
use std::path::PathBuf;
use xberg::cache;

use crate::{WireFormat, style};

#[cfg(any(
    feature = "paddle-ocr",
    feature = "layout-detection",
    feature = "ner-onnx",
    feature = "formula-recognition"
))]
#[derive(Debug, Clone, serde::Serialize)]
struct CacheManifestEntry {
    relative_path: String,
    sha256: String,
    size_bytes: u64,
    source_url: String,
}

#[cfg(any(
    feature = "paddle-ocr",
    feature = "layout-detection",
    feature = "ner-onnx",
    feature = "formula-recognition"
))]
impl CacheManifestEntry {
    fn new(relative_path: String, sha256: String, size_bytes: u64, source_url: String) -> Self {
        Self {
            relative_path,
            sha256,
            size_bytes,
            source_url,
        }
    }
}

/// Execute cache stats command
#[expect(
    clippy::print_stdout,
    reason = "cache statistics are the command's stdout result output"
)]
pub fn stats_command(cache_dir: Option<PathBuf>, format: WireFormat) -> Result<()> {
    let default_cache_dir = std::env::current_dir()
        .context("Failed to get current directory")?
        .join(".xberg");

    let cache_path = cache_dir.unwrap_or(default_cache_dir);
    let cache_dir_str = cache_path.to_string_lossy();

    let stats = cache::get_cache_metadata(&cache_dir_str).with_context(|| {
        format!(
            "Failed to get cache statistics from directory '{}'. Ensure the directory exists and is readable.",
            cache_dir_str
        )
    })?;

    match format {
        WireFormat::Text => {
            println!("{}", style::header("Cache Statistics"));
            println!("{}", style::dim("================"));
            println!("{} {}", style::label("Directory:"), style::success(&cache_dir_str));
            println!("{} {}", style::label("Total files:"), stats.total_files);
            println!("{} {:.2} MB", style::label("Total size:"), stats.total_size_mb);
            println!(
                "{} {:.2} MB",
                style::label("Available space:"),
                stats.available_space_mb
            );
            println!(
                "{} {:.2} days",
                style::label("Oldest file age:"),
                stats.oldest_file_age_days
            );
            println!(
                "{} {:.2} days",
                style::label("Newest file age:"),
                stats.newest_file_age_days
            );
        }
        WireFormat::Json => {
            let output = json!({
                "directory": cache_dir_str,
                "total_files": stats.total_files,
                "total_size_mb": stats.total_size_mb,
                "available_space_mb": stats.available_space_mb,
                "oldest_file_age_days": stats.oldest_file_age_days,
                "newest_file_age_days": stats.newest_file_age_days,
            });
            println!(
                "{}",
                serde_json::to_string_pretty(&output).context("Failed to serialize cache statistics to JSON")?
            );
        }
        WireFormat::Toon => {
            let output = json!({
                "directory": cache_dir_str,
                "total_files": stats.total_files,
                "total_size_mb": stats.total_size_mb,
                "available_space_mb": stats.available_space_mb,
                "oldest_file_age_days": stats.oldest_file_age_days,
                "newest_file_age_days": stats.newest_file_age_days,
            });
            println!(
                "{}",
                serde_toon::to_string(&output).context("Failed to serialize cache statistics to TOON")?
            );
        }
    }

    Ok(())
}

/// Clear the Xberg-managed cache. Shared Hugging Face cache files are excluded.
#[expect(
    clippy::print_stdout,
    reason = "cache clear summary is the command's stdout result output"
)]
pub fn clear_command(cache_dir: Option<PathBuf>, format: WireFormat) -> Result<()> {
    let default_cache_dir = std::env::current_dir()
        .context("Failed to get current directory")?
        .join(".xberg");

    let cache_path = cache_dir.unwrap_or(default_cache_dir);
    let cache_dir_str = cache_path.to_string_lossy();

    let (removed_files, freed_mb) = cache::clear_cache_directory(&cache_dir_str).with_context(|| {
        format!(
            "Failed to clear cache directory '{}'. Ensure you have write permissions.",
            cache_dir_str
        )
    })?;

    match format {
        WireFormat::Text => {
            println!("{}", style::success("Xberg-managed cache cleared successfully"));
            println!("Shared Hugging Face Hub cache files were not removed.");
            println!("{} {}", style::label("Directory:"), style::success(&cache_dir_str));
            println!("{} {}", style::label("Removed files:"), removed_files);
            println!("{} {:.2} MB", style::label("Freed space:"), freed_mb);
        }
        WireFormat::Json => {
            let output = json!({
                "directory": cache_dir_str,
                "removed_files": removed_files,
                "freed_mb": freed_mb,
                "hugging_face_cache_cleared": false,
            });
            println!(
                "{}",
                serde_json::to_string_pretty(&output).context("Failed to serialize cache clear results to JSON")?
            );
        }
        WireFormat::Toon => {
            let output = json!({
                "directory": cache_dir_str,
                "removed_files": removed_files,
                "freed_mb": freed_mb,
                "hugging_face_cache_cleared": false,
            });
            println!(
                "{}",
                serde_toon::to_string(&output).context("Failed to serialize cache clear results to TOON")?
            );
        }
    }

    Ok(())
}

/// Execute cache manifest command - outputs expected model files with checksums.
pub fn manifest_command(format: WireFormat) -> Result<()> {
    // below is `#[cfg]`-stripped and `entries: Vec<_>` has no anchor for
    #[cfg(not(any(
        feature = "paddle-ocr",
        feature = "layout-detection",
        feature = "ner-onnx",
        feature = "formula-recognition"
    )))]
    {
        let _ = format;
        anyhow::bail!(
            "manifest command unavailable: build xberg-cli with at least one of \
             --features \"paddle-ocr\", \"layout-detection\", or \"ner-onnx\""
        );
    }

    #[cfg(any(
        feature = "paddle-ocr",
        feature = "layout-detection",
        feature = "ner-onnx",
        feature = "formula-recognition"
    ))]
    {
        manifest_command_inner(format)
    }
}

/// Gather the manifest entries for every model source compiled into this binary.
#[cfg(any(
    feature = "paddle-ocr",
    feature = "layout-detection",
    feature = "ner-onnx",
    feature = "formula-recognition"
))]
fn collect_manifest_entries() -> Vec<CacheManifestEntry> {
    let mut entries: Vec<CacheManifestEntry> = Vec::new();

    #[cfg(feature = "paddle-ocr")]
    {
        entries.extend(xberg::paddle_ocr::ModelManager::manifest().into_iter().map(|entry| {
            CacheManifestEntry::new(entry.relative_path, entry.sha256, entry.size_bytes, entry.source_url)
        }));
    }

    #[cfg(feature = "layout-detection")]
    {
        entries.extend(xberg::layout::LayoutModelManager::manifest().into_iter().map(|entry| {
            CacheManifestEntry::new(entry.relative_path, entry.sha256, entry.size_bytes, entry.source_url)
        }));
    }

    #[cfg(feature = "formula-recognition")]
    {
        entries.extend(xberg::formula_recognition::manifest().into_iter().map(|entry| {
            CacheManifestEntry::new(entry.relative_path, entry.sha256, entry.size_bytes, entry.source_url)
        }));
    }

    #[cfg(feature = "paddle-ocr")]
    {
        entries.extend(xberg::ocr::TessdataManager::manifest().into_iter().map(|entry| {
            CacheManifestEntry::new(entry.relative_path, entry.sha256, entry.size_bytes, entry.source_url)
        }));
    }

    #[cfg(feature = "ner-onnx")]
    {
        entries.extend(xberg::text::ner::manifest().into_iter().map(|entry| {
            CacheManifestEntry::new(entry.relative_path, entry.sha256, entry.size_bytes, entry.source_url)
        }));
    }

    entries
}

/// Print the model manifest as a human-readable table.
#[cfg(any(
    feature = "paddle-ocr",
    feature = "layout-detection",
    feature = "ner-onnx",
    feature = "formula-recognition"
))]
#[expect(
    clippy::print_stdout,
    reason = "model manifest is the command's stdout result output"
)]
fn print_manifest_text(entries: &[CacheManifestEntry], version: &str, total_size_bytes: u64) {
    println!(
        "{} {}",
        style::header("Model Manifest"),
        style::dim(&format!("(xberg {version})"))
    );
    println!("{}", style::dim("===================================="));
    println!(
        "{:<50} {:>12} {}",
        style::label("PATH"),
        style::label("SIZE"),
        style::label("SHA256")
    );
    println!("{}", style::dim(&format!("{:<50} {:>12} ------", "----", "----")));
    for entry in entries {
        let size_str = if entry.size_bytes > 0 {
            format!("{:.1} MB", entry.size_bytes as f64 / 1_048_576.0)
        } else {
            "unknown".to_string()
        };
        let sha_display = if entry.sha256.len() >= 12 {
            &entry.sha256[..12]
        } else if entry.sha256.is_empty() {
            "-"
        } else {
            &entry.sha256
        };
        println!(
            "{:<50} {:>12} {}",
            entry.relative_path,
            size_str,
            style::dim(sha_display)
        );
    }
    println!();
    println!(
        "{} {} files, {:.1} MB",
        style::label("Total:"),
        entries.len(),
        total_size_bytes as f64 / 1_048_576.0
    );
}

#[cfg(any(
    feature = "paddle-ocr",
    feature = "layout-detection",
    feature = "ner-onnx",
    feature = "formula-recognition"
))]
#[expect(
    clippy::print_stdout,
    reason = "model manifest is the command's stdout result output"
)]
fn manifest_command_inner(format: WireFormat) -> Result<()> {
    let entries = collect_manifest_entries();
    let total_size_bytes: u64 = entries.iter().map(|e| e.size_bytes).sum();
    let version = env!("CARGO_PKG_VERSION");

    match format {
        WireFormat::Text => print_manifest_text(&entries, version, total_size_bytes),
        WireFormat::Json => {
            let output = json!({
                "xberg_version": version,
                "total_size_bytes": total_size_bytes,
                "model_count": entries.len(),
                "models": entries,
            });
            println!(
                "{}",
                serde_json::to_string_pretty(&output).context("Failed to serialize manifest to JSON")?
            );
        }
        WireFormat::Toon => {
            let output = json!({
                "xberg_version": version,
                "total_size_bytes": total_size_bytes,
                "model_count": entries.len(),
                "models": entries,
            });
            println!(
                "{}",
                serde_toon::to_string(&output).context("Failed to serialize manifest to TOON")?
            );
        }
    }

    Ok(())
}

/// Feature-gated options for [`warm_command`], bundled so the command function itself
/// stays within the CLI's parameter-count limit. Each field only exists when its owning
/// feature is enabled, mirroring the `warm` subcommand's own `#[cfg]`-gated CLI flags. ~keep
#[cfg(any(
    feature = "embeddings",
    feature = "layout-detection",
    feature = "paddle-ocr",
    feature = "tree-sitter",
    feature = "ner-onnx"
))]
#[derive(Debug, Default)]
pub struct WarmOptions {
    #[cfg(feature = "embeddings")]
    pub all_embeddings: bool,
    #[cfg(feature = "embeddings")]
    pub embedding_model: Option<String>,
    #[cfg(feature = "layout-detection")]
    pub all_table_models: bool,
    #[cfg(feature = "tree-sitter")]
    pub all_grammars: bool,
    #[cfg(feature = "tree-sitter")]
    pub grammar_groups: Option<Vec<String>>,
    #[cfg(feature = "tree-sitter")]
    pub grammars: Option<Vec<String>>,
    #[cfg(feature = "ner-onnx")]
    pub ner: bool,
    #[cfg(feature = "ner-onnx")]
    pub ner_model: Option<String>,
    #[cfg(feature = "ner-onnx")]
    pub all_ner_models: bool,
}

/// Resolve the Hugging Face cache label shown in the warm summary: `Some` only when at
/// least one requested model source actually reads the HF cache (paddle-ocr always does;
/// embeddings/ner-onnx depend on what was requested).
#[cfg(any(feature = "embeddings", feature = "ner-onnx", feature = "paddle-ocr"))]
fn resolve_hf_cache_label(
    hf_cache_dir: &Option<PathBuf>,
    #[cfg_attr(not(any(feature = "embeddings", feature = "ner-onnx")), allow(unused_variables))] options: &WarmOptions,
) -> Option<String> {
    let uses_hf_cache = cfg!(feature = "paddle-ocr")
        || {
            #[cfg(feature = "embeddings")]
            {
                options.all_embeddings || options.embedding_model.is_some()
            }
            #[cfg(not(feature = "embeddings"))]
            {
                false
            }
        }
        || {
            #[cfg(feature = "ner-onnx")]
            {
                options.ner || options.ner_model.is_some() || options.all_ner_models
            }
            #[cfg(not(feature = "ner-onnx"))]
            {
                false
            }
        };
    uses_hf_cache.then(|| {
        hf_cache_dir
            .as_ref()
            .map(|path| path.display().to_string())
            .unwrap_or_else(|| "HF_HUB_CACHE/HF_HOME/platform default".to_string())
    })
}

/// Download (or confirm already cached) the PaddleOCR v2 model set.
#[cfg(feature = "paddle-ocr")]
fn warm_paddle_ocr_models(hf_cache_dir: Option<PathBuf>, downloaded: &mut Vec<String>) -> Result<()> {
    let manager = hf_cache_dir
        .map(xberg::paddle_ocr::ModelManager::new)
        .unwrap_or_default();

    manager
        .ensure_all_models()
        .context("Failed to download PaddleOCR v2 models")?;
    downloaded.push("paddle-ocr v2 (server+mobile det, cls, doc_ori, unified+per-script rec)".to_string());
    Ok(())
}

/// Download (or confirm already cached) the formula-recognition model set.
#[cfg(feature = "formula-recognition")]
fn warm_formula_recognition(
    cache_base: &Path,
    downloaded: &mut Vec<String>,
    already_cached: &mut Vec<String>,
) -> Result<()> {
    let formula_dir = cache_base.join("formula-recognition");
    if xberg::formula_recognition::models_cached_in(Some(&formula_dir)) {
        already_cached.push("formula-recognition (latex_ocr)".to_string());
    } else {
        xberg::formula_recognition::ensure_models_in(Some(&formula_dir))
            .map_err(|e| anyhow::anyhow!(e))
            .context("Failed to download formula recognition models")?;
        downloaded.push("formula-recognition (latex_ocr)".to_string());
    }
    Ok(())
}

/// Download (or confirm already cached) the layout-detection model set.
#[cfg(feature = "layout-detection")]
fn warm_layout_detection(
    cache_base: &Path,
    all_table_models: bool,
    downloaded: &mut Vec<String>,
    already_cached: &mut Vec<String>,
) -> Result<()> {
    let layout_dir = cache_base.join("layout");
    let manager = xberg::layout::LayoutModelManager::new(Some(layout_dir));

    if all_table_models {
        let was_cached = manager.is_rtdetr_cached() && manager.is_tatr_cached();
        if was_cached {
            already_cached.push("layout (rtdetr, tatr, slanet variants)".to_string());
        } else {
            manager
                .ensure_all_models()
                .context("Failed to download layout models")?;
            downloaded.push("layout (rtdetr, tatr, slanet variants)".to_string());
        }
    } else {
        let was_cached = manager.is_rtdetr_cached() && manager.is_tatr_cached();
        if was_cached {
            already_cached.push("layout (rtdetr, tatr)".to_string());
        } else {
            manager
                .ensure_default_models()
                .context("Failed to download layout models")?;
            downloaded.push("layout (rtdetr, tatr)".to_string());
        }
    }
    Ok(())
}

/// Download (or confirm already cached) the Tesseract language data files.
#[cfg(feature = "paddle-ocr")]
fn warm_tessdata(cache_base: &Path, downloaded: &mut Vec<String>, already_cached: &mut Vec<String>) -> Result<()> {
    let tessdata_dir = cache_base.join("tessdata");
    let manager = xberg::ocr::TessdataManager::new(Some(tessdata_dir));

    let newly_downloaded = manager
        .ensure_all_languages()
        .context("Failed to download tessdata files")?;

    if newly_downloaded > 0 {
        downloaded.push(format!("tessdata ({newly_downloaded} languages)"));
    } else {
        already_cached.push("tessdata (all languages)".to_string());
    }
    Ok(())
}

/// Download the requested embedding model preset(s).
#[cfg(feature = "embeddings")]
fn warm_embeddings(
    all_embeddings: bool,
    embedding_model: Option<String>,
    hf_cache_dir: Option<PathBuf>,
    downloaded: &mut Vec<String>,
) -> Result<()> {
    let presets_to_warm: Vec<xberg::EmbeddingPreset> = if all_embeddings {
        xberg::list_embedding_presets()
            .into_iter()
            .filter_map(|name| xberg::get_embedding_preset(&name))
            .collect()
    } else if let Some(ref name) = embedding_model {
        match xberg::get_embedding_preset(name) {
            Some(preset) => vec![preset],
            None => {
                let available = xberg::list_embedding_presets();
                anyhow::bail!(
                    "Unknown embedding preset '{}'. Available: {}",
                    name,
                    available.join(", ")
                );
            }
        }
    } else {
        vec![]
    };

    for preset in &presets_to_warm {
        let label = format!("embedding ({})", preset.name);
        xberg::embeddings::warm_model(
            &xberg::core::config::EmbeddingModelType::Preset {
                name: preset.name.clone(),
            },
            hf_cache_dir.clone(),
        )
        .map_err(|e| anyhow::anyhow!("Failed to download embedding model '{}': {}", preset.name, e))?;
        downloaded.push(label);
    }
    Ok(())
}

/// Download the requested tree-sitter grammar(s).
#[cfg(feature = "tree-sitter")]
fn warm_tree_sitter_grammars(
    all_grammars: bool,
    grammar_groups: Option<Vec<String>>,
    grammars: Option<Vec<String>>,
    downloaded: &mut Vec<String>,
    already_cached: &mut Vec<String>,
) -> Result<()> {
    if all_grammars {
        let count = tree_sitter_language_pack::download_all().context("Failed to download all tree-sitter grammars")?;
        if count > 0 {
            downloaded.push(format!("tree-sitter grammars ({count} languages)"));
        } else {
            already_cached.push("tree-sitter grammars (all)".to_string());
        }
    } else if let Some(ref groups) = grammar_groups {
        let config = tree_sitter_language_pack::PackConfig {
            cache_dir: None,
            languages: None,
            groups: Some(groups.clone()),
        };
        tree_sitter_language_pack::init(&config).context("Failed to download tree-sitter grammar groups")?;
        downloaded.push(format!("tree-sitter grammars (groups: {})", groups.join(", ")));
    } else if let Some(ref langs) = grammars {
        let refs: Vec<&str> = langs.iter().map(String::as_str).collect();
        let count = tree_sitter_language_pack::download(&refs).context("Failed to download tree-sitter grammars")?;
        if count > 0 {
            downloaded.push(format!("tree-sitter grammars ({count} languages)"));
        } else {
            already_cached.push(format!("tree-sitter grammars ({})", langs.join(", ")));
        }
    }
    Ok(())
}

/// Download the requested GLiNER NER model(s).
#[cfg(feature = "ner-onnx")]
fn warm_ner_models(
    ner: bool,
    ner_model: Option<String>,
    all_ner_models: bool,
    hf_cache_dir: Option<PathBuf>,
    downloaded: &mut Vec<String>,
) -> Result<()> {
    let ner_models: Vec<String> = ner_model.into_iter().collect();
    if ner || !ner_models.is_empty() || all_ner_models {
        let to_download = crate::commands::ner::select_models(ner, ner_models, all_ner_models)?;
        downloaded.extend(
            crate::commands::ner::download_models(&to_download, hf_cache_dir)
                .context("Failed to download GLiNER NER models")?
                .into_iter()
                .map(|entry| format!("ner gliner ({entry})")),
        );
    }
    Ok(())
}

/// Print the warm command's summary in the requested wire format.
#[cfg(any(
    feature = "embeddings",
    feature = "layout-detection",
    feature = "paddle-ocr",
    feature = "tree-sitter",
    feature = "ner-onnx"
))]
#[expect(
    clippy::print_stdout,
    reason = "cache warm download summary is the command's stdout result output"
)]
fn print_warm_summary(
    format: WireFormat,
    cache_base: &Path,
    hf_cache_label: &Option<String>,
    downloaded: &[String],
    already_cached: &[String],
) -> Result<()> {
    match format {
        WireFormat::Text => {
            if !downloaded.is_empty() {
                println!("{}", style::label("Downloaded:"));
                for d in downloaded {
                    println!("  {}", style::success(d));
                }
            }
            if !already_cached.is_empty() {
                println!("{}", style::label("Already cached:"));
                for c in already_cached {
                    println!("  {}", style::dim(c));
                }
            }
            println!(
                "Xberg-managed cache: {}",
                style::success(&cache_base.display().to_string())
            );
            if let Some(hf_cache) = hf_cache_label {
                println!("Hugging Face cache: {}", style::success(hf_cache));
            }
        }
        WireFormat::Json => {
            let output = json!({
                "cache_dir": cache_base.to_string_lossy(),
                "xberg_cache_dir": cache_base.to_string_lossy(),
                "hugging_face_cache_dir": hf_cache_label,
                "downloaded": downloaded,
                "already_cached": already_cached,
            });
            println!(
                "{}",
                serde_json::to_string_pretty(&output).context("Failed to serialize warm results to JSON")?
            );
        }
        WireFormat::Toon => {
            let output = json!({
                "cache_dir": cache_base.to_string_lossy(),
                "xberg_cache_dir": cache_base.to_string_lossy(),
                "hugging_face_cache_dir": hf_cache_label,
                "downloaded": downloaded,
                "already_cached": already_cached,
            });
            println!(
                "{}",
                serde_toon::to_string(&output).context("Failed to serialize warm results to TOON")?
            );
        }
    }

    Ok(())
}

/// Execute cache warm command - eagerly downloads all models.
#[cfg(any(
    feature = "embeddings",
    feature = "layout-detection",
    feature = "paddle-ocr",
    feature = "tree-sitter",
    feature = "ner-onnx"
))]
pub fn warm_command(cache_dir: Option<PathBuf>, format: WireFormat, options: WarmOptions) -> Result<()> {
    #[cfg(any(feature = "embeddings", feature = "ner-onnx", feature = "paddle-ocr"))]
    let hf_cache_dir = cache_dir.clone();
    #[cfg(any(feature = "embeddings", feature = "ner-onnx", feature = "paddle-ocr"))]
    let hf_cache_label = resolve_hf_cache_label(&hf_cache_dir, &options);
    #[cfg(not(any(feature = "embeddings", feature = "ner-onnx", feature = "paddle-ocr")))]
    let hf_cache_label: Option<String> = None;
    let cache_base = resolve_cache_base(cache_dir);

    let mut downloaded: Vec<String> = Vec::new();
    #[cfg(any(
        feature = "paddle-ocr",
        feature = "layout-detection",
        feature = "tree-sitter",
        feature = "formula-recognition"
    ))]
    let mut already_cached: Vec<String> = Vec::new();
    #[cfg(not(any(
        feature = "paddle-ocr",
        feature = "layout-detection",
        feature = "tree-sitter",
        feature = "formula-recognition"
    )))]
    let already_cached: Vec<String> = Vec::new();

    #[cfg(feature = "paddle-ocr")]
    warm_paddle_ocr_models(hf_cache_dir.clone(), &mut downloaded)?;

    #[cfg(feature = "formula-recognition")]
    warm_formula_recognition(&cache_base, &mut downloaded, &mut already_cached)?;

    #[cfg(feature = "layout-detection")]
    warm_layout_detection(
        &cache_base,
        options.all_table_models,
        &mut downloaded,
        &mut already_cached,
    )?;

    #[cfg(feature = "paddle-ocr")]
    warm_tessdata(&cache_base, &mut downloaded, &mut already_cached)?;

    #[cfg(feature = "embeddings")]
    warm_embeddings(
        options.all_embeddings,
        options.embedding_model.clone(),
        hf_cache_dir.clone(),
        &mut downloaded,
    )?;

    #[cfg(feature = "tree-sitter")]
    warm_tree_sitter_grammars(
        options.all_grammars,
        options.grammar_groups.clone(),
        options.grammars.clone(),
        &mut downloaded,
        &mut already_cached,
    )?;

    #[cfg(feature = "ner-onnx")]
    warm_ner_models(
        options.ner,
        options.ner_model.clone(),
        options.all_ner_models,
        hf_cache_dir.clone(),
        &mut downloaded,
    )?;

    print_warm_summary(format, &cache_base, &hf_cache_label, &downloaded, &already_cached)
}

/// Resolve the cache base directory.
#[cfg(any(
    feature = "embeddings",
    feature = "layout-detection",
    feature = "paddle-ocr",
    feature = "tree-sitter",
    feature = "ner-onnx"
))]
fn resolve_cache_base(cache_dir: Option<PathBuf>) -> PathBuf {
    if let Some(dir) = cache_dir {
        return dir;
    }
    if let Ok(env_path) = std::env::var("XBERG_CACHE_DIR") {
        return PathBuf::from(env_path);
    }
    std::env::current_dir()
        .unwrap_or_else(|_| PathBuf::from("."))
        .join(".xberg")
}