Skip to main content

solverforge_scoring/api/
analysis.rs

1//! Score analysis types for detailed constraint tracking.
2//!
3//! This module provides types for analyzing constraint matches in detail,
4//! including which entities are involved in each match, score explanations,
5//! and entity-level indictments.
6
7use std::any::Any;
8use std::fmt::Debug;
9use std::hash::{Hash, Hasher};
10use std::sync::Arc;
11
12use solverforge_core::score::Score;
13use solverforge_core::ConstraintRef;
14
15/// Reference to an entity involved in a constraint match.
16/// Uses type erasure to allow storing references to different entity types
17/// in a single collection.
18#[derive(Clone)]
19pub struct EntityRef {
20    /// Type name of the entity (e.g., "Shift", "Employee").
21    pub type_name: String,
22    /// String representation for display.
23    pub display: String,
24    // Type-erased entity for programmatic access.
25    entity: Arc<dyn Any + Send + Sync>,
26}
27
28impl EntityRef {
29    /// Creates a new entity reference from a concrete entity.
30    pub fn new<T: Clone + Debug + Send + Sync + 'static>(entity: &T) -> Self {
31        Self {
32            type_name: std::any::type_name::<T>().to_string(),
33            display: format!("{:?}", entity),
34            entity: Arc::new(entity.clone()),
35        }
36    }
37
38    /// Creates an entity reference with a custom display string.
39    pub fn with_display<T: Clone + Send + Sync + 'static>(entity: &T, display: String) -> Self {
40        Self {
41            type_name: std::any::type_name::<T>().to_string(),
42            display,
43            entity: Arc::new(entity.clone()),
44        }
45    }
46
47    /// Attempts to downcast to the concrete entity type.
48    pub fn as_entity<T: 'static>(&self) -> Option<&T> {
49        self.entity.downcast_ref::<T>()
50    }
51
52    /// Returns the short type name (without module path).
53    pub fn short_type_name(&self) -> &str {
54        self.type_name
55            .rsplit("::")
56            .next()
57            .unwrap_or(&self.type_name)
58    }
59}
60
61impl Debug for EntityRef {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        f.debug_struct("EntityRef")
64            .field("type", &self.short_type_name())
65            .field("display", &self.display)
66            .finish()
67    }
68}
69
70impl PartialEq for EntityRef {
71    fn eq(&self, other: &Self) -> bool {
72        self.type_name == other.type_name && self.display == other.display
73    }
74}
75
76impl Eq for EntityRef {}
77
78impl Hash for EntityRef {
79    fn hash<H: Hasher>(&self, state: &mut H) {
80        self.type_name.hash(state);
81        self.display.hash(state);
82    }
83}
84
85/// Justification for why a constraint matched.
86#[derive(Debug, Clone)]
87pub struct ConstraintJustification {
88    /// Entities involved in the match.
89    pub entities: Vec<EntityRef>,
90    /// Human-readable description of why the constraint matched.
91    pub description: String,
92}
93
94impl ConstraintJustification {
95    /// Creates a justification from entities, auto-generating description.
96    pub fn new(entities: Vec<EntityRef>) -> Self {
97        let description = if entities.is_empty() {
98            "No entities".to_string()
99        } else {
100            entities
101                .iter()
102                .map(|e| e.display.as_str())
103                .collect::<Vec<_>>()
104                .join(", ")
105        };
106        Self {
107            entities,
108            description,
109        }
110    }
111
112    /// Creates a justification with a custom description.
113    pub fn with_description(entities: Vec<EntityRef>, description: String) -> Self {
114        Self {
115            entities,
116            description,
117        }
118    }
119}
120
121/// A detailed constraint match with entity information.
122#[derive(Debug, Clone)]
123pub struct DetailedConstraintMatch<'a, Sc: Score> {
124    /// Reference to the constraint that matched.
125    pub constraint_ref: &'a ConstraintRef,
126    /// Score impact of this match.
127    pub score: Sc,
128    /// Justification with involved entities.
129    pub justification: ConstraintJustification,
130}
131
132impl<'a, Sc: Score> DetailedConstraintMatch<'a, Sc> {
133    /// Creates a new detailed constraint match.
134    pub fn new(
135        constraint_ref: &'a ConstraintRef,
136        score: Sc,
137        justification: ConstraintJustification,
138    ) -> Self {
139        Self {
140            constraint_ref,
141            score,
142            justification,
143        }
144    }
145}
146
147/// Per-constraint breakdown in a score explanation.
148#[derive(Debug, Clone)]
149pub struct ConstraintAnalysis<'a, Sc: Score> {
150    /// Constraint reference.
151    pub constraint_ref: &'a ConstraintRef,
152    /// Bound runtime weight multiplier; `0` means the constraint is disabled.
153    pub weight_multiplier: u32,
154    /// Total (weighted) score from this constraint.
155    pub score: Sc,
156    /// All matches for this constraint.
157    pub matches: Vec<DetailedConstraintMatch<'a, Sc>>,
158    /// Whether this is a hard constraint.
159    pub is_hard: bool,
160}
161
162impl<'a, Sc: Score> ConstraintAnalysis<'a, Sc> {
163    /// Creates a new constraint analysis.
164    pub fn new(
165        constraint_ref: &'a ConstraintRef,
166        weight_multiplier: u32,
167        score: Sc,
168        matches: Vec<DetailedConstraintMatch<'a, Sc>>,
169        is_hard: bool,
170    ) -> Self {
171        Self {
172            constraint_ref,
173            weight_multiplier,
174            score,
175            matches,
176            is_hard,
177        }
178    }
179
180    /// Returns the number of matches.
181    pub fn match_count(&self) -> usize {
182        self.matches.len()
183    }
184
185    /// Returns the constraint name.
186    pub fn name(&self) -> &str {
187        &self.constraint_ref.name
188    }
189}