use serde::Serialize;
use crate::query::{query_cascade, Hit, Index};
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Choice {
pub label: String,
pub city: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub region: Option<String>,
pub lat: f64,
pub lon: f64,
}
#[derive(Clone, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Outcome {
Answer {
results: Vec<Hit>,
},
Clarify {
results: Vec<Hit>,
missing: &'static str,
options: Vec<Choice>,
},
None {
reason: &'static str,
},
}
pub const REASONS: [&str; 5] = [
"no_street",
"no_house",
"city_unknown",
"outside_sheet",
"unparsed",
];
pub fn query_outcome(addr: &Index, poi: Option<&Index>, q: &str, k: usize) -> Outcome {
let results = query_cascade(addr, poi, q, k);
if results.is_empty() {
return Outcome::None {
reason: why_silent(addr, q),
};
}
let top = &results[0];
if !top.flags.contains(&"ambiguous_far") {
return Outcome::Answer { results };
}
let options = choices(&query_cascade(addr, poi, q, 10));
if options.len() < 2 {
return Outcome::Answer { results };
}
let same_name = options.iter().all(|c| c.city == options[0].city);
let missing = match (same_name, options.iter().all(|c| c.region.is_some())) {
(_, true) => "region",
(true, false) => "postcode",
(false, false) => "city",
};
Outcome::Clarify {
results,
missing,
options,
}
}
fn choices(candidates: &[Hit]) -> Vec<Choice> {
let Some(top) = candidates.first() else {
return Vec::new();
};
let tier = |h: &Hit| match h.precision {
"house" | "interp" | "near" => 0,
"street" | "intersection" => 1,
_ => 2,
};
let mut out: Vec<Choice> = Vec::new();
for h in candidates.iter().filter(|h| tier(h) == tier(top)) {
let far_from_all = out
.iter()
.all(|c| crate::codes::haversine_m((c.lat, c.lon), (h.lat, h.lon)) > 50_000.0);
if !far_from_all {
continue;
}
let label = match (&h.region, h.postcode.is_empty()) {
(Some(region), _) if !region.is_empty() => format!("{}, {region}", h.commune),
(_, false) => format!("{} {}", h.commune, h.postcode),
_ => h.commune.clone(),
};
out.push(Choice {
label,
city: h.commune.clone(),
region: h.region.clone().filter(|r| !r.is_empty()),
lat: h.lat,
lon: h.lon,
});
if out.len() == 5 {
break;
}
}
out
}
fn why_silent(addr: &Index, q: &str) -> &'static str {
if crate::forms::point(q).is_some() {
return "outside_sheet";
}
if q.trim().is_empty() || !q.chars().any(char::is_alphabetic) {
return "unparsed";
}
let trace = crate::diagnosis::Scope::new();
let _ = addr.query(q, 1);
let observed = trace.finish(0);
match reason_of_stage(observed["stop_stage"].as_str().unwrap_or("")) {
"city_unknown" if !q.contains(',') => "no_street",
reason => reason,
}
}
fn reason_of_stage(stage: &str) -> &'static str {
match stage {
"empty_parse" | "unobserved_shortcut" => "unparsed",
"no_area_or_global_street" => "city_unknown",
"no_street_candidate" => "no_street",
"before_hit_construction"
| "after_ranking_unobserved_guard"
| "fallback_guard_rejected" => "no_house",
_ => "no_street",
}
}
#[cfg(test)]
mod tests {
use super::*;
fn hit(commune: &str, region: Option<&str>, lat: f64, precision: &'static str) -> Hit {
Hit {
lat,
lon: -84.5,
precision,
score: 1.0,
confidence: 0.2,
street: "Mill Street".into(),
housenumber: None,
commune: commune.into(),
postcode: String::new(),
flags: vec!["street_exact"],
region: region.map(String::from),
distance_m: None,
}
}
#[test]
fn choices_are_the_distinct_far_places_of_the_answer_tier() {
let c = choices(&[
hit("Lexington", Some("Kentucky"), 38.04, "street"),
hit("Lexington", Some("Kentucky"), 38.05, "street"), hit("Lexington", Some("North Carolina"), 35.82, "street"),
hit("Lexington", Some("Virginia"), 37.0, "city"), ]);
let labels: Vec<&str> = c.iter().map(|c| c.label.as_str()).collect();
assert_eq!(labels, ["Lexington, Kentucky", "Lexington, North Carolina"]);
}
#[test]
fn every_stage_of_the_trace_has_one_of_the_five_reasons() {
for stage in [
"empty_parse",
"unobserved_shortcut",
"no_area_or_global_street",
"no_street_candidate",
"before_hit_construction",
"after_ranking_unobserved_guard",
"fallback_guard_rejected",
"returned",
] {
assert!(REASONS.contains(&reason_of_stage(stage)), "{stage}");
}
assert_eq!(reason_of_stage("no_area_or_global_street"), "city_unknown");
assert_eq!(reason_of_stage("before_hit_construction"), "no_house");
}
}