use alloc::collections::{BTreeMap, BinaryHeap};
use alloc::vec::Vec;
use core::cmp::Reverse;
use search_core::{Cost, Heuristic};
use crate::cost::add;
use crate::graph::Graph;
use crate::output::{Solution, Stats};
pub fn constrained_shortest_path<G, H, C, P>(
graph: &G,
mut heuristic: H,
start: G::State,
is_goal: P,
budget: C,
stats: &mut Stats,
) -> Option<Solution<G::State, [C; 2]>>
where
G: Graph<Weight = [C; 2]>,
H: Heuristic<G::State, [C; 2]>,
C: Cost,
P: Fn(&G::State) -> bool,
{
let mut nodes: Vec<(G::State, [C; 2], Option<usize>)> = Vec::new();
let mut open = BinaryHeap::new();
let mut g2_min: BTreeMap<G::State, C> = BTreeMap::new();
let mut successors = Vec::new();
let h = heuristic.estimate(&start)?;
if h[1] > budget {
return None;
}
nodes.push((start, [C::ZERO; 2], None));
open.push(Reverse((h, 0)));
stats.generated += 1;
while let Some(Reverse((_, index))) = open.pop() {
let (here, g, _) = nodes[index].clone();
if g2_min.get(&here).is_some_and(|&m| g[1] >= m) {
continue;
}
g2_min.insert(here.clone(), g[1]);
if is_goal(&here) {
return Some(rebuild(&nodes, index));
}
stats.expanded += 1;
graph.successors(&here, &mut successors);
for (next, weight) in successors.drain(..) {
let g_next = add(g, weight);
if g2_min.get(&next).is_some_and(|&m| g_next[1] >= m) {
continue;
}
let Some(h) = heuristic.estimate(&next) else {
continue;
};
let f = add(g_next, h);
if f[1] > budget {
continue;
}
nodes.push((next, g_next, Some(index)));
open.push(Reverse((f, nodes.len() - 1)));
stats.generated += 1;
}
}
None
}
pub(crate) fn rebuild<S: Clone, C: Copy, const N: usize>(
nodes: &[(S, [C; N], Option<usize>)],
index: usize,
) -> Solution<S, [C; N]> {
let mut path = Vec::new();
let mut current = Some(index);
while let Some(i) = current {
path.push(nodes[i].0.clone());
current = nodes[i].2;
}
path.reverse();
Solution {
cost: nodes[index].1,
path,
}
}