apr-cli 0.64.0

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

/// The complete stdout of `apr rm`, in whichever mode was asked for.
///
/// `None` means "write nothing to stdout": the not-found case under `--json`.
/// That keeps the convention the already-correct JSON commands use
/// (`apr validate --json`, `apr stamp --json`) — on failure the diagnostic goes
/// to stderr and the exit code carries the outcome, so a consumer that parses
/// stdout only ever sees a whole JSON document or nothing at all.
// serde_json::json!() uses infallible unwrap internally
#[allow(clippy::disallowed_methods)]
pub(crate) fn remove_stdout(model_ref: &str, removed: bool, json: bool) -> Option<String> {
    if json {
        if !removed {
            return None;
        }
        let doc = serde_json::json!({
            "model": model_ref,
            "removed": true,
        });
        return Some(serde_json::to_string_pretty(&doc).unwrap_or_default());
    }

    let outcome = if removed {
        format!("{} Model removed from cache", "".green())
    } else {
        format!("{} Model not found in cache", "".yellow())
    };
    Some(format!(
        "{}\n\nModel: {}\n{}",
        "=== APR Remove ===".cyan().bold(),
        model_ref.cyan(),
        outcome
    ))
}

/// Remove a model from cache
pub fn remove(model_ref: &str, json: bool) -> Result<()> {
    let mut fetcher = ModelFetcher::new().map_err(|e| {
        CliError::ValidationFailed(format!("Failed to initialize model fetcher: {e}"))
    })?;

    let removed = fetcher
        .remove(model_ref)
        .map_err(|e| CliError::ValidationFailed(format!("Failed to remove model: {e}")))?;


    if removed {
        if let Some(out) = remove_stdout(model_ref, true, json) {
            println!("{out}");
        }
        return Ok(());
    }

    // RM-NS-001: the pacha manifest is not the cache. `apr pull`'s streaming
    // path, `apr convert` and plain file copies all write straight into the
    // cache directory, so a manifest lookup misses almost everything `apr list`
    // prints — every name it showed was rejected here. Resolve against the same
    // enumeration `apr list` uses before giving up.
    //
    // The path is folded into the single `remove_stdout` call rather than
    // printed separately: under `--json` a stray `Path: ...` line would sit
    // outside the JSON document and break every consumer parsing stdout.
    if let Some(path) = remove_from_cache_dir(fetcher.cache_dir(), model_ref)? {
        if let Some(out) = remove_stdout(model_ref, true, json) {
            println!("{out}");
            if !json {
                println!("  Path: {}", path.display());
            }
        }
        return Ok(());
    }

    // GH-601: rm of nonexistent model must exit non-zero (like unix rm).
    if let Some(out) = remove_stdout(model_ref, false, json) {
        println!("{out}");
    }
    Err(CliError::FileNotFound(std::path::PathBuf::from(model_ref)))
}

/// RM-NS-001: `blake3(uri)[..16]` — the stem `apr pull` gives a cached file
/// (`build_single_cache_path`), so `apr rm hf://org/repo/model.gguf` can find
/// what `apr pull hf://org/repo/model.gguf` wrote.
fn cache_stem_for_ref(model_ref: &str) -> String {
    let hash = blake3::hash(model_ref.as_bytes()).to_hex().to_string();
    hash[..16].to_string()
}

/// RM-NS-001: does `model_ref` name this cached model file?
///
/// Accepts every form the user can plausibly have in hand: the identifier
/// `apr list` prints (the file stem), the file name, a path to the file, and
/// the `hf://` reference that was pulled.
fn cache_entry_matches_ref(entry: &DiskModelEntry, model_ref: &str) -> bool {
    if model_ref.is_empty() {
        return false;
    }
    if entry.name == model_ref {
        return true;
    }
    if entry.path.file_name().and_then(|s| s.to_str()) == Some(model_ref) {
        return true;
    }
    let as_path = std::path::Path::new(model_ref);
    if as_path == entry.path {
        return true;
    }
    if let (Ok(given), Ok(cached)) = (as_path.canonicalize(), entry.path.canonicalize()) {
        if given == cached {
            return true;
        }
    }
    entry.name == cache_stem_for_ref(model_ref)
        || entry.name == cache_stem_for_ref(&normalize_hf_uri(model_ref))
}

