use std::collections::HashMap;
use relate_core::{expected_type_detail, value_type_name, Error, Result, Value};
use relate_ir::{Expr, SearchCombineSpec};
use relate_model::EntityKind;
use crate::ctx::ExecCtx;
use crate::eval::eval;
use crate::exec::candidates::{ranked_candidates, TopWindow};
use crate::row::Row;
use super::{
candidate_entity_id, invalid_value_type, search_spec_candidates, spec_window, Growth,
SearchEnv, SearchWindow, SpecCandidates,
};
pub(super) fn combine_candidates(
env: &SearchEnv<'_>,
input: &Row,
combine: &SearchCombineSpec,
window: SearchWindow,
) -> Result<Option<SpecCandidates>> {
let constant = eval_wrrf_number(
env.ctx,
input,
combine.constant_expr.as_deref(),
60.0,
"CONSTANT",
)?;
let mut kind: Option<EntityKind> = None;
let mut fused: HashMap<i64, f64> = HashMap::new();
for source in &combine.sources {
let source_window = spec_window(env, input, &source.spec)?;
let Some(fetched) =
search_spec_candidates(env, input, &source.spec, source_window, Growth::Fixed)?
else {
continue;
};
let fused_kind = *kind.get_or_insert(fetched.kind);
if fused_kind != fetched.kind {
return Err(invalid_value_type(expected_type_detail(
fused_kind.display_name(),
fetched.kind.display_name(),
)));
}
let weight =
eval_wrrf_number(env.ctx, input, source.weight_expr.as_deref(), 1.0, "WEIGHT")?;
for (rank, (candidate, _score)) in fetched
.candidates
.into_iter()
.skip(source_window.skip)
.enumerate()
{
let id = candidate_entity_id(&candidate)?;
let contribution = weight / (constant + rank as f64 + 1.0);
fused
.entry(id)
.and_modify(|score| *score += contribution)
.or_insert(contribution);
}
}
let Some(kind) = kind else {
return Ok(None);
};
let mut top = TopWindow::new(0, window.limit);
for (id, score) in &fused {
top.push(*score, *id);
}
let candidates = ranked_candidates(env.ctx.graph, kind, top.into_sorted_rows());
Ok(Some(SpecCandidates {
kind,
candidates,
may_widen: false,
}))
}
fn eval_wrrf_number(
ctx: ExecCtx<'_>,
input: &Row,
expr: Option<&Expr>,
default: f64,
clause: &str,
) -> Result<f64> {
let Some(expr) = expr else {
return Ok(default);
};
let ExecCtx { graph, params, .. } = ctx;
let value = eval(graph, input, expr, params)?;
let number = match &value {
Value::Int(number) => *number as f64,
Value::Float(number) => *number,
_ => {
return Err(invalid_value_type(format!(
"{} (SEARCH {clause})",
expected_type_detail(
"INTEGER NOT NULL or FLOAT NOT NULL",
&value_type_name(&value),
)
)))
}
};
if !(0.0..=f64::from(i32::MAX)).contains(&number) {
return Err(Error::syntax(format!(
"NumberOutOfRange: SEARCH {clause} must be between 0 and 2147483647"
)));
}
Ok(number)
}