1use crate::core::search::{Confidence, Hit};
8use serde::Serialize;
9
10#[derive(Debug, Clone, Serialize)]
11pub struct Citation {
12 pub source_id: i64,
13 pub path: String,
14 pub page: i64,
15 pub line_start: i64,
16 pub line_end: i64,
17 #[serde(skip_serializing_if = "Option::is_none")]
19 pub anchor: Option<String>,
20 #[serde(skip_serializing_if = "Option::is_none")]
22 pub section: Option<String>,
23 pub reference: String,
25}
26
27#[derive(Debug, Clone, Serialize)]
28pub struct Answer {
29 pub question: String,
30 pub text: String,
32 pub citations: Vec<Citation>,
33 pub not_found: bool,
35 pub engine: String,
37}
38
39impl Citation {
40 pub fn from_hit(hit: &Hit) -> Self {
41 let mut reference = hit.path.clone();
42 if let Some(anchor) = &hit.anchor {
43 reference.push_str(&format!(" [{anchor}]"));
44 }
45 if hit.line_start > 0 {
46 reference.push_str(&format!(":{}-{}", hit.line_start, hit.line_end));
47 } else if hit.page > 0 {
48 reference.push_str(&format!(":p.{}", hit.page));
49 }
50 Self {
51 source_id: hit.source_id,
52 path: hit.path.clone(),
53 page: hit.page,
54 line_start: hit.line_start,
55 line_end: hit.line_end,
56 anchor: hit.anchor.clone(),
57 section: hit.section.clone(),
58 reference,
59 }
60 }
61}
62
63impl Answer {
64 pub fn from_hits(question: &str, hits: &[Hit]) -> Self {
70 let supported: Vec<&Hit> = hits
71 .iter()
72 .filter(|hit| !matches!(hit.confidence, Confidence::Low))
73 .collect();
74 match supported.first() {
75 None => Self {
76 question: question.to_string(),
77 text: String::new(),
78 citations: vec![],
79 not_found: true,
80 engine: "local".to_string(),
81 },
82 Some(top) => Self {
83 question: question.to_string(),
84 text: top.snippet.clone(),
85 citations: supported
86 .iter()
87 .take(3)
88 .map(|h| Citation::from_hit(h))
89 .collect(),
90 not_found: false,
91 engine: "local".to_string(),
92 },
93 }
94 }
95
96 pub fn render(&self) -> String {
98 if self.not_found {
99 return "No matching document found in the local index.".to_string();
100 }
101 let mut out = self.text.clone();
102 out.push_str("\n\nSources:\n");
103 for citation in &self.citations {
104 out.push_str(&format!(" - {}\n", citation.reference));
105 }
106 out
107 }
108}