/// RM-NS-001: resolve `model_ref` against the cache directory `apr list` enumerates.
///
/// Returns every matching model file so the caller can refuse an ambiguous
/// reference rather than delete an arbitrary one.
fn resolve_cached_model_files(cache_dir: &Path, model_ref: &str) -> Vec<std::path::PathBuf> {
    scan_cache_dir(cache_dir)
        .into_iter()
        .filter(|entry| cache_entry_matches_ref(entry, model_ref))
        .map(|entry| entry.path)
        .collect()
}

/// RM-NS-001: delete the cached model file named by `model_ref`.
///
/// `Ok(None)` means nothing in the cache directory answers to that name — the
/// caller turns that into GH-601's non-zero "not found". An ambiguous reference
/// (same stem, several formats) is an error and deletes nothing.
fn remove_from_cache_dir(cache_dir: &Path, model_ref: &str) -> Result<Option<std::path::PathBuf>> {
    let mut matches = resolve_cached_model_files(cache_dir, model_ref);
    match matches.len() {
        0 => Ok(None),
        1 => {
            let path = matches.remove(0);
            std::fs::remove_file(&path).map_err(|e| {
                CliError::ValidationFailed(format!("Failed to remove {}: {e}", path.display()))
            })?;
            Ok(Some(path))
        }
        _ => {
            matches.sort();
            let candidates = matches
                .iter()
                .map(|p| format!("  {}", p.display()))
                .collect::<Vec<_>>()
                .join("\n");
            Err(CliError::ValidationFailed(format!(
                "'{model_ref}' matches {} cached models — pass the file name to pick one:\n{candidates}",
                matches.len()
            )))
        }
    }
}

/// Resolve a model reference to a local path (for run/serve commands)
/// Downloads if not cached and auto_pull is enabled
#[allow(dead_code)]
pub fn resolve_model_path(model_ref: &str) -> Result<std::path::PathBuf> {
    contract_pre_model_path_resolution!();
    // If it's already a local file path, use it directly
    let path = std::path::Path::new(model_ref);
    if path.exists() && path.is_file() {
        return Ok(path.to_path_buf());
    }

    // Try to resolve via pacha
    let mut fetcher = ModelFetcher::with_config(FetchConfig::default()).map_err(|e| {
        CliError::ValidationFailed(format!("Failed to initialize model fetcher: {e}"))
    })?;

    // Pull (uses cache if available)
    let result = fetcher
        .pull(model_ref, |progress| {
            if progress.total_bytes > 0 {
                let pct = progress.percent();
                eprint!(
                    "\rPulling model... [{:30}] {:5.1}%",
                    "=".repeat((pct / 3.33) as usize),
                    pct
                );
                io::stderr().flush().ok();
            }
        })
        .map_err(|e| {
            // Not a pacha model ref, check if file exists
            CliError::ValidationFailed(format!(
                "Model '{}' not found. Not a local file and could not resolve via registry: {}",
                model_ref, e
            ))
        })?;

    if !result.cache_hit {
        eprintln!(); // Newline after progress
    }

    contract_post_model_path_resolution!(&());
    Ok(result.path)
}

/// Format bytes to human-readable string
fn format_bytes(bytes: u64) -> String {
    batuta_common::fmt::format_bytes(bytes)
}

