memvid_cli/commands/
inspection.rs

1//! Inspection command handlers (view, stats, who)
2
3#[cfg(feature = "audio-playback")]
4use std::io::Cursor;
5use std::io::{self, Write};
6use std::path::{Path, PathBuf};
7use std::process::Command;
8#[cfg(feature = "audio-playback")]
9use std::time::Duration;
10
11use anyhow::{anyhow, bail, Context, Result};
12use clap::Args;
13use memvid_core::table::list_tables;
14use memvid_core::{
15    lockfile, normalize_text, Frame, FrameRole, MediaManifest, Memvid, TextChunkManifest,
16    TextChunkRange,
17};
18use serde_json::{json, Value};
19use tempfile::Builder;
20use tracing::warn;
21use uuid::Uuid;
22use hex;
23
24use crate::config::CliConfig;
25use crate::utils::{
26    format_bytes, format_percent, format_timestamp_ms, frame_status_str, open_read_only_mem,
27    owner_hint_to_json, parse_timecode, round_percent, select_frame, yes_no,
28};
29
30const DEFAULT_VIEW_PAGE_CHARS: usize = 1_200;
31const CHUNK_MANIFEST_KEY: &str = "memvid_chunks_v1";
32
33/// Arguments for the `view` subcommand
34#[derive(Args)]
35pub struct ViewArgs {
36    #[arg(value_name = "FILE", value_parser = clap::value_parser!(PathBuf))]
37    pub file: PathBuf,
38    #[arg(long = "frame-id", value_name = "ID", conflicts_with = "uri")]
39    pub frame_id: Option<u64>,
40    #[arg(long, value_name = "URI", conflicts_with = "frame_id")]
41    pub uri: Option<String>,
42    #[arg(long)]
43    pub json: bool,
44    #[arg(long, conflicts_with = "json")]
45    pub binary: bool,
46    #[arg(long, conflicts_with_all = ["json", "binary"])]
47    pub preview: bool,
48    /// Optional start time for video previews (HH:MM:SS[.mmm])
49    #[arg(
50        long = "start",
51        value_name = "HH:MM:SS",
52        requires = "preview",
53        conflicts_with_all = ["json", "binary", "play"]
54    )]
55    pub preview_start: Option<String>,
56    /// Optional end time for video previews (HH:MM:SS[.mmm])
57    #[arg(
58        long = "end",
59        value_name = "HH:MM:SS",
60        requires = "preview",
61        conflicts_with_all = ["json", "binary", "play"]
62    )]
63    pub preview_end: Option<String>,
64    #[arg(long = "play", conflicts_with_all = ["json", "binary", "preview"])]
65    pub play: bool,
66    #[arg(long = "start-seconds", requires = "play")]
67    pub start_seconds: Option<f32>,
68    #[arg(long = "end-seconds", requires = "play")]
69    pub end_seconds: Option<f32>,
70    #[arg(long, value_name = "N", default_value_t = 1)]
71    pub page: usize,
72    #[arg(long = "page-size", value_name = "CHARS")]
73    pub page_size: Option<usize>,
74}
75
76/// Arguments for the `stats` subcommand
77#[derive(Args)]
78pub struct StatsArgs {
79    #[arg(value_name = "FILE", value_parser = clap::value_parser!(PathBuf))]
80    pub file: PathBuf,
81    #[arg(long)]
82    pub json: bool,
83    /// Replay: Show stats for frames with ID <= AS_OF_FRAME (time-travel view)
84    #[arg(long = "as-of-frame", value_name = "FRAME_ID")]
85    pub as_of_frame: Option<u64>,
86    /// Replay: Show stats for frames with timestamp <= AS_OF_TS (time-travel view)
87    #[arg(long = "as-of-ts", value_name = "UNIX_TIMESTAMP")]
88    pub as_of_ts: Option<i64>,
89}
90
91/// Arguments for the `who` subcommand
92#[derive(Args)]
93pub struct WhoArgs {
94    #[arg(value_name = "FILE", value_parser = clap::value_parser!(PathBuf))]
95    pub file: PathBuf,
96    #[arg(long)]
97    pub json: bool,
98}
99
100/// Handler for `memvid stats`
101pub fn handle_stats(_config: &CliConfig, args: StatsArgs) -> Result<()> {
102    let mut mem = Memvid::open_read_only(&args.file)?;
103    let stats = mem.stats()?;
104    let tables = list_tables(&mut mem).unwrap_or_default();
105    let vec_dimension = mem.effective_vec_index_dimension()?;
106    let embedding_identity = mem.embedding_identity_summary(10_000);
107
108    // Note: Replay filtering for stats is currently not implemented
109    // The stats show the full memory state
110    if args.as_of_frame.is_some() || args.as_of_ts.is_some() {
111        eprintln!("Note: Replay filtering (--as-of-frame/--as-of-ts) shows current stats.");
112        eprintln!("      Use 'find' or 'timeline' commands for filtered results.");
113    }
114    let overhead_bytes = stats.size_bytes.saturating_sub(stats.payload_bytes);
115    let payload_share_percent: f64 = if stats.size_bytes > 0 {
116        round_percent((stats.payload_bytes as f64 / stats.size_bytes as f64) * 100.0)
117    } else {
118        0.0
119    };
120    let overhead_share_percent: f64 = if stats.size_bytes > 0 {
121        round_percent((100.0 - payload_share_percent).max(0.0))
122    } else {
123        0.0
124    };
125    let maintenance_command = format!(
126        "memvid doctor {} --vacuum --rebuild-time-index --rebuild-lex-index",
127        args.file.display()
128    );
129
130    if args.json {
131        let mut raw_json = serde_json::to_value(&stats)?;
132        if let Value::Object(ref mut obj) = raw_json {
133            obj.remove("tier");
134        }
135
136        // Build tables list for JSON output
137        let tables_json: Vec<serde_json::Value> = tables
138            .iter()
139            .map(|t| {
140                json!({
141                    "table_id": t.table_id,
142                    "source_file": t.source_file,
143                    "n_rows": t.n_rows,
144                    "n_cols": t.n_cols,
145                    "pages": format!("{}-{}", t.page_start, t.page_end),
146                    "quality": format!("{:?}", t.quality),
147                    "headers": t.headers,
148                })
149            })
150            .collect();
151
152        // Compute embedding quality for JSON output
153        let embedding_quality_json = if stats.has_vec_index {
154            mem.embedding_quality().ok().flatten().map(|eq| {
155                json!({
156                    "vector_count": eq.vector_count,
157                    "dimension": eq.dimension,
158                    "avg_similarity": eq.avg_similarity,
159                    "min_similarity": eq.min_similarity,
160                    "max_similarity": eq.max_similarity,
161                    "std_similarity": eq.std_similarity,
162                    "clustering_coefficient": eq.clustering_coefficient,
163                    "estimated_clusters": eq.estimated_clusters,
164                    "recommended_threshold": eq.recommended_threshold,
165                    "quality_rating": eq.quality_rating,
166                    "quality_explanation": eq.quality_explanation,
167                })
168            })
169        } else {
170            None
171        };
172
173        let embedding_identity_json = match &embedding_identity {
174            memvid_core::EmbeddingIdentitySummary::Unknown => Value::Null,
175            memvid_core::EmbeddingIdentitySummary::Single(identity) => json!({
176                "provider": identity.provider.as_deref(),
177                "model": identity.model.as_deref(),
178                "dimension": identity.dimension.or(vec_dimension),
179                "normalized": identity.normalized,
180            }),
181            memvid_core::EmbeddingIdentitySummary::Mixed(identities) => {
182                let values: Vec<Value> = identities
183                    .iter()
184                    .map(|entry| {
185                        json!({
186                            "provider": entry.identity.provider.as_deref(),
187                            "model": entry.identity.model.as_deref(),
188                            "dimension": entry.identity.dimension.or(vec_dimension),
189                            "normalized": entry.identity.normalized,
190                            "count": entry.count,
191                        })
192                    })
193                    .collect();
194                json!({ "mixed": values })
195            }
196        };
197
198        // Get enrichment stats for JSON output
199        let enrichment_stats = mem.enrichment_stats();
200        let enrichment_json = json!({
201            "total_frames": enrichment_stats.total_frames,
202            "enriched_frames": enrichment_stats.enriched_frames,
203            "pending_frames": enrichment_stats.pending_frames,
204            "searchable_only": enrichment_stats.searchable_only,
205        });
206
207        // Get ticket info for JSON output
208        let ticket = mem.current_ticket();
209        let ticket_json = json!({
210            "issuer": ticket.issuer,
211            "seq_no": ticket.seq_no,
212            "expires_in_secs": ticket.expires_in_secs,
213            "capacity_bytes": ticket.capacity_bytes,
214            "verified": ticket.verified,
215        });
216
217        let report = json!({
218            "summary": {
219                "sequence": stats.seq_no,
220                "frames": format!("{} total ({} active)", stats.frame_count, stats.active_frame_count),
221                "usage": format!(
222                    "{} used / {} total ({})",
223                    format_bytes(stats.size_bytes),
224                    format_bytes(stats.capacity_bytes),
225                    format_percent(stats.storage_utilisation_percent)
226                ),
227                "remaining": format!("{} free", format_bytes(stats.remaining_capacity_bytes)),
228            },
229            "storage": {
230                "payload": format!("{} ({})", format_bytes(stats.payload_bytes), format_percent(payload_share_percent)),
231                "overhead": format!("{} ({}) - WAL + indexes", format_bytes(overhead_bytes), format_percent(overhead_share_percent)),
232                "logical_payload": format!("{} before compression", format_bytes(stats.logical_bytes)),
233                "compression_savings": format!("{} saved ({})", format_bytes(stats.saved_bytes), format_percent(stats.savings_percent)),
234                "compression_ratio": format_percent(stats.compression_ratio_percent),
235            },
236            "frames": {
237                "average_stored": format_bytes(stats.average_frame_payload_bytes),
238                "average_logical": format_bytes(stats.average_frame_logical_bytes),
239                "clip_images": stats.clip_image_count,
240            },
241            "indexes": {
242                "lexical": yes_no(stats.has_lex_index),
243                "vector": yes_no(stats.has_vec_index),
244                "time": yes_no(stats.has_time_index),
245            },
246            "enrichment": enrichment_json,
247            "ticket": ticket_json,
248            "embedding_identity": embedding_identity_json,
249            "embedding_quality": embedding_quality_json,
250            "tables": {
251                "count": tables.len(),
252                "tables": tables_json,
253            },
254            "maintenance": maintenance_command,
255            "raw": raw_json,
256        });
257
258        println!("{}", serde_json::to_string_pretty(&report)?);
259    } else {
260        let seq_display = stats
261            .seq_no
262            .map(|seq| seq.to_string())
263            .unwrap_or_else(|| "n/a".to_string());
264
265        println!("Memory: {}", args.file.display());
266        println!("Sequence: {}", seq_display);
267        println!(
268            "Frames: {} total ({} active)",
269            stats.frame_count, stats.active_frame_count
270        );
271
272        println!("\nCapacity:");
273        println!(
274            "  Usage: {} used / {} total ({})",
275            format_bytes(stats.size_bytes),
276            format_bytes(stats.capacity_bytes),
277            format_percent(stats.storage_utilisation_percent)
278        );
279        println!(
280            "  Remaining: {}",
281            format_bytes(stats.remaining_capacity_bytes)
282        );
283
284        // Show ticket verification status
285        let ticket = mem.current_ticket();
286        if ticket.seq_no > 0 {
287            let verified_str = if ticket.verified { "✓ verified" } else { "⚠ unverified" };
288            println!(
289                "  Ticket: seq={} issuer={} ({})",
290                ticket.seq_no, ticket.issuer, verified_str
291            );
292        }
293
294        println!("\nStorage breakdown:");
295        println!(
296            "  Payload: {} ({})",
297            format_bytes(stats.payload_bytes),
298            format_percent(payload_share_percent)
299        );
300        println!(
301            "  Overhead: {} ({})",
302            format_bytes(overhead_bytes),
303            format_percent(overhead_share_percent)
304        );
305        // PHASE 2: Detailed overhead breakdown for observability
306        println!("    ├─ WAL: {}", format_bytes(stats.wal_bytes));
307        println!(
308            "    ├─ Lexical index: {}",
309            format_bytes(stats.lex_index_bytes)
310        );
311        println!(
312            "    ├─ Vector index: {}",
313            format_bytes(stats.vec_index_bytes)
314        );
315        println!(
316            "    └─ Time index: {}",
317            format_bytes(stats.time_index_bytes)
318        );
319        println!(
320            "  Logical payload: {} before compression",
321            format_bytes(stats.logical_bytes)
322        );
323
324        if stats.has_vec_index {
325            println!("\nEmbeddings:");
326            if let Some(dim) = vec_dimension {
327                println!("  Dimension: {}", dim);
328            }
329            match &embedding_identity {
330                memvid_core::EmbeddingIdentitySummary::Unknown => {
331                    println!("  Model: unknown (no persisted embedding identity)");
332                }
333                memvid_core::EmbeddingIdentitySummary::Single(identity) => {
334                    if let Some(provider) = identity.provider.as_deref() {
335                        println!("  Provider: {}", provider);
336                    }
337                    if let Some(model) = identity.model.as_deref() {
338                        println!("  Model: {}", model);
339                    }
340                }
341                memvid_core::EmbeddingIdentitySummary::Mixed(identities) => {
342                    println!("  Model: mixed ({} identities detected)", identities.len());
343                    for entry in identities.iter().take(5) {
344                        let provider = entry.identity.provider.as_deref().unwrap_or("unknown");
345                        let model = entry.identity.model.as_deref().unwrap_or("unknown");
346                        println!("    - {} / {} ({} frames)", provider, model, entry.count);
347                    }
348                    if identities.len() > 5 {
349                        println!("    - ...");
350                    }
351                }
352            }
353        }
354        println!(
355            "  Compression savings: {} ({})",
356            format_bytes(stats.saved_bytes),
357            format_percent(stats.savings_percent)
358        );
359
360        println!("\nAverage frame:");
361        println!(
362            "  Stored: {}   Logical: {}",
363            format_bytes(stats.average_frame_payload_bytes),
364            format_bytes(stats.average_frame_logical_bytes)
365        );
366        if stats.clip_image_count > 0 {
367            println!("  CLIP images: {}", stats.clip_image_count);
368        }
369
370        // PHASE 2: Per-document cost analysis
371        if stats.active_frame_count > 0 {
372            let overhead_per_doc = overhead_bytes / stats.active_frame_count;
373            let lex_per_doc = stats.lex_index_bytes / stats.active_frame_count;
374            let vec_per_doc = stats.vec_index_bytes / stats.active_frame_count;
375
376            println!("\nPer-document overhead:");
377            println!("  Total: {}", format_bytes(overhead_per_doc));
378            if stats.has_lex_index {
379                println!("  Lexical: {}", format_bytes(lex_per_doc));
380            }
381            if stats.has_vec_index {
382                let vec_ratio = if stats.average_frame_payload_bytes > 0 {
383                    vec_per_doc as f64 / stats.average_frame_payload_bytes as f64
384                } else {
385                    0.0
386                };
387                println!(
388                    "  Vector: {} ({:.0}x text size)",
389                    format_bytes(vec_per_doc),
390                    vec_ratio
391                );
392            }
393        }
394
395        println!("\nIndexes:");
396        println!(
397            "  Lexical: {}   Vector: {}   Time: {}",
398            yes_no(stats.has_lex_index),
399            yes_no(stats.has_vec_index),
400            yes_no(stats.has_time_index)
401        );
402
403        // Show enrichment queue stats
404        let enrichment_stats = mem.enrichment_stats();
405        if enrichment_stats.pending_frames > 0 || enrichment_stats.searchable_only > 0 {
406            println!("\nEnrichment:");
407            println!(
408                "  Enriched: {} / {}",
409                enrichment_stats.enriched_frames, enrichment_stats.total_frames
410            );
411            if enrichment_stats.pending_frames > 0 {
412                println!("  Pending: {} frames", enrichment_stats.pending_frames);
413                println!(
414                    "  Run `memvid process-queue {}` to complete enrichment",
415                    args.file.display()
416                );
417            }
418        }
419
420        // Show embedding quality stats if vector index is available
421        if stats.has_vec_index {
422            if let Ok(Some(eq)) = mem.embedding_quality() {
423                println!("\nEmbedding Quality:");
424                println!(
425                    "  Vectors: {}   Dimension: {}",
426                    eq.vector_count, eq.dimension
427                );
428                println!(
429                    "  Similarity: avg={:.3}  min={:.3}  max={:.3}  std={:.3}",
430                    eq.avg_similarity, eq.min_similarity, eq.max_similarity, eq.std_similarity
431                );
432                println!(
433                    "  Clusters: ~{}   Quality: {}",
434                    eq.estimated_clusters, eq.quality_rating
435                );
436                println!(
437                    "  Recommended --min-relevancy: {:.1}",
438                    eq.recommended_threshold
439                );
440                println!("  {}", eq.quality_explanation);
441            }
442        }
443
444        if !tables.is_empty() {
445            println!("\nTables: {} extracted", tables.len());
446            for t in &tables {
447                println!(
448                    "  {} — {} rows × {} cols ({})",
449                    t.table_id, t.n_rows, t.n_cols, t.source_file
450                );
451            }
452        }
453
454        println!("\nMaintenance:");
455        println!(
456            "  Run `{}` to rebuild indexes and reclaim space.",
457            maintenance_command
458        );
459    }
460    Ok(())
461}
462
463/// Handler for `memvid who`
464pub fn handle_who(args: WhoArgs) -> Result<()> {
465    match lockfile::current_owner(&args.file)? {
466        Some(owner) => {
467            if args.json {
468                let output = json!({
469                    "locked": true,
470                    "owner": owner_hint_to_json(&owner),
471                });
472                println!("{}", serde_json::to_string_pretty(&output)?);
473            } else {
474                println!("{} is locked by:", args.file.display());
475                if let Some(pid) = owner.pid {
476                    println!("  pid: {pid}");
477                }
478                if let Some(cmd) = owner.cmd.as_deref() {
479                    println!("  cmd: {cmd}");
480                }
481                if let Some(started) = owner.started_at.as_deref() {
482                    println!("  started_at: {started}");
483                }
484                if let Some(last) = owner.last_heartbeat.as_deref() {
485                    println!("  last_heartbeat: {last}");
486                }
487                if let Some(interval) = owner.heartbeat_ms {
488                    println!("  heartbeat_interval_ms: {interval}");
489                }
490                if let Some(file_id) = owner.file_id.as_deref() {
491                    println!("  file_id: {file_id}");
492                }
493                if let Some(path) = owner.file_path.as_ref() {
494                    println!("  file_path: {}", path.display());
495                }
496            }
497        }
498        None => {
499            if args.json {
500                let output = json!({"locked": false});
501                println!("{}", serde_json::to_string_pretty(&output)?);
502            } else {
503                println!("No active writer for {}", args.file.display());
504            }
505        }
506    }
507    Ok(())
508}
509
510// ============================================================================
511// View command handler and helpers
512// ============================================================================
513
514/// Handler for `memvid view`
515pub fn handle_view(args: ViewArgs) -> Result<()> {
516    if args.page == 0 {
517        bail!("page must be greater than zero");
518    }
519    if let Some(size) = args.page_size {
520        if size == 0 {
521            bail!("page-size must be greater than zero");
522        }
523    }
524
525    let mut mem = open_read_only_mem(&args.file)?;
526    let frame = select_frame(&mut mem, args.frame_id, args.uri.as_deref())?;
527
528    if args.play {
529        #[cfg(feature = "audio-playback")]
530        {
531            play_frame_audio(&mut mem, &frame, args.start_seconds, args.end_seconds)?;
532            return Ok(());
533        }
534        #[cfg(not(feature = "audio-playback"))]
535        {
536            bail!("Audio playback requires the 'audio-playback' feature (only available on macOS)");
537        }
538    }
539
540    if args.preview {
541        let bounds = parse_preview_bounds(args.preview_start.as_ref(), args.preview_end.as_ref())?;
542        preview_frame_media(&mut mem, &frame, args.uri.as_deref(), bounds)?;
543        return Ok(());
544    }
545
546    if args.binary {
547        let bytes = mem.frame_canonical_payload(frame.id)?;
548        let mut stdout = io::stdout();
549        stdout.write_all(&bytes)?;
550        stdout.flush()?;
551        return Ok(());
552    }
553
554    let canonical_text = canonical_text_for_view(&mut mem, &frame)?;
555    let manifest_from_meta = canonical_manifest_from_frame(&canonical_text, &frame);
556
557    let page_size = args
558        .page_size
559        .or_else(|| manifest_from_meta.as_ref().map(|m| m.chunk_chars))
560        .unwrap_or(DEFAULT_VIEW_PAGE_CHARS);
561
562    let mut manifest = if args.page_size.is_none() {
563        manifest_from_meta.unwrap_or_else(|| compute_chunk_manifest(&canonical_text, page_size))
564    } else {
565        compute_chunk_manifest(&canonical_text, page_size)
566    };
567    if manifest.chunks.is_empty() {
568        manifest = TextChunkManifest {
569            chunk_chars: page_size,
570            chunks: vec![TextChunkRange {
571                start: 0,
572                end: canonical_text.chars().count(),
573            }],
574        };
575    }
576
577    if frame.role == FrameRole::DocumentChunk && args.page_size.is_none() {
578        let total_chars = canonical_text.chars().count();
579        manifest = TextChunkManifest {
580            chunk_chars: total_chars.max(1),
581            chunks: vec![TextChunkRange {
582                start: 0,
583                end: total_chars,
584            }],
585        };
586    }
587
588    let total_pages = manifest.chunks.len().max(1);
589    if args.page > total_pages {
590        bail!(
591            "page {} is out of range (total pages: {})",
592            args.page,
593            total_pages
594        );
595    }
596
597    let chunk = &manifest.chunks[args.page - 1];
598    let content = extract_chunk_slice(&canonical_text, chunk);
599
600    if args.json {
601        let mut frame_json = frame_to_json(&frame);
602        if let Some(obj) = frame_json.as_object_mut() {
603            // Note: Do NOT overwrite search_text - it contains the extracted text from the document.
604            // The "content" field shows the paginated payload view.
605            if let Some(manifest_json) = obj.get_mut("chunk_manifest") {
606                if let Some(manifest_obj) = manifest_json.as_object_mut() {
607                    let total = manifest.chunks.len();
608                    if total > 0 {
609                        let mut window = serde_json::Map::new();
610                        let idx = args.page.saturating_sub(1).min(total - 1);
611                        if idx > 0 {
612                            let prev = &manifest.chunks[idx - 1];
613                            window.insert("prev".into(), json!([prev.start, prev.end]));
614                        }
615                        let current = &manifest.chunks[idx];
616                        window.insert("current".into(), json!([current.start, current.end]));
617                        if idx + 1 < total {
618                            let next = &manifest.chunks[idx + 1];
619                            window.insert("next".into(), json!([next.start, next.end]));
620                        }
621                        manifest_obj.insert("chunks".into(), Value::Object(window));
622                    }
623                }
624            }
625        }
626        let json = json!({
627            "frame": frame_json,
628            "page": args.page,
629            "page_size": manifest.chunk_chars,
630            "page_count": total_pages,
631            "has_prev": args.page > 1,
632            "has_next": args.page < total_pages,
633            "content": content,
634        });
635        println!("{}", serde_json::to_string_pretty(&json)?);
636    } else {
637        print_frame_summary(&mut mem, &frame)?;
638        println!(
639            "Page {}/{} ({} chars per page)",
640            args.page, total_pages, manifest.chunk_chars
641        );
642        println!();
643        println!("{}", content);
644    }
645    Ok(())
646}
647
648#[derive(Debug)]
649pub struct PreviewBounds {
650    pub start_ms: Option<u64>,
651    pub end_ms: Option<u64>,
652}
653
654pub fn parse_preview_bounds(
655    start: Option<&String>,
656    end: Option<&String>,
657) -> Result<Option<PreviewBounds>> {
658    let start_ms = match start {
659        Some(value) => Some(parse_timecode(value)?),
660        None => None,
661    };
662    let end_ms = match end {
663        Some(value) => Some(parse_timecode(value)?),
664        None => None,
665    };
666
667    if let (Some(s), Some(e)) = (start_ms, end_ms) {
668        if e <= s {
669            anyhow::bail!("--end must be greater than --start");
670        }
671    }
672
673    if start_ms.is_none() && end_ms.is_none() {
674        Ok(None)
675    } else {
676        Ok(Some(PreviewBounds { start_ms, end_ms }))
677    }
678}
679
680fn preview_frame_media(
681    mem: &mut Memvid,
682    frame: &Frame,
683    cli_uri: Option<&str>,
684    bounds: Option<PreviewBounds>,
685) -> Result<()> {
686    let manifest = mem.media_manifest(frame.id)?;
687    let mut mime = manifest
688        .as_ref()
689        .map(|m| m.mime.clone())
690        .or_else(|| frame.metadata.as_ref().and_then(|meta| meta.mime.clone()))
691        .unwrap_or_else(|| "application/octet-stream".to_string());
692
693    // If mime is generic, try to detect from payload bytes
694    if mime == "application/octet-stream" {
695        if let Ok(bytes) = mem.frame_canonical_payload(frame.id) {
696            if let Some(kind) = infer::get(&bytes) {
697                mime = kind.mime_type().to_string();
698            }
699        }
700    }
701
702    let is_video = manifest
703        .as_ref()
704        .map(|media| media.kind.eq_ignore_ascii_case("video"))
705        .unwrap_or_else(|| mime.starts_with("video/"));
706
707    if is_video {
708        preview_frame_video(mem, frame, cli_uri, bounds, manifest, &mime)?;
709    } else {
710        if bounds.is_some() {
711            anyhow::bail!("--start/--end are only supported for video previews");
712        }
713        if is_image_mime(&mime) {
714            preview_frame_image(mem, frame, cli_uri)?;
715        } else if is_audio_mime(&mime) {
716            preview_frame_audio_file(mem, frame, cli_uri, manifest.as_ref(), &mime)?;
717        } else {
718            preview_frame_document(mem, frame, cli_uri, manifest.as_ref(), &mime)?;
719        }
720    }
721    Ok(())
722}
723
724fn preview_frame_video(
725    mem: &mut Memvid,
726    frame: &Frame,
727    cli_uri: Option<&str>,
728    bounds: Option<PreviewBounds>,
729    manifest: Option<MediaManifest>,
730    mime: &str,
731) -> Result<()> {
732    let extension = manifest
733        .as_ref()
734        .and_then(|m| m.filename.as_deref())
735        .and_then(|name| Path::new(name).extension().and_then(|ext| ext.to_str()))
736        .map(|ext| ext.trim_start_matches('.').to_ascii_lowercase())
737        .or_else(|| extension_from_mime(mime).map(|ext| ext.to_string()))
738        .unwrap_or_else(|| "mp4".to_string());
739
740    let mut temp_file = Builder::new()
741        .prefix("memvid-preview-")
742        .suffix(&format!(".{extension}"))
743        .tempfile_in(std::env::temp_dir())
744        .context("failed to create temporary preview file")?;
745
746    let mut reader = mem
747        .blob_reader(frame.id)
748        .context("failed to stream payload for preview")?;
749    io::copy(&mut reader, &mut temp_file).context("failed to write video data to preview file")?;
750    temp_file
751        .flush()
752        .context("failed to flush video preview to disk")?;
753
754    let (file, preview_path) = temp_file.keep().context("failed to persist preview file")?;
755    drop(file);
756
757    let mut display_path = preview_path.clone();
758    if let Some(ref span) = bounds {
759        let needs_trim = span.start_ms.is_some() || span.end_ms.is_some();
760        if needs_trim {
761            if let Some(trimmed) = maybe_trim_with_ffmpeg(&preview_path, &extension, span)? {
762                display_path = trimmed;
763            }
764        }
765    }
766
767    println!("Opening preview...");
768    open::that(&display_path).with_context(|| {
769        format!(
770            "failed to launch default video player for {}",
771            display_path.display()
772        )
773    })?;
774
775    let display_uri = cli_uri
776        .or_else(|| frame.uri.as_deref())
777        .unwrap_or("<unknown>");
778    println!(
779        "Opened preview for {} (frame {}) -> {} ({})",
780        display_uri,
781        frame.id,
782        display_path.display(),
783        mime
784    );
785    Ok(())
786}
787
788fn maybe_trim_with_ffmpeg(
789    source: &Path,
790    extension: &str,
791    bounds: &PreviewBounds,
792) -> Result<Option<PathBuf>> {
793    if bounds.start_ms.is_none() && bounds.end_ms.is_none() {
794        return Ok(None);
795    }
796
797    let ffmpeg = match which::which("ffmpeg") {
798        Ok(path) => path,
799        Err(_) => {
800            warn!("ffmpeg binary not found on PATH; opening full video");
801            return Ok(None);
802        }
803    };
804
805    let target = std::env::temp_dir().join(format!(
806        "memvid-preview-clip-{}.{}",
807        Uuid::new_v4(),
808        extension
809    ));
810
811    let mut command = Command::new(ffmpeg);
812    command.arg("-y");
813    if let Some(start) = bounds.start_ms {
814        command.arg("-ss").arg(format_timestamp_ms(start));
815    }
816    command.arg("-i").arg(source);
817    if let Some(end) = bounds.end_ms {
818        command.arg("-to").arg(format_timestamp_ms(end));
819    }
820    command.arg("-c").arg("copy");
821    command.arg(&target);
822
823    let status = command
824        .status()
825        .context("failed to run ffmpeg for preview trimming")?;
826    if status.success() {
827        return Ok(Some(target));
828    }
829
830    let details = status
831        .code()
832        .map(|code| code.to_string())
833        .unwrap_or_else(|| "terminated".to_string());
834    warn!("ffmpeg exited with status {details}; opening full video");
835    Ok(None)
836}
837
838fn preview_frame_image(mem: &mut Memvid, frame: &Frame, cli_uri: Option<&str>) -> Result<()> {
839    let bytes = mem
840        .frame_canonical_payload(frame.id)
841        .context("failed to load canonical payload for frame")?;
842    if bytes.is_empty() {
843        bail!("frame payload is empty; nothing to preview");
844    }
845
846    let detected_kind = infer::get(&bytes);
847    let mut mime = frame
848        .metadata
849        .as_ref()
850        .and_then(|meta| meta.mime.clone())
851        .filter(|value| is_image_mime(value));
852
853    if mime.is_none() {
854        if let Some(kind) = &detected_kind {
855            let candidate = kind.mime_type();
856            if is_image_mime(candidate) {
857                mime = Some(candidate.to_string());
858            }
859        }
860    }
861
862    let mime = mime.ok_or_else(|| anyhow!("frame does not contain an image payload"))?;
863    if !is_image_mime(&mime) {
864        bail!("frame mime type {mime} is not an image");
865    }
866
867    let extension = detected_kind
868        .as_ref()
869        .map(|kind| kind.extension().to_string())
870        .or_else(|| extension_from_mime(&mime).map(|ext| ext.to_string()))
871        .unwrap_or_else(|| "img".to_string());
872
873    let suffix = format!(".{extension}");
874    let mut temp_file = Builder::new()
875        .prefix("memvid-preview-")
876        .suffix(&suffix)
877        .tempfile_in(std::env::temp_dir())
878        .context("failed to create temporary preview file")?;
879    temp_file
880        .write_all(&bytes)
881        .context("failed to write image data to preview file")?;
882    temp_file
883        .flush()
884        .context("failed to flush preview file to disk")?;
885
886    let (file, preview_path) = temp_file.keep().context("failed to persist preview file")?;
887    drop(file);
888
889    println!("Opening preview...");
890    open::that(&preview_path).with_context(|| {
891        format!(
892            "failed to launch default image viewer for {}",
893            preview_path.display()
894        )
895    })?;
896
897    let display_uri = cli_uri
898        .or_else(|| frame.uri.as_deref())
899        .unwrap_or("<unknown>");
900    println!(
901        "Opened preview for {} (frame {}) -> {} ({})",
902        display_uri,
903        frame.id,
904        preview_path.display(),
905        mime
906    );
907    Ok(())
908}
909
910fn preview_frame_document(
911    mem: &mut Memvid,
912    frame: &Frame,
913    cli_uri: Option<&str>,
914    manifest: Option<&MediaManifest>,
915    mime: &str,
916) -> Result<()> {
917    let display_uri = cli_uri
918        .or_else(|| frame.uri.as_deref())
919        .unwrap_or("<unknown>");
920
921    // For documents (PDFs, etc.), prefer opening the original source file if it still exists.
922    // The canonical payload for document frames contains extracted text, not the original binary.
923    if let Some(source_path) = &frame.source_path {
924        let source = Path::new(source_path);
925        if source.exists() {
926            println!("Opening preview...");
927            open::that(source).with_context(|| {
928                format!("failed to launch default viewer for {}", source.display())
929            })?;
930            println!(
931                "Opened preview for {} (frame {}) -> {} ({})",
932                display_uri, frame.id, source_path, mime
933            );
934            return Ok(());
935        } else {
936            warn!(
937                "Original source file no longer exists: {}. Falling back to extracted content.",
938                source_path
939            );
940        }
941    }
942
943    // Fall back to extracted content (text for PDFs, raw bytes for other documents)
944    let bytes = mem
945        .frame_canonical_payload(frame.id)
946        .context("failed to load canonical payload for frame")?;
947    if bytes.is_empty() {
948        bail!("frame payload is empty; nothing to preview");
949    }
950
951    let mut extension = manifest
952        .and_then(|m| m.filename.as_deref())
953        .and_then(|name| Path::new(name).extension().and_then(|ext| ext.to_str()))
954        .map(|ext| ext.trim_start_matches('.').to_string())
955        .or_else(|| extension_from_mime(mime).map(|ext| ext.to_string()))
956        .unwrap_or_else(|| "bin".to_string());
957
958    // For documents where we only have extracted text, use .txt extension
959    if frame.chunk_manifest.is_some() {
960        extension = "txt".to_string();
961    } else if extension == "bin" && std::str::from_utf8(&bytes).is_ok() {
962        extension = "txt".to_string();
963    }
964
965    let suffix = format!(".{extension}");
966    let mut temp_file = Builder::new()
967        .prefix("memvid-preview-")
968        .suffix(&suffix)
969        .tempfile_in(std::env::temp_dir())
970        .context("failed to create temporary preview file")?;
971    temp_file
972        .write_all(&bytes)
973        .context("failed to write document data to preview file")?;
974    temp_file
975        .flush()
976        .context("failed to flush preview file to disk")?;
977
978    let (file, preview_path) = temp_file.keep().context("failed to persist preview file")?;
979    drop(file);
980
981    println!("Opening preview...");
982    open::that(&preview_path).with_context(|| {
983        format!(
984            "failed to launch default viewer for {}",
985            preview_path.display()
986        )
987    })?;
988
989    println!(
990        "Opened preview for {} (frame {}) -> {} ({})",
991        display_uri,
992        frame.id,
993        preview_path.display(),
994        if frame.chunk_manifest.is_some() {
995            "text/plain (extracted)"
996        } else {
997            mime
998        }
999    );
1000    Ok(())
1001}
1002
1003fn preview_frame_audio_file(
1004    mem: &mut Memvid,
1005    frame: &Frame,
1006    cli_uri: Option<&str>,
1007    manifest: Option<&MediaManifest>,
1008    mime: &str,
1009) -> Result<()> {
1010    let bytes = mem
1011        .frame_canonical_payload(frame.id)
1012        .context("failed to load canonical payload for frame")?;
1013    if bytes.is_empty() {
1014        bail!("frame payload is empty; nothing to preview");
1015    }
1016
1017    let mut extension = manifest
1018        .and_then(|m| m.filename.as_deref())
1019        .and_then(|name| Path::new(name).extension().and_then(|ext| ext.to_str()))
1020        .map(|ext| ext.trim_start_matches('.').to_string())
1021        .or_else(|| extension_from_mime(mime).map(|ext| ext.to_string()))
1022        .unwrap_or_else(|| "audio".to_string());
1023
1024    if extension == "bin" {
1025        extension = "audio".to_string();
1026    }
1027
1028    let suffix = format!(".{extension}");
1029    let mut temp_file = Builder::new()
1030        .prefix("memvid-preview-")
1031        .suffix(&suffix)
1032        .tempfile_in(std::env::temp_dir())
1033        .context("failed to create temporary preview file")?;
1034    temp_file
1035        .write_all(&bytes)
1036        .context("failed to write audio data to preview file")?;
1037    temp_file
1038        .flush()
1039        .context("failed to flush preview file to disk")?;
1040
1041    let (file, preview_path) = temp_file.keep().context("failed to persist preview file")?;
1042    drop(file);
1043
1044    println!("Opening preview...");
1045    open::that(&preview_path).with_context(|| {
1046        format!(
1047            "failed to launch default audio player for {}",
1048            preview_path.display()
1049        )
1050    })?;
1051
1052    let display_uri = cli_uri
1053        .or_else(|| frame.uri.as_deref())
1054        .unwrap_or("<unknown>");
1055    println!(
1056        "Opened preview for {} (frame {}) -> {} ({})",
1057        display_uri,
1058        frame.id,
1059        preview_path.display(),
1060        mime
1061    );
1062    Ok(())
1063}
1064
1065#[cfg(feature = "audio-playback")]
1066fn play_frame_audio(
1067    mem: &mut Memvid,
1068    frame: &Frame,
1069    start_seconds: Option<f32>,
1070    end_seconds: Option<f32>,
1071) -> Result<()> {
1072    use rodio::Source;
1073
1074    if let (Some(start), Some(end)) = (start_seconds, end_seconds) {
1075        if end <= start {
1076            bail!("--end-seconds must be greater than --start-seconds");
1077        }
1078    }
1079
1080    let bytes = mem
1081        .frame_canonical_payload(frame.id)
1082        .context("failed to load canonical payload for frame")?;
1083    if bytes.is_empty() {
1084        bail!("frame payload is empty; nothing to play");
1085    }
1086
1087    let start = start_seconds.unwrap_or(0.0).max(0.0);
1088    let duration_meta = frame
1089        .metadata
1090        .as_ref()
1091        .and_then(|meta| meta.audio.as_ref())
1092        .and_then(|audio| audio.duration_secs)
1093        .unwrap_or(0.0);
1094
1095    if duration_meta > 0.0 && start >= duration_meta {
1096        bail!("start-seconds ({start:.2}) exceeds audio duration ({duration_meta:.2})");
1097    }
1098
1099    if let Some(end) = end_seconds {
1100        if duration_meta > 0.0 && end > duration_meta + f32::EPSILON {
1101            warn!(
1102                "requested end-seconds {:.2} exceeds known duration {:.2}; clamping",
1103                end, duration_meta
1104            );
1105        }
1106    }
1107
1108    let cursor = Cursor::new(bytes);
1109    let decoder = rodio::Decoder::new(cursor).context("failed to decode audio stream")?;
1110    let (_stream, stream_handle) =
1111        rodio::OutputStream::try_default().context("failed to open default audio output")?;
1112    let sink = rodio::Sink::try_new(&stream_handle).context("failed to create audio sink")?;
1113    let display_uri = frame.uri.as_deref().unwrap_or("<unknown>");
1114
1115    if let Some(end) = end_seconds {
1116        let effective_end = if duration_meta > 0.0 {
1117            end.min(duration_meta)
1118        } else {
1119            end
1120        };
1121        let duration = (effective_end - start).max(0.0);
1122        if duration <= 0.0 {
1123            bail!("playback duration is zero; adjust start/end seconds");
1124        }
1125        let source = decoder
1126            .skip_duration(Duration::from_secs_f32(start))
1127            .take_duration(Duration::from_secs_f32(duration));
1128        sink.append(source);
1129        let segment_desc = format!("{start:.2}s → {effective_end:.2}s");
1130        announce_playback(display_uri, &segment_desc);
1131    } else {
1132        let source = decoder.skip_duration(Duration::from_secs_f32(start));
1133        sink.append(source);
1134        let segment_desc = format!("{start:.2}s → end");
1135        announce_playback(display_uri, &segment_desc);
1136    }
1137    sink.sleep_until_end();
1138    Ok(())
1139}
1140
1141#[cfg(feature = "audio-playback")]
1142fn announce_playback(uri: &str, segment_desc: &str) {
1143    println!("Playing {uri} ({segment_desc})");
1144}
1145
1146fn is_image_mime(value: &str) -> bool {
1147    let normalized = value.split(';').next().unwrap_or(value).trim();
1148    normalized.to_ascii_lowercase().starts_with("image/")
1149}
1150
1151fn is_audio_mime(value: &str) -> bool {
1152    let normalized = value.split(';').next().unwrap_or(value).trim();
1153    normalized.to_ascii_lowercase().starts_with("audio/")
1154}
1155
1156pub fn extension_from_mime(mime: &str) -> Option<&'static str> {
1157    let normalized = mime
1158        .split(';')
1159        .next()
1160        .unwrap_or(mime)
1161        .trim()
1162        .to_ascii_lowercase();
1163    match normalized.as_str() {
1164        "image/jpeg" | "image/jpg" => Some("jpg"),
1165        "image/png" => Some("png"),
1166        "image/gif" => Some("gif"),
1167        "image/webp" => Some("webp"),
1168        "image/bmp" => Some("bmp"),
1169        "image/tiff" => Some("tiff"),
1170        "image/x-icon" | "image/vnd.microsoft.icon" => Some("ico"),
1171        "image/svg+xml" => Some("svg"),
1172        "video/mp4" | "video/iso.segment" => Some("mp4"),
1173        "video/quicktime" => Some("mov"),
1174        "video/webm" => Some("webm"),
1175        "video/x-matroska" | "video/matroska" => Some("mkv"),
1176        "video/x-msvideo" => Some("avi"),
1177        "video/mpeg" => Some("mpg"),
1178        "application/pdf" => Some("pdf"),
1179        "audio/mpeg" | "audio/mp3" => Some("mp3"),
1180        "audio/wav" | "audio/x-wav" => Some("wav"),
1181        "audio/x-flac" | "audio/flac" => Some("flac"),
1182        "audio/ogg" | "audio/vorbis" => Some("ogg"),
1183        "audio/x-m4a" | "audio/mp4" => Some("m4a"),
1184        "audio/aac" => Some("aac"),
1185        "audio/x-aiff" | "audio/aiff" => Some("aiff"),
1186        "text/plain" => Some("txt"),
1187        "text/markdown" | "text/x-markdown" => Some("md"),
1188        "text/html" => Some("html"),
1189        "application/xhtml+xml" => Some("xhtml"),
1190        "application/json" | "text/json" | "application/vnd.api+json" => Some("json"),
1191        "application/xml" | "text/xml" => Some("xml"),
1192        "text/csv" | "application/csv" => Some("csv"),
1193        "application/javascript" | "text/javascript" => Some("js"),
1194        "text/css" => Some("css"),
1195        "application/yaml" | "application/x-yaml" | "text/yaml" => Some("yaml"),
1196        "application/rtf" => Some("rtf"),
1197        "application/msword" => Some("doc"),
1198        "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => Some("docx"),
1199        "application/vnd.ms-powerpoint" => Some("ppt"),
1200        "application/vnd.openxmlformats-officedocument.presentationml.presentation" => Some("pptx"),
1201        "application/vnd.ms-excel" => Some("xls"),
1202        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => Some("xlsx"),
1203        "application/zip" => Some("zip"),
1204        "application/x-tar" => Some("tar"),
1205        "application/x-7z-compressed" => Some("7z"),
1206        _ => None,
1207    }
1208}
1209pub fn search_snippet(text: Option<&String>) -> Option<String> {
1210    text.and_then(|value| {
1211        let trimmed = value.trim();
1212        if trimmed.is_empty() {
1213            None
1214        } else {
1215            Some(trimmed.chars().take(160).collect())
1216        }
1217    })
1218}
1219pub fn frame_to_json(frame: &Frame) -> serde_json::Value {
1220    json!({
1221        "id": frame.id,
1222        "status": frame_status_str(frame.status),
1223        "timestamp": frame.timestamp,
1224        "kind": frame.kind,
1225        "track": frame.track,
1226        "uri": frame.uri,
1227        "title": frame.title,
1228        "payload_length": frame.payload_length,
1229        "canonical_encoding": format!("{:?}", frame.canonical_encoding),
1230        "canonical_length": frame.canonical_length,
1231        "role": format!("{:?}", frame.role),
1232        "parent_id": frame.parent_id,
1233        "chunk_index": frame.chunk_index,
1234        "chunk_count": frame.chunk_count,
1235        "tags": frame.tags,
1236        "labels": frame.labels,
1237        "search_text": frame.search_text,
1238        "metadata": frame.metadata,
1239        "extra_metadata": frame.extra_metadata,
1240        "content_dates": frame.content_dates,
1241        "chunk_manifest": frame.chunk_manifest,
1242        "supersedes": frame.supersedes,
1243        "superseded_by": frame.superseded_by,
1244        "source_sha256": frame.source_sha256.map(|h| hex::encode(h)),
1245        "source_path": frame.source_path,
1246    })
1247}
1248pub fn print_frame_summary(mem: &mut Memvid, frame: &Frame) -> Result<()> {
1249    println!("Frame {} [{}]", frame.id, frame_status_str(frame.status));
1250    println!("Timestamp: {}", frame.timestamp);
1251    if let Some(uri) = &frame.uri {
1252        println!("URI: {uri}");
1253    }
1254    if let Some(title) = &frame.title {
1255        println!("Title: {title}");
1256    }
1257    if let Some(kind) = &frame.kind {
1258        println!("Kind: {kind}");
1259    }
1260    if let Some(track) = &frame.track {
1261        println!("Track: {track}");
1262    }
1263    if let Some(supersedes) = frame.supersedes {
1264        println!("Supersedes frame: {supersedes}");
1265    }
1266    if let Some(successor) = frame.superseded_by {
1267        println!("Superseded by frame: {successor}");
1268    }
1269    println!(
1270        "Payload: {} bytes (canonical {:?}, logical {:?})",
1271        frame.payload_length, frame.canonical_encoding, frame.canonical_length
1272    );
1273    if !frame.tags.is_empty() {
1274        println!("Tags: {}", frame.tags.join(", "));
1275    }
1276    if !frame.labels.is_empty() {
1277        println!("Labels: {}", frame.labels.join(", "));
1278    }
1279    if let Some(snippet) = search_snippet(frame.search_text.as_ref()) {
1280        println!("Search text: {snippet}");
1281    }
1282    if let Some(meta) = &frame.metadata {
1283        let rendered = serde_json::to_string_pretty(meta)?;
1284        println!("Metadata: {rendered}");
1285    }
1286    if !frame.extra_metadata.is_empty() {
1287        let mut entries: Vec<_> = frame.extra_metadata.iter().collect();
1288        entries.sort_by(|a, b| a.0.cmp(b.0));
1289        println!("Extra metadata:");
1290        for (key, value) in entries {
1291            println!("  {key}: {value}");
1292        }
1293    }
1294    if !frame.content_dates.is_empty() {
1295        println!("Content dates: {}", frame.content_dates.join(", "));
1296    }
1297    // Show no-raw mode info if applicable
1298    if let Some(hash) = frame.source_sha256 {
1299        println!("Source SHA256: {} (raw binary not stored)", hex::encode(hash));
1300        if let Some(path) = &frame.source_path {
1301            println!("Source path: {path}");
1302        }
1303    }
1304    match mem.frame_embedding(frame.id) {
1305        Ok(Some(embedding)) => println!("Embedding: {} dimensions", embedding.len()),
1306        Ok(None) => println!("Embedding: none"),
1307        Err(err) => println!("Embedding: unavailable ({err})"),
1308    }
1309    Ok(())
1310}
1311fn canonical_text_for_view(mem: &mut Memvid, frame: &Frame) -> Result<String> {
1312    let bytes = mem.frame_canonical_payload(frame.id)?;
1313    let raw = match String::from_utf8(bytes) {
1314        Ok(text) => text,
1315        Err(err) => {
1316            let bytes = err.into_bytes();
1317            String::from_utf8_lossy(&bytes).into_owned()
1318        }
1319    };
1320
1321    Ok(normalize_text(&raw, usize::MAX)
1322        .map(|n| n.text)
1323        .unwrap_or_default())
1324}
1325
1326fn manifests_match_text(text: &str, manifest: &TextChunkManifest) -> bool {
1327    if manifest.chunk_chars == 0 || manifest.chunks.is_empty() {
1328        return false;
1329    }
1330    let total_chars = text.chars().count();
1331    manifest
1332        .chunks
1333        .iter()
1334        .all(|chunk| chunk.start <= chunk.end && chunk.end <= total_chars)
1335}
1336
1337fn canonical_manifest_from_frame(text: &str, frame: &Frame) -> Option<TextChunkManifest> {
1338    let primary = frame
1339        .chunk_manifest
1340        .clone()
1341        .filter(|manifest| manifests_match_text(text, manifest));
1342    if primary.is_some() {
1343        return primary;
1344    }
1345
1346    frame
1347        .extra_metadata
1348        .get(CHUNK_MANIFEST_KEY)
1349        .and_then(|raw| serde_json::from_str::<TextChunkManifest>(raw).ok())
1350        .filter(|manifest| manifests_match_text(text, manifest))
1351}
1352
1353fn compute_chunk_manifest(text: &str, chunk_chars: usize) -> TextChunkManifest {
1354    let normalized = normalize_text(text, usize::MAX)
1355        .map(|n| n.text)
1356        .unwrap_or_default();
1357
1358    let effective_chunk = chunk_chars.max(1);
1359    let total_chars = normalized.chars().count();
1360    if total_chars == 0 {
1361        return TextChunkManifest {
1362            chunk_chars: effective_chunk,
1363            chunks: vec![TextChunkRange { start: 0, end: 0 }],
1364        };
1365    }
1366    if total_chars <= effective_chunk {
1367        return TextChunkManifest {
1368            chunk_chars: effective_chunk,
1369            chunks: vec![TextChunkRange {
1370                start: 0,
1371                end: total_chars,
1372            }],
1373        };
1374    }
1375    let mut chunks = Vec::new();
1376    let mut start = 0usize;
1377    while start < total_chars {
1378        let end = (start + effective_chunk).min(total_chars);
1379        chunks.push(TextChunkRange { start, end });
1380        start = end;
1381    }
1382    TextChunkManifest {
1383        chunk_chars: effective_chunk,
1384        chunks,
1385    }
1386}
1387
1388fn extract_chunk_slice(text: &str, range: &TextChunkRange) -> String {
1389    if range.start >= range.end || text.is_empty() {
1390        return String::new();
1391    }
1392    let mut start_byte = text.len();
1393    let mut end_byte = text.len();
1394    let mut idx = 0usize;
1395    for (byte_offset, _) in text.char_indices() {
1396        if idx == range.start {
1397            start_byte = byte_offset;
1398        }
1399        if idx == range.end {
1400            end_byte = byte_offset;
1401            break;
1402        }
1403        idx += 1;
1404    }
1405    if start_byte == text.len() {
1406        return String::new();
1407    }
1408    if end_byte == text.len() {
1409        end_byte = text.len();
1410    }
1411    text[start_byte..end_byte].to_string()
1412}