/// GH-198 + GAP-UX-002: Download companion files (tokenizer.json, config.json) for SafeTensors models.
///
/// SafeTensors format stores weights only — unlike GGUF which embeds tokenizer and config.
/// The realizar inference engine expects these as sibling files.
///
/// GAP-UX-002: Store companions with model hash prefix to prevent cross-model conflicts.
/// Example: `d71534cb.safetensors` → `d71534cb.config.json`, `d71534cb.tokenizer.json`
fn fetch_safetensors_companions(model_path: &Path, resolved_uri: &str) -> Result<()> {
    // Extract HF repo from resolved URI: "hf://org/repo/file.safetensors" → "org/repo"
    let Some(repo_id) = extract_hf_repo(resolved_uri) else {
        // Not an HF URI — can't fetch companions (local file or unknown source)
        return Ok(());
    };

    // GAP-UX-002: Extract model stem (hash) for prefixing companion files
    // Model: d71534cb948e32eb.safetensors → stem: d71534cb948e32eb
    let model_stem = model_path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("model");

    // GH-356: tokenizer.json is optional — some models only have tokenizer.model (SentencePiece)
    let companions = [
        "tokenizer.json",
        "config.json",
        "tokenizer_config.json",
        "tokenizer.model",
    ];
    let cache_dir = model_path
        .parent()
        .ok_or_else(|| CliError::ValidationFailed("Model path has no parent directory".into()))?;

    for filename in &companions {
        // GAP-UX-002: Use hash-prefixed filename (e.g., "d71534cb.config.json")
        let prefixed_filename = format!("{model_stem}.{filename}");
        let sibling_path = cache_dir.join(&prefixed_filename);

        if sibling_path.exists() {
            println!(
                "  {} {} (already exists)",
                "".green(),
                prefixed_filename.dimmed()
            );
            continue;
        }

        let url = format!(
            "https://huggingface.co/{}/resolve/main/{}",
            repo_id, filename
        );

        // GH-355: Use hf_get() for auth — ureq::get() bypassed gated model tokens
        match hf_get(&url)?.call() {
            Ok(response) => {
                let mut body = Vec::new();
                response.into_reader().read_to_end(&mut body).map_err(|e| {
                    CliError::NetworkError(format!("Failed to read {filename}: {e}"))
                })?;
                std::fs::write(&sibling_path, &body).map_err(|e| {
                    CliError::ValidationFailed(format!(
                        "Failed to write {}: {e}",
                        sibling_path.display()
                    ))
                })?;
                println!(
                    "  {} {} ({})",
                    "".green(),
                    prefixed_filename,
                    format_bytes(body.len() as u64).dimmed()
                );
            }
            Err(ureq::Error::Status(404, _)) => {
                // File doesn't exist in repo — not fatal for any companion
                println!(
                    "  {} {} (not found in repo)",
                    "".yellow(),
                    prefixed_filename.dimmed()
                );
            }
            Err(ureq::Error::Status(401, _)) => {
                eprintln!(
                    "  {} {} (access denied — set HF_TOKEN for gated models)",
                    "".yellow(),
                    prefixed_filename,
                );
            }
            Err(e) => {
                // Network error — warn but don't block the pull
                eprintln!(
                    "  {} Failed to download {}: {}",
                    "".yellow(),
                    prefixed_filename,
                    e
                );
            }
        }
    }

    // GH-356: Post-condition — at least one tokenizer file must exist.
    // Same contract as download_companion_files (sharded path). Without this,
    // inference fails late with a cryptic "tokenizer not found" instead of failing fast here.
    let tokenizer_prefixes = ["tokenizer.json", "tokenizer.model", "tokenizer_config.json"];
    let has_tokenizer = tokenizer_prefixes
        .iter()
        .any(|f| cache_dir.join(format!("{model_stem}.{f}")).exists());
    if !has_tokenizer {
        return Err(CliError::ValidationFailed(format!(
            "No tokenizer found for this model. Tried: {}.\n\
             The model may require a custom tokenizer not hosted in the repository.",
            tokenizer_prefixes.join(", ")
        )));
    }

    Ok(())
}

/// GH-352: Print a hint about format conversion instead of doing it eagerly.
///
/// Previously (GH-211), this function ran `apr_import()` + `apr_export()` to produce
/// sibling `.apr` and `.gguf` files. This loaded the ENTIRE model into memory — twice —
/// causing 55+ GB RSS for large models like Qwen3-30B-A3B.
///
/// Root cause (five-whys): pull should download only. Conversion is `apr convert`'s job.
/// The realizar inference engine reads SafeTensors directly — no conversion needed to run.
fn convert_safetensors_formats(safetensors_path: &Path) -> Result<()> {
    let apr_path = safetensors_path.with_extension("apr");
    let gguf_path = safetensors_path.with_extension("gguf");

    // If both already exist (from a previous pull), just note it
    if apr_path.exists() && gguf_path.exists() {
        println!();
        println!(
            "  {} APR and GGUF formats available",
            "".green(),
        );
        return Ok(());
    }

    // GH-352: Hint instead of eagerly converting (which loads entire model into RAM)
    println!();
    println!(
        "  {} To convert formats, run:",
        "".cyan(),
    );
    if !apr_path.exists() {
        println!(
            "    apr convert {} --format apr",
            safetensors_path.display()
        );
    }
    if !gguf_path.exists() {
        println!(
            "    apr convert {} --format gguf",
            safetensors_path.display()
        );
    }

    Ok(())
}

/// Extract HuggingFace repo ID from a resolved URI.
///
/// Examples:
///   "hf://Qwen/Qwen2.5-Coder-0.5B-Instruct/model.safetensors" → Some("Qwen/Qwen2.5-Coder-0.5B-Instruct")
///   "hf://Qwen/Qwen2.5-Coder-0.5B-Instruct" → Some("Qwen/Qwen2.5-Coder-0.5B-Instruct")
///   "/local/path/model.safetensors" → None
fn extract_hf_repo(uri: &str) -> Option<String> {
    let path = uri.strip_prefix("hf://")?;
    let parts: Vec<&str> = path.split('/').collect();
    if parts.len() >= 2 {
        Some(format!("{}/{}", parts[0], parts[1]))
    } else {
        None
    }
}

/// PMAT-108 + GH-213: Resolve HuggingFace model reference to a downloadable target.
///
/// Returns `SingleFile` for:
/// - Non-HF URIs (local paths, URLs)
/// - URIs with explicit file extension (`.gguf`, `.safetensors`, etc.)
/// - Repos with a single `model.safetensors`
/// - GGUF repos (auto-detects best quantization)
///
/// Returns `Sharded` for:
/// - Repos with `model.safetensors.index.json` (sharded SafeTensors, typically 3B+ models)
///
/// Priority for GGUF auto-detection: Q4_K_M > Q4_K_S > Q4_0 > Q8_0 > any
/// GH-213: Normalize bare "org/repo" to "hf://org/repo".
fn normalize_hf_uri(uri: &str) -> String {
    if !uri.contains("://") && !uri.starts_with('/') && !uri.starts_with('.') {
        let parts: Vec<&str> = uri.split('/').collect();
        if parts.len() >= 2 && !parts[0].is_empty() && !parts[1].is_empty() {
            return format!("hf://{uri}");
        }
    }
    uri.to_string()
}

/// Select best GGUF file by quantization priority (Q4_K_M > Q4_K_S > Q4_0 > Q8_0 > first).
fn select_best_gguf(gguf_files: &[&str], org: &str, repo: &str) -> ResolvedModel {
    let quantization_priority = ["q4_k_m", "q4_k_s", "q4_0", "q8_0"];
    for quant in quantization_priority {
        let matches: Vec<_> = gguf_files.iter().filter(|f| f.to_lowercase().contains(quant)).collect();
        if matches.len() == 1 {
            return ResolvedModel::SingleFile(format!("hf://{org}/{repo}/{}", matches[0]));
        } else if matches.len() > 1 {
            // For now, if there are multiple parts (sharded GGUF), just pick the first one 
            // (Note: full sharded GGUF support in `apr pull` might require more work, but this avoids random picking).
            // Usually the first shard contains metadata, but it's not a full model.
            // A better fix for sharded GGUF is to download all parts, but pacha single-file streaming doesn't support that yet.
            // We will just pick the first part so it doesn't crash on `find`.
            if let Some(first_part) = matches.iter().find(|f| f.contains("-00001-of-")) {
                return ResolvedModel::SingleFile(format!("hf://{org}/{repo}/{}", first_part));
            }
            return ResolvedModel::SingleFile(format!("hf://{org}/{repo}/{}", matches[0]));
        }
    }
    ResolvedModel::SingleFile(format!("hf://{org}/{repo}/{}", gguf_files[0]))
}

/// Download and parse sharded SafeTensors index, returning shard filenames.
fn resolve_sharded_safetensors(org: &str, repo: &str) -> Result<ResolvedModel> {
    let index_url =
        format!("https://huggingface.co/{org}/{repo}/resolve/main/model.safetensors.index.json");
    let index_response = hf_get(&index_url)?
        .call()
        .map_err(|e| CliError::NetworkError(format!("Failed to download model index: {e}")))?;

    let mut index_body = Vec::new();
    index_response
        .into_reader()
        .read_to_end(&mut index_body)
        .map_err(|e| CliError::NetworkError(format!("Failed to read model index: {e}")))?;

    let index_json = String::from_utf8_lossy(&index_body);
    let shard_files = extract_shard_files_from_index(&index_json);

    if shard_files.is_empty() {
        return Err(CliError::ValidationFailed(format!(
            "Sharded model index for {org}/{repo} contains no shard files"
        )));
    }

    Ok(ResolvedModel::Sharded {
        org: org.to_string(),
        repo: repo.to_string(),
        shard_files,
    })
}

/// Find a SafeTensors file in the repo file list, returning it as a resolved model.
fn find_safetensors_file(filenames: &[&str], org: &str, repo: &str) -> Option<ResolvedModel> {
    if filenames
        .iter()
        .any(|f| f.to_lowercase() == "model.safetensors")
    {
        return Some(ResolvedModel::SingleFile(format!(
            "hf://{org}/{repo}/model.safetensors"
        )));
    }
    filenames
        .iter()
        .find(|f| f.to_lowercase().ends_with(".safetensors"))
        .map(|file| ResolvedModel::SingleFile(format!("hf://{org}/{repo}/{file}")))
}

/// Check if a URI already has a known model file extension.
fn has_known_model_extension(uri: &str) -> bool {
    std::path::Path::new(uri).extension().is_some_and(|ext| {
        ext.eq_ignore_ascii_case("gguf")
            || ext.eq_ignore_ascii_case("safetensors")
            || ext.eq_ignore_ascii_case("apr")
            || ext.eq_ignore_ascii_case("pt")
    })
}

pub(crate) fn resolve_hf_model(uri: &str) -> Result<ResolvedModel> {
    let uri = normalize_hf_uri(uri);
    let uri = uri.as_str();

    if !uri.starts_with("hf://") {
        return Ok(ResolvedModel::SingleFile(uri.to_string()));
    }

    if has_known_model_extension(uri) {
        return Ok(ResolvedModel::SingleFile(uri.to_string()));
    }

    let path = uri.strip_prefix("hf://").unwrap_or(uri);
    let parts: Vec<&str> = path.split('/').collect();

    if parts.len() < 2 {
        return Err(CliError::ValidationFailed(format!(
            "Invalid HuggingFace URI: {uri}. Expected hf://org/repo or hf://org/repo/file.gguf"
        )));
    }

    let org = parts[0];
    let repo = parts[1];

    let api_url = format!("https://huggingface.co/api/models/{org}/{repo}");
    let response = hf_get(&api_url)?.call().map_err(|e| match &e {
        ureq::Error::Status(401, _) => {
            CliError::NetworkError(format_gated_model_error(&api_url))
        }
        _ => CliError::NetworkError(format!("Failed to query HuggingFace API: {e}")),
    })?;

    let body: serde_json::Value = {
        let text = response.into_string().map_err(|e| {
            CliError::ValidationFailed(format!("Failed to read HuggingFace response: {e}"))
        })?;
        serde_json::from_str(&text).map_err(|e| {
            CliError::ValidationFailed(format!("Failed to parse HuggingFace response: {e}"))
        })?
    };

    let siblings = body["siblings"]
        .as_array()
        .ok_or_else(|| CliError::ValidationFailed("No files found in repository".to_string()))?;

    let filenames: Vec<&str> = siblings
        .iter()
        .filter_map(|s| s["rfilename"].as_str())
        .collect();

    let gguf_files: Vec<&str> = filenames
        .iter()
        .copied()
        .filter(|f| f.to_lowercase().ends_with(".gguf"))
        .collect();

    if !gguf_files.is_empty() {
        // #1893: a complete sharded-GGUF set (`model-NNNNN-of-MMMMM.gguf`, no
        // index.json) must download ALL parts — not a single `select_best_gguf`
        // pick, which would silently grab one part and produce a broken model.
        if let Some(shard_files) = detect_gguf_shards(&gguf_files) {
            return Ok(ResolvedModel::Sharded {
                org: org.to_string(),
                repo: repo.to_string(),
                shard_files,
            });
        }
        return Ok(select_best_gguf(&gguf_files, org, repo));
    }

    if filenames.contains(&"model.safetensors.index.json") {
        return resolve_sharded_safetensors(org, repo);
    }

    if let Some(model) = find_safetensors_file(&filenames, org, repo) {
        return Ok(model);
    }

    resolve_hf_model_fallback(&filenames, org, repo)
}

/// GH-357: Handle repos with no GGUF/SafeTensors — detect PyTorch-only repos.
fn resolve_hf_model_fallback(filenames: &[&str], org: &str, repo: &str) -> Result<ResolvedModel> {
    let has_bin_files = filenames
        .iter()
        .any(|f| f.to_lowercase().ends_with(".bin"));
    if has_bin_files {
        return Err(CliError::ValidationFailed(format!(
            "{org}/{repo} only has PyTorch .bin weights (no SafeTensors or GGUF).\n\
             Convert first with:\n  \
             python -c \"from transformers import AutoModelForCausalLM; \
             m = AutoModelForCausalLM.from_pretrained('{org}/{repo}'); \
             m.save_pretrained('{repo}-st', safe_serialization=True)\"\n\
             Or request SafeTensors on the model page."
        )));
    }

    Err(CliError::ValidationFailed(format!(
        "No .gguf or .safetensors files found in {org}/{repo}"
    )))
}

/// #1893: Parse a sharded-GGUF filename `<prefix>-NNNNN-of-MMMMM.gguf` into
/// `(prefix_lowercased, part_no, total)`. Returns `None` for any name that
/// isn't a shard part (single-file GGUF, multi-quant repos, etc.).
///
/// The `.gguf` suffix and prefix are matched case-insensitively for grouping;
/// the caller keeps the original-case filename for download.
fn parse_gguf_shard_name(name: &str) -> Option<(String, u32, u32)> {
    let lower = name.to_lowercase();
    let stem = lower.strip_suffix(".gguf")?;
    // "<prefix>-NNNNN" + "-of-" + "MMMMM"
    let (prefix_and_part, total_str) = stem.rsplit_once("-of-")?;
    let total: u32 = total_str.parse().ok()?;
    let (prefix, part_str) = prefix_and_part.rsplit_once('-')?;
    let part: u32 = part_str.parse().ok()?;
    Some((prefix.to_string(), part, total))
}

/// #1893: Detect a COMPLETE sharded-GGUF set among a repo's `.gguf` files.
///
/// Modern 7B+ GGUFs ship split as `<prefix>-NNNNN-of-MMMMM.gguf` (zero-padded,
/// 1-indexed) with NO `index.json` (unlike sharded SafeTensors). Returns the
/// part filenames sorted by part number IFF a single prefix has a complete set
/// (`total >= 2` and all parts `1..=total` present). Returns `None` for a
/// single-file GGUF, unrelated multi-quant GGUFs, or an incomplete set — so the
/// caller falls back to single-file selection (`select_best_gguf`).
fn detect_gguf_shards(gguf_files: &[&str]) -> Option<Vec<String>> {
    use std::collections::BTreeMap;
    // (prefix, total) -> { part_no -> original_filename }
    let mut groups: BTreeMap<(String, u32), BTreeMap<u32, String>> = BTreeMap::new();
    for &f in gguf_files {
        if let Some((prefix, part, total)) = parse_gguf_shard_name(f) {
            groups
                .entry((prefix, total))
                .or_default()
                .insert(part, f.to_string());
        }
    }
    for ((_, total), parts) in groups {
        if total >= 2 && parts.len() as u32 == total && (1..=total).all(|n| parts.contains_key(&n)) {
            // BTreeMap iterates by ascending part number → correctly ordered.
            return Some(parts.into_values().collect());
        }
    }
    None
}

/// GH-213: Extract unique shard filenames from index.json weight_map, sorted for deterministic order.
///
/// Format: `{"metadata": {...}, "weight_map": {"tensor.name": "model-00001-of-00006.safetensors", ...}}`
/// Find the content of a brace-delimited section, handling nesting.
fn find_brace_content(text: &str) -> Option<&str> {
    let start = text.find('{')?;
    let content = &text[start + 1..];
    let mut depth = 1usize;
    for (i, c) in content.char_indices() {
        match c {
            '{' => depth += 1,
            '}' if depth == 1 => return Some(&content[..i]),
            '}' => depth -= 1,
            _ => {}
        }
    }
    None
}

/// RM-NS-001: `apr rm` must be able to remove what `apr list` prints.
///
/// Every test here drives `remove_from_cache_dir` against a throwaway cache
/// directory and asserts on the FILE — present or gone — not on a return shape.
#[cfg(test)]
mod rm_list_namespace_tests {
    use super::{cache_stem_for_ref, remove_from_cache_dir, resolve_cached_model_files};
    use std::path::{Path, PathBuf};

    fn temp_cache(tag: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "apr-rm-ns-{}-{}-{:?}",
            tag,
            std::process::id(),
            std::thread::current().id()
        ));
        std::fs::remove_dir_all(&dir).ok();
        std::fs::create_dir_all(&dir).expect("mkdir temp cache");
        dir
    }

    fn touch(dir: &Path, name: &str) -> PathBuf {
        let path = dir.join(name);
        std::fs::write(&path, b"not-a-real-model").expect("write fixture");
        path
    }

    /// FT-RMNS-001: the identifier `apr list` prints (the file stem) removes the
    /// file. This is the exact repro: `apr list` showed `064a3693fa1ea02c` and
    /// `apr rm 064a3693fa1ea02c` left it on disk.
    #[test]
    fn removes_by_the_name_list_prints() {
        let dir = temp_cache("stem");
        let model = touch(&dir, "064a3693fa1ea02c.safetensors");

        let removed = remove_from_cache_dir(&dir, "064a3693fa1ea02c").expect("no error");

        assert_eq!(removed.as_deref(), Some(model.as_path()));
        assert!(
            !model.exists(),
            "FT-RMNS-001: the model file must be gone after rm, found it still at {}",
            model.display()
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    /// FT-RMNS-002: the file name and an absolute path also remove the file.
    #[test]
    fn removes_by_filename_and_by_absolute_path() {
        let dir = temp_cache("forms");
        let by_name = touch(&dir, "aaaaaaaaaaaaaaaa.gguf");
        remove_from_cache_dir(&dir, "aaaaaaaaaaaaaaaa.gguf").expect("no error");
        assert!(!by_name.exists(), "FT-RMNS-002: file name form must delete");

        let by_path = touch(&dir, "bbbbbbbbbbbbbbbb.apr");
        let arg = by_path.display().to_string();
        remove_from_cache_dir(&dir, &arg).expect("no error");
        assert!(!by_path.exists(), "FT-RMNS-002: path form must delete");

        std::fs::remove_dir_all(&dir).ok();
    }

    /// FT-RMNS-003: the `hf://` reference that was pulled removes the file
    /// `apr pull` wrote for it (pull names it `blake3(uri)[..16]`).
    #[test]
    fn removes_by_the_hf_reference_that_was_pulled() {
        let dir = temp_cache("hfref");
        let uri = "hf://Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf";
        let model = touch(&dir, &format!("{}.gguf", cache_stem_for_ref(uri)));

        remove_from_cache_dir(&dir, uri).expect("no error");

        assert!(
            !model.exists(),
            "FT-RMNS-003: rm of the pulled hf:// ref must delete {}",
            model.display()
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    /// FT-RMNS-004 (GH-601 preserved): a genuine miss removes nothing and
    /// reports nothing removed, so the caller still exits non-zero.
    #[test]
    fn unknown_reference_removes_nothing() {
        let dir = temp_cache("miss");
        let other = touch(&dir, "cccccccccccccccc.gguf");

        let removed = remove_from_cache_dir(&dir, "definitely-not-a-model").expect("no error");

        assert!(
            removed.is_none(),
            "FT-RMNS-004: an unknown ref must not report a removal"
        );
        assert!(
            other.exists(),
            "FT-RMNS-004: an unknown ref must not delete an unrelated model"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    /// FT-RMNS-005: an ambiguous stem (same model cached in two formats) is
    /// refused and deletes NEITHER file — rm must never guess.
    #[test]
    fn ambiguous_stem_deletes_nothing() {
        let dir = temp_cache("ambig");
        let st = touch(&dir, "dddddddddddddddd.safetensors");
        let apr = touch(&dir, "dddddddddddddddd.apr");

        let err = remove_from_cache_dir(&dir, "dddddddddddddddd")
            .expect_err("FT-RMNS-005: ambiguous ref must be an error");
        assert!(
            format!("{err}").contains("matches 2 cached models"),
            "FT-RMNS-005: error must name the ambiguity, got: {err}"
        );
        assert!(st.exists() && apr.exists(), "FT-RMNS-005: nothing deleted");

        std::fs::remove_dir_all(&dir).ok();
    }

    /// FT-RMNS-006: non-model files in the cache dir (manifest, companion
    /// sidecars) are not removable through `apr rm` — it only ever deletes what
    /// `apr list` enumerates.
    #[test]
    fn non_model_files_are_not_removable() {
        let dir = temp_cache("sidecar");
        let manifest = touch(&dir, "manifest.json");
        let companion = touch(&dir, "eeeeeeeeeeeeeeee.config.json");

        assert!(resolve_cached_model_files(&dir, "manifest.json").is_empty());
        assert!(remove_from_cache_dir(&dir, "manifest.json")
            .expect("no error")
            .is_none());
        assert!(remove_from_cache_dir(&dir, "eeeeeeeeeeeeeeee.config.json")
            .expect("no error")
            .is_none());
        assert!(
            manifest.exists() && companion.exists(),
            "FT-RMNS-006: rm must not touch non-model files"
        );
        std::fs::remove_dir_all(&dir).ok();
    }
}

#[cfg(test)]
mod sharded_gguf_tests {
    use super::{detect_gguf_shards, parse_gguf_shard_name};

    // ===== #1893: sharded-GGUF detection (contract sharded-gguf-pull-v1) =====

    /// FT-SHGGUF-001: a complete 2-part set is detected and returned in part order.
    #[test]
    fn detects_complete_two_part_set() {
        let files = ["m-00002-of-00002.gguf", "m-00001-of-00002.gguf"];
        let got = detect_gguf_shards(&files).expect("complete set must be detected");
        assert_eq!(
            got,
            vec!["m-00001-of-00002.gguf".to_string(), "m-00002-of-00002.gguf".to_string()],
            "FT-SHGGUF-001: parts returned sorted by part number regardless of input order"
        );
    }

    /// FT-SHGGUF-002: a complete 3-part set with a realistic prefix.
    #[test]
    fn detects_three_part_with_quant_prefix() {
        let files = [
            "Qwen2.5-7B-Instruct-Q4_K_M-00001-of-00003.gguf",
            "Qwen2.5-7B-Instruct-Q4_K_M-00002-of-00003.gguf",
            "Qwen2.5-7B-Instruct-Q4_K_M-00003-of-00003.gguf",
        ];
        let got = detect_gguf_shards(&files).expect("3-part set");
        assert_eq!(got.len(), 3);
        assert_eq!(got[0], "Qwen2.5-7B-Instruct-Q4_K_M-00001-of-00003.gguf");
    }

    /// FT-SHGGUF-003: a single non-sharded GGUF is NOT treated as sharded
    /// (caller falls back to select_best_gguf).
    #[test]
    fn single_file_is_not_sharded() {
        assert_eq!(detect_gguf_shards(&["model.gguf"]), None);
        assert_eq!(detect_gguf_shards(&["qwen2.5-coder-1.5b-q4_k_m.gguf"]), None);
    }

    /// FT-SHGGUF-004: unrelated multi-quant GGUFs (not a shard set) → None.
    #[test]
    fn multi_quant_not_sharded() {
        let files = ["model-Q4_K_M.gguf", "model-Q8_0.gguf", "model-f16.gguf"];
        assert_eq!(detect_gguf_shards(&files), None);
    }

    /// FT-SHGGUF-005: an INCOMPLETE set (missing a part) → None, so we never
    /// claim a model is downloadable when a part is absent.
    #[test]
    fn incomplete_set_rejected() {
        let files = ["m-00001-of-00003.gguf", "m-00002-of-00003.gguf"]; // missing 00003
        assert_eq!(detect_gguf_shards(&files), None);
    }

    /// FT-SHGGUF-006: filename parser handles case + rejects non-shard names.
    #[test]
    fn parser_edge_cases() {
        assert_eq!(
            parse_gguf_shard_name("M-00001-OF-00004.GGUF"),
            Some(("m".to_string(), 1, 4))
        );
        assert_eq!(parse_gguf_shard_name("model.gguf"), None);
        assert_eq!(parse_gguf_shard_name("foo-bar.gguf"), None);
        assert_eq!(parse_gguf_shard_name("model.safetensors"), None);
    }
}