Skip to main content

libkeri/cesr/
tholder.rs

1use crate::cesr::bexter::Bexter;
2use crate::cesr::number::Number;
3use crate::cesr::{bex_dex, num_dex, BaseMatter, Parsable};
4use crate::errors::MatterError;
5use crate::keri::core::serdering::SadValue;
6use crate::Matter;
7use num_rational::Rational32;
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10use std::fmt;
11use std::fmt::Debug;
12
13/// Represents a weight specification for weighted thresholds
14#[derive(Debug, Clone, PartialEq)]
15pub enum WeightSpec {
16    /// Simple fractional weight
17    Simple(Rational32),
18
19    /// Weighted threshold with key weight and list of witness weights
20    WeightedVec(Vec<WeightSpec>),
21
22    /// Weighted threshold with key weight and list of witness weights
23    WeightedMap(Rational32, Vec<Rational32>),
24}
25
26/// Tholder is KERI Signing Threshold Satisfaction struct
27/// It evaluates satisfaction based on ordered list of indices of
28/// verified signatures where indices correspond to offsets in key list.
29#[derive(Debug, Clone)]
30pub struct Tholder {
31    /// True if fractional weighted threshold, False if numeric
32    _weighted: bool,
33
34    /// Minimum size of keys list
35    _size: usize,
36
37    /// Original signing threshold (for sith property)
38    _sith: TholderSith,
39
40    /// Parsed signing threshold for calculating satisfaction
41    _thold: TholderThold,
42
43    /// Bexter instance of weighted signing threshold or None
44    _bexter: Option<Bexter>,
45
46    /// Number instance of integer threshold or None
47    _number: Option<Number>,
48}
49
50/// Represents the different forms of signing threshold (sith)
51#[derive(Debug, Clone, Serialize, Deserialize)]
52#[serde(untagged)]
53pub enum TholderSith {
54    /// Non-negative integer threshold (M of N)
55    Integer(usize),
56
57    /// Hex string representation of integer threshold
58    HexString(String),
59
60    /// Json representation of threshold
61    Json(String),
62
63    /// Single clause of fractional weights
64    Weights(Vec<WeightedSithElement>),
65}
66
67impl TholderSith {
68    pub fn from_sad_value(val: SadValue) -> Result<Self, MatterError> {
69        match val {
70            SadValue::Number(num) => Ok(TholderSith::Integer(num.as_u64().unwrap() as usize)),
71            SadValue::String(s) => {
72                if s.contains("[") {
73                    Ok(TholderSith::Json(s))
74                } else {
75                    Ok(TholderSith::HexString(s))
76                }
77            }
78            // Weighted: kt/nt are JSON lists in the event (keripy: core/coring.py Tholder.sith).
79            SadValue::Array(_) => serde_json::to_string(&val)
80                .map(TholderSith::Json)
81                .map_err(|e| MatterError::ValueError(format!("invalid sith value: {}", e))),
82            _ => Err(MatterError::ValueError(format!(
83                "invalid sith value: {:?}",
84                val
85            ))),
86        }
87    }
88}
89
90impl fmt::Display for TholderSith {
91    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92        match self {
93            TholderSith::Integer(n) => write!(f, "{}", n),
94            TholderSith::HexString(s) => write!(f, "{}", s),
95            TholderSith::Json(s) => write!(f, "{}", s),
96            TholderSith::Weights(w) => {
97                // Format the weights as a JSON string
98                match serde_json::to_string(w) {
99                    Ok(json) => write!(f, "{}", json),
100                    Err(_) => write!(f, "<invalid weights>"),
101                }
102            }
103        }
104    }
105}
106
107// Also implement for the WeightedSithElement for completeness
108impl fmt::Display for WeightedSithElement {
109    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
110        match serde_json::to_string(self) {
111            Ok(json) => write!(f, "{}", json),
112            Err(_) => write!(f, "<invalid weight element>"),
113        }
114    }
115}
116
117/// Represents the different elements that can appear in a weight clause
118#[derive(Debug, Clone, Serialize, Deserialize)]
119#[serde(untagged)]
120pub enum WeightedSithElement {
121    /// Simple fraction string like "1/2"
122    Simple(String),
123
124    /// Array of nested weights like ["1/2", "1/3", ["1/3", "1/3", "1/3"]]
125    Array(Vec<WeightedSithElement>),
126
127    /// Complex weight with key as fraction and value as list of fractions like {"1/2": ["1/2", "1/3"]}
128    Complex(HashMap<String, Vec<WeightedSithElement>>),
129}
130
131/// Represents the parsed threshold for calculating satisfaction
132#[derive(Debug, Clone, PartialEq)]
133pub enum TholderThold {
134    /// Simple integer threshold
135    Integer(usize),
136
137    /// Weighted threshold clauses
138    Weighted(Vec<Vec<WeightSpec>>),
139}
140
141impl Default for Tholder {
142    fn default() -> Self {
143        Tholder {
144            _weighted: false,
145            _size: 0,
146            _sith: TholderSith::HexString(String::new()),
147            _thold: TholderThold::Integer(0),
148            _bexter: None,
149            _number: None,
150        }
151    }
152}
153
154impl Tholder {
155    /// Creates a new Tholder with the provided threshold
156    ///
157    /// # Arguments
158    ///
159    /// * `thold` - Optional computed threshold representation
160    /// * `limen` - Optional CESR serialized threshold
161    /// * `sith` - Optional JSON/CBOR/MGPK serializable threshold
162    ///
163    /// # Returns
164    ///
165    /// A new Tholder instance or an error
166    pub fn new(
167        thold: Option<TholderThold>,
168        limen: Option<Vec<u8>>,
169        sith: Option<TholderSith>,
170    ) -> Result<Self, MatterError> {
171        if let Some(t) = thold {
172            return Self::process_thold(t);
173        } else if let Some(l) = limen {
174            let mut tholder = Tholder::default();
175            tholder.process_limen(l.as_slice(), Some(false))?;
176            return Ok(tholder);
177        } else if let Some(s) = sith {
178            let mut tholder = Tholder::default();
179            tholder.process_sith(s)?;
180            return Ok(tholder);
181        }
182
183        Err(MatterError::EmptyMaterialError(
184            "Missing threshold expression.".to_string(),
185        ))
186    }
187
188    /// Process a computed threshold representation
189    fn process_thold(thold: TholderThold) -> Result<Self, MatterError> {
190        let mut tholder = Tholder::default();
191        match thold {
192            TholderThold::Integer(num) => {
193                tholder.process_unweighted(num)?;
194            }
195            TholderThold::Weighted(clauses) => {
196                tholder.process_weighted(clauses)?;
197            }
198        }
199
200        Ok(tholder)
201    }
202
203    /// Process limen input
204    ///
205    /// # Arguments
206    ///
207    /// * `limen` - CESR encoded qb64 threshold (weighted or unweighted)
208    /// * `strip` - Optional flag to strip trailing pad bytes
209    pub fn process_limen(&mut self, limen: &[u8], strip: Option<bool>) -> Result<(), MatterError> {
210        let matter = BaseMatter::from_qb64b(&mut limen.to_vec(), strip)?;
211
212        if num_dex::MAP.contains_key(matter.code()) {
213            let number = Number::new(Some(matter.raw()), Some(matter.code()), None, None)?;
214            self.process_unweighted(number.num() as usize)?;
215        } else if bex_dex::MAP.contains_key(matter.code()) {
216            // Convert to fractional thold expression
217            let bexter = Bexter::new(Some(matter.raw()), Some(matter.code()), None, None)?;
218            let t = bexter.bext()?.replace('s', "/");
219
220            // Get clauses
221            let clauses: Vec<&str> = t.split('a').collect();
222
223            let mut thold = Vec::new();
224            for c in clauses {
225                let c_parts: Vec<&str> = c.split('c').collect();
226                let mut clause = Vec::new();
227
228                for e in c_parts {
229                    if let Some(k_pos) = e.find('k') {
230                        let k = &e[..k_pos];
231                        let v = &e[(k_pos + 1)..];
232
233                        let v_parts: Vec<&str> = v.split('v').collect();
234                        let weights: Vec<Rational32> = v_parts
235                            .iter()
236                            .map(|w| Self::weight(w))
237                            .collect::<Result<Vec<Rational32>, _>>()?;
238
239                        clause.push(WeightSpec::WeightedMap(Self::weight(k)?, weights));
240                    } else {
241                        clause.push(WeightSpec::Simple(Self::weight(e)?));
242                    }
243                }
244
245                thold.push(clause);
246            }
247
248            self.process_weighted(thold)?;
249        } else {
250            return Err(MatterError::InvalidCode(format!(
251                "Invalid code for limen = {}",
252                matter.code()
253            )));
254        }
255
256        Ok(())
257    }
258
259    /// Process attributes for fractionally weighted threshold sith
260    ///
261    /// # Arguments
262    ///
263    /// * `sith` - Signing threshold (current or next) expressed as one of the TholderSith variants:
264    ///   - Integer: non-negative integer of threshold number (M-of-N threshold)
265    ///   - HexString: non-negative hex string of threshold number (M-of-N threshold)
266    ///   - SimpleWeights: a single clause of fractional weights
267    ///   - ComplexWeights: multiple clauses of fractional weights (AND conditions)
268    pub fn process_sith(&mut self, sith: TholderSith) -> Result<(), MatterError> {
269        match sith {
270            TholderSith::Integer(threshold) => self.process_unweighted(threshold),
271
272            TholderSith::HexString(hex_str) => {
273                // Parse the hex string to get the integer threshold
274                match i32::from_str_radix(&hex_str, 16) {
275                    Ok(threshold) => self.process_unweighted(threshold as usize),
276                    Err(_) => Err(MatterError::ValueError(format!(
277                        "Invalid hex string sith = {}",
278                        hex_str
279                    ))),
280                }
281            }
282
283            TholderSith::Json(json_val) => {
284                // Try to parse as nested array first (multi-clause)
285                if let Ok(nested_clauses) =
286                    serde_json::from_str::<Vec<Vec<WeightedSithElement>>>(json_val.as_str())
287                {
288                    // Multi-clause case
289                    let mut thold = Vec::new();
290                    for clause_elements in nested_clauses {
291                        let mut clause_specs = Vec::new();
292                        for element in clause_elements {
293                            let mut element_specs = self.process_weight_clause(&element)?;
294                            clause_specs.append(&mut element_specs);
295                        }
296                        thold.push(clause_specs);
297                    }
298                    self.process_weighted(thold)
299                } else {
300                    // Single clause case
301                    let clauses: Vec<WeightedSithElement> =
302                        serde_json::from_str(json_val.as_str()).unwrap();
303                    if clauses.is_empty() {
304                        return Err(MatterError::ValueError("Empty weight list".to_string()));
305                    }
306
307                    // Convert all elements to a single clause
308                    let mut single_clause = Vec::new();
309                    for clause in clauses {
310                        let mut processed_specs = self.process_weight_clause(&clause)?;
311                        single_clause.append(&mut processed_specs);
312                    }
313                    self.process_weighted(vec![single_clause])
314                }
315            }
316
317            TholderSith::Weights(clauses) => {
318                if clauses.is_empty() {
319                    return Err(MatterError::ValueError("Empty weight list".to_string()));
320                }
321
322                // Convert all elements to a single clause
323                let mut single_clause = Vec::new();
324                for clause in clauses {
325                    let mut processed_specs = self.process_weight_clause(&clause)?;
326                    single_clause.append(&mut processed_specs);
327                }
328                self.process_weighted(vec![single_clause])
329            }
330        }
331    }
332
333    /// Helper function to process a clause of weight elements
334    fn process_weight_clause(
335        &self,
336        clause: &WeightedSithElement,
337    ) -> Result<Vec<WeightSpec>, MatterError> {
338        match clause {
339            WeightedSithElement::Simple(weight_str) => {
340                let weight = Self::weight(weight_str)?;
341                Ok(vec![WeightSpec::Simple(weight)])
342            }
343
344            WeightedSithElement::Array(elements) => {
345                if elements.is_empty() {
346                    return Err(MatterError::ValueError(
347                        "Empty weight array not allowed".to_string(),
348                    ));
349                }
350
351                let mut specs = Vec::new();
352                for element in elements {
353                    let mut element_specs = self.process_weight_clause(element)?;
354                    specs.append(&mut element_specs);
355                }
356                Ok(specs)
357            }
358
359            WeightedSithElement::Complex(weight_map) => {
360                if weight_map.is_empty() {
361                    return Err(MatterError::ValueError(
362                        "Empty weight map not allowed".to_string(),
363                    ));
364                }
365
366                let mut specs = Vec::new();
367                for (key_str, value_elements) in weight_map {
368                    if value_elements.is_empty() {
369                        return Err(MatterError::ValueError(
370                            "Empty weight values not allowed".to_string(),
371                        ));
372                    }
373
374                    let key_weight = Self::weight(key_str)?;
375                    let mut value_weights = Vec::new();
376
377                    for value_element in value_elements {
378                        if let WeightedSithElement::Simple(weight_str) = value_element {
379                            value_weights.push(Self::weight(weight_str)?);
380                        } else {
381                            return Err(MatterError::ValueError(
382                                "Complex weight values must be simple weights".to_string(),
383                            ));
384                        }
385                    }
386
387                    specs.push(WeightSpec::WeightedMap(key_weight, value_weights));
388                }
389                Ok(specs)
390            }
391        }
392    }
393
394    /// Evaluates if the provided verified signature indices satisfy the threshold
395    ///
396    /// # Arguments
397    ///
398    /// * `indices` - List of indices of verified signatures
399    ///
400    /// # Returns
401    ///
402    /// True if the indices satisfy the threshold, false otherwise
403    pub fn satisfy(&self, indices: &[usize]) -> bool {
404        if self._weighted {
405            self.satisfy_weighted(indices)
406        } else {
407            self.satisfy_numeric(indices)
408        }
409    }
410
411    /// Evaluates if indices satisfy a numeric threshold
412    fn satisfy_numeric(&self, indices: &[usize]) -> bool {
413        if let TholderThold::Integer(num) = self._thold {
414            indices.len() >= num
415        } else {
416            false
417        }
418    }
419
420    /// Evaluates if indices satisfy a weighted threshold
421    fn satisfy_weighted(&self, indices: &[usize]) -> bool {
422        if indices.is_empty() {
423            return false;
424        }
425
426        // Remove duplicates and sort
427        let mut unique_indices: Vec<usize> = indices.iter().cloned().collect();
428        unique_indices.sort_unstable();
429        unique_indices.dedup();
430
431        // Create satisfaction array
432        let mut sats = vec![false; self._size];
433        for &idx in &unique_indices {
434            if idx < self._size {
435                sats[idx] = true;
436            }
437        }
438
439        if let TholderThold::Weighted(ref clauses) = self._thold {
440            let mut wio = 0; // weight index offset
441
442            for clause in clauses {
443                let mut cw = Rational32::new(0, 1); // clause weight
444
445                for element in clause {
446                    match element {
447                        WeightSpec::Simple(weight) => {
448                            if wio < sats.len() && sats[wio] {
449                                cw += *weight;
450                            }
451                            wio += 1;
452                        }
453                        WeightSpec::WeightedMap(key_weight, nested_weights) => {
454                            let mut vw = Rational32::new(0, 1); // value weight
455                            for nested_weight in nested_weights {
456                                if wio < sats.len() && sats[wio] {
457                                    vw += *nested_weight;
458                                }
459                                wio += 1;
460                            }
461                            if vw >= Rational32::new(1, 1) {
462                                cw += *key_weight;
463                            }
464                        }
465                        WeightSpec::WeightedVec(nested_specs) => {
466                            // Handle nested vector case
467                            let mut vw = Rational32::new(0, 1);
468                            for nested_spec in nested_specs {
469                                if let WeightSpec::Simple(weight) = nested_spec {
470                                    if wio < sats.len() && sats[wio] {
471                                        vw += *weight;
472                                    }
473                                    wio += 1;
474                                }
475                            }
476                            if vw >= Rational32::new(1, 1) {
477                                cw += Rational32::new(1, 1); // or appropriate weight
478                            }
479                        }
480                    }
481                }
482
483                if cw < Rational32::new(1, 1) {
484                    return false;
485                }
486            }
487
488            true
489        } else {
490            false
491        }
492    }
493
494    /// Returns whether the threshold is weighted or not
495    pub fn weighted(&self) -> bool {
496        self._weighted
497    }
498
499    /// Returns the parsed threshold
500    pub fn thold(&self) -> &TholderThold {
501        &self._thold
502    }
503
504    /// Returns the minimum size of keys list
505    pub fn size(&self) -> usize {
506        self._size
507    }
508
509    /// Returns the CESR serializable threshold
510    pub fn limen(&self) -> Vec<u8> {
511        if self._weighted {
512            // Assuming Bexter has a qb64b method that returns Vec<u8>
513            self._bexter.as_ref().unwrap().qb64b()
514        } else {
515            // Assuming Number has a qb64b method that returns Vec<u8>
516            self._number.as_ref().unwrap().qb64b()
517        }
518    }
519
520    /// Returns the JSON serializable threshold
521    pub fn sith(&self) -> TholderSith {
522        match &self._thold {
523            TholderThold::Weighted(clauses) => {
524                let mut sith_clauses = Vec::new();
525
526                for clause in clauses {
527                    let mut sith_clause = Vec::new();
528
529                    for element in clause {
530                        match element {
531                            WeightSpec::Simple(weight) => {
532                                let weight_str = if *weight > Rational32::new(0, 1)
533                                    && *weight < Rational32::new(1, 1)
534                                {
535                                    format!("{}/{}", weight.numer(), weight.denom())
536                                } else {
537                                    format!("{}", weight.numer() / weight.denom())
538                                };
539                                sith_clause.push(WeightedSithElement::Simple(weight_str));
540                            }
541                            WeightSpec::WeightedMap(key_weight, nested_weights) => {
542                                let key_str = if *key_weight > Rational32::new(0, 1)
543                                    && *key_weight < Rational32::new(1, 1)
544                                {
545                                    format!("{}/{}", key_weight.numer(), key_weight.denom())
546                                } else {
547                                    format!("{}", key_weight.numer() / key_weight.denom())
548                                };
549
550                                let value_elements: Vec<WeightedSithElement> = nested_weights
551                                    .iter()
552                                    .map(|w| {
553                                        let weight_str = if *w > Rational32::new(0, 1)
554                                            && *w < Rational32::new(1, 1)
555                                        {
556                                            format!("{}/{}", w.numer(), w.denom())
557                                        } else {
558                                            format!("{}", w.numer() / w.denom())
559                                        };
560                                        WeightedSithElement::Simple(weight_str)
561                                    })
562                                    .collect();
563
564                                let mut map = HashMap::new();
565                                map.insert(key_str, value_elements);
566                                sith_clause.push(WeightedSithElement::Complex(map));
567                            }
568                            WeightSpec::WeightedVec(_) => {
569                                // Handle nested vector case
570                            }
571                        }
572                    }
573
574                    sith_clauses.push(sith_clause);
575                }
576
577                // If only one clause, simplify
578                if sith_clauses.len() == 1 {
579                    TholderSith::Weights(sith_clauses.into_iter().next().unwrap())
580                } else {
581                    // Handle multiple clauses case
582                    TholderSith::Json(serde_json::to_string(&sith_clauses).unwrap_or_default())
583                }
584            }
585            TholderThold::Integer(n) => TholderSith::HexString(format!("{:x}", n)),
586        }
587    }
588
589    /// Returns JSON serialization of sith expression
590    pub fn json(&self) -> String {
591        match &self.sith() {
592            TholderSith::Json(json_str) => json_str.clone(), // Return the JSON string directly
593            other => serde_json::to_string(other).unwrap_or_default(), // Serialize other types
594        }
595    }
596
597    /// Returns the numeric threshold value if not weighted
598    pub fn num(&self) -> Option<usize> {
599        if !self._weighted {
600            if let TholderThold::Integer(n) = self._thold {
601                return Some(n);
602            }
603        }
604        None
605    }
606
607    // Process unweighted (numeric) threshold
608    fn process_unweighted(&mut self, thold: usize) -> Result<(), MatterError> {
609        if thold == 0 {
610            // Special case for zero threshold (allowed for next threshold)
611            self._weighted = false;
612            self._size = thold;
613            self._sith = TholderSith::Integer(thold);
614            self._thold = TholderThold::Integer(thold);
615            self._bexter = None;
616            self._number = Some(Number::from_numh(format!("{:x}", thold).as_str())?);
617
618            Ok(())
619        } else {
620            self._weighted = false;
621            self._size = thold;
622            self._sith = TholderSith::Integer(thold);
623            self._thold = TholderThold::Integer(thold);
624            self._bexter = None;
625            self._number = Some(Number::from_numh(format!("{:x}", thold).as_str())?);
626
627            Ok(())
628        }
629    }
630
631    /// Process weighted threshold
632    fn process_weighted(&mut self, thold: Vec<Vec<WeightSpec>>) -> Result<(), MatterError> {
633        // Validate threshold clauses
634        for clause in &thold {
635            // Validate that sum of top-level weights in clause must be >= 1
636            let mut top_weights = Vec::new();
637
638            for e in clause {
639                match e {
640                    WeightSpec::Simple(weight) => {
641                        top_weights.push(*weight);
642                    }
643                    WeightSpec::WeightedMap(key_weight, nested_weights) => {
644                        top_weights.push(*key_weight);
645
646                        // Validate that sum of nested weights must be >= 1
647                        let sum_nested: Rational32 = nested_weights.iter().sum();
648                        if sum_nested < Rational32::new(1, 1) {
649                            return Err(MatterError::ValueError(format!(
650                                "Invalid sith clause, nested clause weight sum must be >= 1. Got: {:?}",
651                                sum_nested
652                            )));
653                        }
654                    }
655                    WeightSpec::WeightedVec(nested_specs) => {
656                        // Handle nested vector case similar to Complex case
657                        let mut nested_sum = Rational32::new(0, 1);
658
659                        for nested_spec in nested_specs {
660                            if let WeightSpec::Simple(weight) = nested_spec {
661                                nested_sum = nested_sum + *weight;
662                            }
663                            // Could handle deeper nesting here if needed
664                        }
665
666                        if nested_sum < Rational32::new(1, 1) {
667                            return Err(MatterError::ValueError(format!(
668                                "Invalid sith clause, nested vec weight sum must be >= 1. Got: {:?}",
669                                nested_sum
670                            )));
671                        }
672
673                        // Add a weight for this nested vector (could be a parameter)
674                        top_weights.push(Rational32::new(1, 1));
675                    }
676                }
677            }
678
679            // Validate top level sum
680            let sum_top: Rational32 = top_weights.iter().sum();
681            if sum_top < Rational32::new(1, 1) {
682                return Err(MatterError::ValueError(format!(
683                    "Invalid sith clause, top level weight sum must be >= 1. Got: {:?}",
684                    sum_top
685                )));
686            }
687        }
688
689        // Calculate size based on weighted threshold
690        let mut size = 0;
691        for clause in &thold {
692            for e in clause {
693                match e {
694                    WeightSpec::Simple(_) => {
695                        size += 1;
696                    }
697                    WeightSpec::WeightedMap(_, nested_weights) => {
698                        size += nested_weights.len();
699                    }
700                    WeightSpec::WeightedVec(nested_specs) => {
701                        size += nested_specs.len();
702                    }
703                }
704            }
705        }
706
707        // Create bexter string from thold
708        let mut ta = Vec::new(); // List of clauses
709
710        for clause in &thold {
711            let mut bc = Vec::new(); // List of elements in current clause
712
713            for e in clause {
714                match e {
715                    WeightSpec::Simple(weight) => {
716                        // Format simple weight
717                        let w_str =
718                            if *weight > Rational32::new(0, 1) && *weight < Rational32::new(1, 1) {
719                                format!("{}s{}", weight.numer(), weight.denom())
720                            } else {
721                                format!("{}", weight.numer() / weight.denom())
722                            };
723
724                        bc.push(w_str);
725                    }
726                    WeightSpec::WeightedMap(key_weight, nested_weights) => {
727                        // Format key weight
728                        let k = if *key_weight > Rational32::new(0, 1)
729                            && *key_weight < Rational32::new(1, 1)
730                        {
731                            format!("{}s{}", key_weight.numer(), key_weight.denom())
732                        } else {
733                            format!("{}", key_weight.numer() / key_weight.denom())
734                        };
735
736                        // Format nested weights joined by 'v'
737                        let v = nested_weights
738                            .iter()
739                            .map(|f| {
740                                if *f > Rational32::new(0, 1) && *f < Rational32::new(1, 1) {
741                                    format!("{}s{}", f.numer(), f.denom())
742                                } else {
743                                    format!("{}", f.numer() / f.denom())
744                                }
745                            })
746                            .collect::<Vec<String>>()
747                            .join("v");
748
749                        // Join key and values with 'k'
750                        let kv = format!("{}k{}", k, v);
751                        bc.push(kv);
752                    }
753                    WeightSpec::WeightedVec(_nested_specs) => {
754                        // Handle nested vectors similar to WeightedMap
755                        // This would be more complex and depends on how you want to represent
756                        // nested vectors in the bexter format
757                        // For simplicity, just adding a placeholder
758                        bc.push("1".to_string()); // Placeholder
759                    }
760                }
761            }
762
763            ta.push(bc);
764        }
765
766        // Join clauses with 'a' and elements with 'c'
767        let bext = ta
768            .iter()
769            .map(|bc| bc.join("c"))
770            .collect::<Vec<String>>()
771            .join("a");
772
773        // Create Bexter from bext
774        let bexter = Bexter::from_bext(bext.as_bytes())?;
775
776        // Update Tholder attributes
777        self._weighted = true;
778        self._size = size;
779
780        // Set the appropriate sith based on number of clauses
781        self._sith = if thold.len() == 1 {
782            // Single clause - convert to simple weights
783            let mut weight_elements = Vec::new();
784            for element in &thold[0] {
785                match element {
786                    WeightSpec::Simple(weight) => {
787                        let weight_str =
788                            if *weight > Rational32::new(0, 1) && *weight < Rational32::new(1, 1) {
789                                format!("{}/{}", weight.numer(), weight.denom())
790                            } else {
791                                format!("{}", weight.numer() / weight.denom())
792                            };
793                        weight_elements.push(WeightedSithElement::Simple(weight_str));
794                    }
795                    WeightSpec::WeightedMap(key_weight, nested_weights) => {
796                        let key_str = if *key_weight > Rational32::new(0, 1)
797                            && *key_weight < Rational32::new(1, 1)
798                        {
799                            format!("{}/{}", key_weight.numer(), key_weight.denom())
800                        } else {
801                            format!("{}", key_weight.numer() / key_weight.denom())
802                        };
803
804                        let value_elements: Vec<WeightedSithElement> = nested_weights
805                            .iter()
806                            .map(|w| {
807                                let weight_str =
808                                    if *w > Rational32::new(0, 1) && *w < Rational32::new(1, 1) {
809                                        format!("{}/{}", w.numer(), w.denom())
810                                    } else {
811                                        format!("{}", w.numer() / w.denom())
812                                    };
813                                WeightedSithElement::Simple(weight_str)
814                            })
815                            .collect();
816
817                        let mut map = HashMap::new();
818                        map.insert(key_str, value_elements);
819                        weight_elements.push(WeightedSithElement::Complex(map));
820                    }
821                    WeightSpec::WeightedVec(_) => {
822                        // Handle nested vector case
823                    }
824                }
825            }
826            TholderSith::Weights(weight_elements)
827        } else {
828            // Multiple clauses - convert to nested JSON
829            let mut sith_clauses = Vec::new();
830
831            for clause in &thold {
832                let mut sith_clause = Vec::new();
833
834                for element in clause {
835                    match element {
836                        WeightSpec::Simple(weight) => {
837                            let weight_str = if *weight > Rational32::new(0, 1)
838                                && *weight < Rational32::new(1, 1)
839                            {
840                                format!("{}/{}", weight.numer(), weight.denom())
841                            } else {
842                                format!("{}", weight.numer() / weight.denom())
843                            };
844                            sith_clause.push(WeightedSithElement::Simple(weight_str));
845                        }
846                        WeightSpec::WeightedMap(key_weight, nested_weights) => {
847                            let key_str = if *key_weight > Rational32::new(0, 1)
848                                && *key_weight < Rational32::new(1, 1)
849                            {
850                                format!("{}/{}", key_weight.numer(), key_weight.denom())
851                            } else {
852                                format!("{}", key_weight.numer() / key_weight.denom())
853                            };
854
855                            let value_elements: Vec<WeightedSithElement> = nested_weights
856                                .iter()
857                                .map(|w| {
858                                    let weight_str = if *w > Rational32::new(0, 1)
859                                        && *w < Rational32::new(1, 1)
860                                    {
861                                        format!("{}/{}", w.numer(), w.denom())
862                                    } else {
863                                        format!("{}", w.numer() / w.denom())
864                                    };
865                                    WeightedSithElement::Simple(weight_str)
866                                })
867                                .collect();
868
869                            let mut map = HashMap::new();
870                            map.insert(key_str, value_elements);
871                            sith_clause.push(WeightedSithElement::Complex(map));
872                        }
873                        WeightSpec::WeightedVec(_) => {
874                            // Handle nested vector case
875                        }
876                    }
877                }
878
879                sith_clauses.push(sith_clause);
880            }
881
882            TholderSith::Json(serde_json::to_string(&sith_clauses).unwrap_or_default())
883        };
884
885        self._thold = TholderThold::Weighted(thold);
886        self._bexter = Some(bexter);
887        self._number = None;
888
889        Ok(())
890    }
891
892    /// Add the missing ValueError to the MatterError enum
893    #[allow(missing_docs)]
894    pub fn weight(weight_str: &str) -> Result<Rational32, MatterError> {
895        // Handle empty string case
896        if weight_str.is_empty() {
897            return Err(MatterError::ParseError("Empty weight string".to_string()));
898        }
899
900        // First try to parse as float to detect float strings (which should be rejected)
901        if let Ok(float_val) = weight_str.parse::<f64>() {
902            let int_val = float_val as i32;
903            if (float_val - int_val as f64).abs() > f64::EPSILON {
904                return Err(MatterError::WeightError(format!(
905                    "Invalid weight str got float w={}.",
906                    weight_str
907                )));
908            }
909            // It's actually an integer, continue with integer parsing
910        }
911
912        // Try integer parsing first
913        if let Ok(int_val) = weight_str.parse::<i32>() {
914            if int_val < 0 || int_val > 1 {
915                return Err(MatterError::WeightError(format!(
916                    "Invalid weight not 0 <= {} <= 1.",
917                    int_val
918                )));
919            }
920            return Ok(Rational32::new(int_val, 1));
921        }
922
923        // Try fraction parsing
924        if let Some(idx) = weight_str.find('/') {
925            let numerator_str = &weight_str[0..idx];
926            let denominator_str = &weight_str[idx + 1..];
927
928            match (numerator_str.parse::<i32>(), denominator_str.parse::<i32>()) {
929                (Ok(num), Ok(denom)) => {
930                    if denom <= 0 {
931                        return Err(MatterError::WeightError(format!(
932                            "Denominator must be positive, got: {}",
933                            denom
934                        )));
935                    }
936
937                    let rational = Rational32::new(num, denom);
938                    if rational < Rational32::new(0, 1) || rational > Rational32::new(1, 1) {
939                        return Err(MatterError::WeightError(format!(
940                            "Invalid weight not 0 <= {} <= 1.",
941                            rational
942                        )));
943                    }
944                    Ok(rational)
945                }
946                _ => Err(MatterError::ParseError(format!(
947                    "Failed to parse rational number: {}",
948                    weight_str
949                ))),
950            }
951        } else {
952            Err(MatterError::ParseError(format!(
953                "Invalid weight format: {}",
954                weight_str
955            )))
956        }
957    }
958}
959
960impl fmt::Display for Tholder {
961    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
962        write!(
963            f,
964            "Tholder(weighted={}, size={})",
965            self._weighted, self._size
966        )
967    }
968}
969
970#[cfg(test)]
971mod tests {
972    use super::*;
973
974    #[test]
975    fn test_tholder_empty_material_error() {
976        // Test that creating a Tholder with no arguments raises EmptyMaterialError
977        let result = Tholder::new(None, None, None);
978        assert!(result.is_err());
979        if let Err(MatterError::EmptyMaterialError(_)) = result {
980            // Expected error type
981        } else {
982            panic!("Expected EmptyMaterialError, got: {:?}", result);
983        }
984    }
985
986    #[test]
987    fn test_tholder_validation_errors() {
988        // Test negative integer - should fail validation
989        let result = Tholder::new(None, None, Some(TholderSith::Integer(usize::MAX))); // This will wrap, simulating negative
990                                                                                       // Note: In Rust, usize can't be negative, but we can test other invalid values
991
992        // Test invalid JSON with integers instead of strings for weights
993        let json_str1 = r#"[1]"#;
994        let weights_result1: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str1);
995        if weights_result1.is_ok() {
996            let weights1 = weights_result1.unwrap();
997            let result1 = Tholder::new(None, None, Some(TholderSith::Weights(weights1)));
998            assert!(result1.is_err(), "Should fail with integer weight");
999        }
1000
1001        let json_str2 = r#"[2]"#;
1002        let weights_result2: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str2);
1003        if weights_result2.is_ok() {
1004            let weights2 = weights_result2.unwrap();
1005            let result2 = Tholder::new(None, None, Some(TholderSith::Weights(weights2)));
1006            assert!(result2.is_err(), "Should fail with integer weight");
1007        }
1008
1009        // Test weights > 1 - should fail validation
1010        let json_str3 = r#"["2"]"#;
1011        let weights_result3: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str3);
1012        if weights_result3.is_ok() {
1013            let weights3 = weights_result3.unwrap();
1014            let result3 = Tholder::new(None, None, Some(TholderSith::Weights(weights3)));
1015            assert!(result3.is_err(), "Should fail with weight > 1");
1016        }
1017
1018        // Test float weights - should fail validation
1019        let json_str4 = r#"["0.5", "0.5"]"#;
1020        let weights_result4: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str4);
1021        if weights_result4.is_ok() {
1022            let weights4 = weights_result4.unwrap();
1023            let result4 = Tholder::new(None, None, Some(TholderSith::Weights(weights4)));
1024            assert!(result4.is_err(), "Should fail with float weights");
1025        }
1026
1027        // Test non-integer string for unweighted
1028        let result5 = Tholder::new(None, None, Some(TholderSith::HexString("1.0".to_string())));
1029        assert!(
1030            result5.is_err(),
1031            "Should fail with float string for unweighted"
1032        );
1033
1034        let result6 = Tholder::new(None, None, Some(TholderSith::HexString("0.5".to_string())));
1035        assert!(
1036            result6.is_err(),
1037            "Should fail with float string for unweighted"
1038        );
1039
1040        // Test ratio of floats
1041        let result7 = Tholder::new(
1042            None,
1043            None,
1044            Some(TholderSith::HexString("1.0/2.0".to_string())),
1045        );
1046        assert!(result7.is_err(), "Should fail with float ratio");
1047
1048        // Test empty array
1049        let empty_weights: Vec<WeightedSithElement> = vec![];
1050        let result8 = Tholder::new(None, None, Some(TholderSith::Weights(empty_weights)));
1051        assert!(result8.is_err(), "Should fail with empty weights array");
1052    }
1053
1054    #[test]
1055    fn test_tholder_weighted_validation_errors() {
1056        // Test mixed array with empty element
1057        let json_str1 = r#"["1/3", "1/2", []]"#;
1058        let weights_result1: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str1);
1059
1060        // JSON parsing will succeed, but Tholder creation should fail
1061        assert!(weights_result1.is_ok(), "JSON parsing should succeed");
1062        let weights1 = weights_result1.unwrap();
1063        let result1 = Tholder::new(None, None, Some(TholderSith::Weights(weights1)));
1064        assert!(
1065            result1.is_err(),
1066            "Should fail with mixed array containing empty element"
1067        );
1068
1069        // Test insufficient total weight
1070        let json_str2 = r#"["1/3", "1/2"]"#;
1071        let weights_result2: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str2);
1072        if weights_result2.is_ok() {
1073            let weights2 = weights_result2.unwrap();
1074            let result2 = Tholder::new(None, None, Some(TholderSith::Weights(weights2)));
1075            // This might be allowed in some implementations, but should be tested
1076            // assert!(result2.is_err(), "Should fail with insufficient total weight");
1077        }
1078
1079        // Test nested empty arrays
1080        let json_str3 = r#"[[], []]"#;
1081        let weights_result3: Result<Vec<Vec<WeightedSithElement>>, _> =
1082            serde_json::from_str(json_str3);
1083        if weights_result3.is_ok() {
1084            // Convert to single array format for testing
1085            let nested_weights = weights_result3.unwrap();
1086            let flat_weights: Vec<WeightedSithElement> =
1087                nested_weights.into_iter().flatten().collect();
1088            let result3 = Tholder::new(None, None, Some(TholderSith::Weights(flat_weights)));
1089            assert!(result3.is_err(), "Should fail with empty nested arrays");
1090        }
1091
1092        // Test weight > 1 in fraction form
1093        let json_str4 = r#"["1/2", "1/2", "3/2"]"#;
1094        let weights_result4: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str4);
1095        if weights_result4.is_ok() {
1096            let weights4 = weights_result4.unwrap();
1097            let result4 = Tholder::new(None, None, Some(TholderSith::Weights(weights4)));
1098            assert!(result4.is_err(), "Should fail with weight > 1 (3/2)");
1099        }
1100
1101        // Test weight > 1 in another fraction form
1102        let json_str5 = r#"["1/2", "1/2", "2/1"]"#;
1103        let weights_result5: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str5);
1104        if weights_result5.is_ok() {
1105            let weights5 = weights_result5.unwrap();
1106            let result5 = Tholder::new(None, None, Some(TholderSith::Weights(weights5)));
1107            assert!(result5.is_err(), "Should fail with weight > 1 (2/1)");
1108        }
1109
1110        // Test integer weight > 1
1111        let json_str6 = r#"["1/2", "1/2", "2"]"#;
1112        let weights_result6: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str6);
1113        if weights_result6.is_ok() {
1114            let weights6 = weights_result6.unwrap();
1115            let result6 = Tholder::new(None, None, Some(TholderSith::Weights(weights6)));
1116            assert!(result6.is_err(), "Should fail with integer weight > 1");
1117        }
1118    }
1119
1120    #[test]
1121    fn test_tholder_nested_validation_errors() {
1122        // Test nested arrays with invalid weights
1123        let json_str1 = r#"[["1/2", "1/2", "3/2"]]"#;
1124        let weights_result1: Result<Vec<Vec<WeightedSithElement>>, _> =
1125            serde_json::from_str(json_str1);
1126        if weights_result1.is_ok() {
1127            let nested_weights = weights_result1.unwrap();
1128            let flat_weights: Vec<WeightedSithElement> =
1129                nested_weights.into_iter().flatten().collect();
1130            let result1 = Tholder::new(None, None, Some(TholderSith::Weights(flat_weights)));
1131            assert!(result1.is_err(), "Should fail with nested weight > 1");
1132        }
1133
1134        // Test mixed nested structure with integer
1135        let json_str2 = r#"[["1/2", "1/2"], "1"]"#;
1136        let weights_result2: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str2);
1137        if weights_result2.is_ok() {
1138            let weights2 = weights_result2.unwrap();
1139            let result2 = Tholder::new(None, None, Some(TholderSith::Weights(weights2)));
1140            // This tests mixing of nested arrays with simple strings
1141            // The validation should catch this inconsistency
1142        }
1143
1144        // Test float in mixed structure
1145        let json_str3 = r#"[["1/2", "1/2"], "1.0"]"#;
1146        let weights_result3: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str3);
1147        if weights_result3.is_ok() {
1148            let weights3 = weights_result3.unwrap();
1149            let result3 = Tholder::new(None, None, Some(TholderSith::Weights(weights3)));
1150            assert!(
1151                result3.is_err(),
1152                "Should fail with float in mixed structure"
1153            );
1154        }
1155
1156        // Test empty array in mixed structure
1157        let json_str4 = r#"["1/2", "1/2", []]"#;
1158        let weights_result4: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str4);
1159        if weights_result4.is_ok() {
1160            let weights4 = weights_result4.unwrap();
1161            let result4 = Tholder::new(None, None, Some(TholderSith::Weights(weights4)));
1162            assert!(
1163                result4.is_err(),
1164                "Should fail with empty array in mixed structure"
1165            );
1166        }
1167    }
1168
1169    #[test]
1170    fn test_tholder_unweighted_valid_case() {
1171        // Test that sith=2 creates a valid unweighted threshold
1172        let tholder = Tholder::new(None, None, Some(TholderSith::Integer(2))).unwrap();
1173        assert!(!tholder.weighted());
1174        assert_eq!(tholder.num().unwrap(), 2);
1175
1176        let TholderThold::Integer(thold) = tholder.thold() else {
1177            panic!("Expected integer threshold");
1178        };
1179        assert_eq!(*thold, 2);
1180    }
1181
1182    #[test]
1183    fn test_tholder_unweighted() {
1184        // Expected limen value
1185        let expected_limen = b"MAAL";
1186
1187        // Create a Tholder with hex string "b" (which is 11 in decimal)
1188        let mut tholder = Tholder::default();
1189        tholder
1190            .process_sith(TholderSith::HexString("b".to_string()))
1191            .unwrap();
1192
1193        // Check all properties and behaviors
1194        assert!(!tholder.weighted());
1195
1196        let TholderThold::Integer(thold) = tholder.thold() else {
1197            panic!("Invalid threshold")
1198        };
1199        assert_eq!(tholder.size(), *thold);
1200        assert_eq!(*thold, 11);
1201        assert_eq!(tholder.limen(), expected_limen);
1202
1203        let TholderSith::HexString(sith) = tholder.sith() else {
1204            panic!("Invalid sith")
1205        };
1206        assert_eq!(sith, "b");
1207        assert_eq!(tholder.json(), "\"b\"");
1208        assert_eq!(tholder.num().unwrap(), 11);
1209
1210        // Test satisfaction with insufficient indices
1211        let insufficient_indices = vec![0, 1, 2];
1212        assert!(!tholder.satisfy(&insufficient_indices));
1213
1214        // Test satisfaction with sufficient indices
1215        let sufficient_indices: Vec<usize> = (0..*thold).collect();
1216        assert!(tholder.satisfy(&sufficient_indices));
1217    }
1218
1219    #[test]
1220    fn test_tholder_integer_sith() {
1221        // Test Tholder(sith=11) - equivalent to hex "b"
1222        let expected_limen = b"MAAL";
1223        let tholder = Tholder::new(None, None, Some(TholderSith::Integer(11))).unwrap();
1224
1225        assert!(!tholder.weighted());
1226
1227        let TholderThold::Integer(thold) = tholder.thold() else {
1228            panic!("Invalid threshold")
1229        };
1230        assert_eq!(tholder.size(), *thold);
1231        assert_eq!(*thold, 11);
1232        assert_eq!(tholder.limen(), expected_limen);
1233
1234        let TholderSith::HexString(sith) = tholder.sith() else {
1235            panic!("Invalid sith")
1236        };
1237        assert_eq!(sith, "b");
1238        assert_eq!(tholder.json(), "\"b\"");
1239        assert_eq!(tholder.num().unwrap(), 11);
1240
1241        assert!(!tholder.satisfy(&[0, 1, 2]));
1242        assert!(tholder.satisfy(&(0..11).collect::<Vec<_>>()));
1243    }
1244
1245    #[test]
1246    fn test_tholder_from_limen() {
1247        // Test Tholder(limen=limen)
1248        let limen = b"MAAL";
1249        let tholder = Tholder::new(None, Some(limen.to_vec()), None).unwrap();
1250
1251        assert!(!tholder.weighted());
1252
1253        let TholderThold::Integer(thold) = tholder.thold() else {
1254            panic!("Invalid threshold")
1255        };
1256        assert_eq!(tholder.size(), *thold);
1257        assert_eq!(*thold, 11);
1258        assert_eq!(tholder.limen(), limen);
1259
1260        let TholderSith::HexString(sith) = tholder.sith() else {
1261            panic!("Invalid sith")
1262        };
1263        assert_eq!(sith, "b");
1264        assert_eq!(tholder.json(), "\"b\"");
1265        assert_eq!(tholder.num().unwrap(), 11);
1266
1267        assert!(!tholder.satisfy(&[0, 1, 2]));
1268        assert!(tholder.satisfy(&(0..11).collect::<Vec<_>>()));
1269    }
1270
1271    #[test]
1272    fn test_tholder_from_thold() {
1273        // Test Tholder(thold=11)
1274        let expected_limen = b"MAAL";
1275        let tholder = Tholder::new(Some(TholderThold::Integer(11)), None, None).unwrap();
1276
1277        assert!(!tholder.weighted());
1278
1279        let TholderThold::Integer(thold) = tholder.thold() else {
1280            panic!("Invalid threshold")
1281        };
1282        assert_eq!(tholder.size(), *thold);
1283        assert_eq!(*thold, 11);
1284        assert_eq!(tholder.limen(), expected_limen);
1285
1286        let TholderSith::HexString(sith) = tholder.sith() else {
1287            panic!("Invalid sith")
1288        };
1289        assert_eq!(sith, "b");
1290        assert_eq!(tholder.json(), "\"b\"");
1291        assert_eq!(tholder.num().unwrap(), 11);
1292
1293        assert!(!tholder.satisfy(&[0, 1, 2]));
1294        assert!(tholder.satisfy(&(0..11).collect::<Vec<_>>()));
1295    }
1296
1297    #[test]
1298    fn test_tholder_hex_f() {
1299        // Test Tholder(sith=f'{15:x}') which would be "f"
1300        let expected_limen = b"MAAP";
1301        let tholder =
1302            Tholder::new(None, None, Some(TholderSith::HexString("f".to_string()))).unwrap();
1303
1304        assert!(!tholder.weighted());
1305
1306        let TholderThold::Integer(thold) = tholder.thold() else {
1307            panic!("Invalid threshold")
1308        };
1309        assert_eq!(tholder.size(), *thold);
1310        assert_eq!(*thold, 15);
1311        assert_eq!(tholder.limen(), expected_limen);
1312
1313        let TholderSith::HexString(sith) = tholder.sith() else {
1314            panic!("Invalid sith")
1315        };
1316        assert_eq!(sith, "f");
1317        assert_eq!(tholder.json(), "\"f\"");
1318        assert_eq!(tholder.num().unwrap(), 15);
1319
1320        assert!(!tholder.satisfy(&[0, 1, 2]));
1321        assert!(tholder.satisfy(&(0..15).collect::<Vec<_>>()));
1322    }
1323
1324    #[test]
1325    fn test_tholder_integer_2() {
1326        // Test Tholder(sith=2)
1327        let expected_limen = b"MAAC";
1328        let tholder = Tholder::new(None, None, Some(TholderSith::Integer(2))).unwrap();
1329
1330        assert!(!tholder.weighted());
1331
1332        let TholderThold::Integer(thold) = tholder.thold() else {
1333            panic!("Invalid threshold")
1334        };
1335        assert_eq!(tholder.size(), *thold);
1336        assert_eq!(*thold, 2);
1337        assert_eq!(tholder.limen(), expected_limen);
1338
1339        let TholderSith::HexString(sith) = tholder.sith() else {
1340            panic!("Invalid sith")
1341        };
1342        assert_eq!(sith, "2");
1343        assert_eq!(tholder.json(), "\"2\"");
1344        assert_eq!(tholder.num().unwrap(), 2);
1345
1346        assert!(tholder.satisfy(&[0, 1, 2])); // More than needed
1347        assert!(tholder.satisfy(&(0..2).collect::<Vec<_>>())); // Exactly needed
1348    }
1349
1350    #[test]
1351    fn test_tholder_integer_1() {
1352        // Test Tholder(sith=1)
1353        let expected_limen = b"MAAB";
1354        let tholder = Tholder::new(None, None, Some(TholderSith::Integer(1))).unwrap();
1355
1356        assert!(!tholder.weighted());
1357
1358        let TholderThold::Integer(thold) = tholder.thold() else {
1359            panic!("Invalid threshold")
1360        };
1361        assert_eq!(tholder.size(), *thold);
1362        assert_eq!(*thold, 1);
1363        assert_eq!(tholder.limen(), expected_limen);
1364
1365        let TholderSith::HexString(sith) = tholder.sith() else {
1366            panic!("Invalid sith")
1367        };
1368        assert_eq!(sith, "1");
1369        assert_eq!(tholder.json(), "\"1\"");
1370        assert_eq!(tholder.num().unwrap(), 1);
1371
1372        assert!(tholder.satisfy(&[0])); // Single index
1373        assert!(tholder.satisfy(&(0..1).collect::<Vec<_>>())); // Exactly needed
1374    }
1375
1376    #[test]
1377    fn test_deserialize_weighted_sith_elements() -> Result<(), Box<dyn std::error::Error>> {
1378        // Test case 1: Simple array of fraction strings
1379        let json_str1 = r#"["1/2", "1/2", "1/4", "1/4", "1/4"]"#;
1380        let elements1: Vec<WeightedSithElement> = serde_json::from_str(json_str1)?;
1381
1382        assert_eq!(elements1.len(), 5);
1383        if let WeightedSithElement::Simple(val) = &elements1[0] {
1384            assert_eq!(val, "1/2");
1385        } else {
1386            panic!("Expected Simple element");
1387        }
1388
1389        // Test case 2: Nested arrays of weights
1390        let json_str2 = r#"[["1/2", "1/2", "1/4", "1/4", "1/4"], ["1", "1"]]"#;
1391        let elements2: Vec<Vec<WeightedSithElement>> = serde_json::from_str(json_str2)?;
1392
1393        assert_eq!(elements2.len(), 2);
1394        assert_eq!(elements2[0].len(), 5);
1395        assert_eq!(elements2[1].len(), 2);
1396
1397        if let WeightedSithElement::Simple(val) = &elements2[0][0] {
1398            assert_eq!(val, "1/2");
1399        } else {
1400            panic!("Expected Simple element");
1401        }
1402
1403        if let WeightedSithElement::Simple(val) = &elements2[1][0] {
1404            assert_eq!(val, "1");
1405        } else {
1406            panic!("Expected Simple element");
1407        }
1408
1409        // Test case 3: Mixed simple and complex elements
1410        let json_str3 = r#"[{"1/3":["1/2", "1/2", "1/2"]}, "1/3", "1/2", {"1/2": ["1", "1"]}]"#;
1411        let elements3: Vec<WeightedSithElement> = serde_json::from_str(json_str3)?;
1412
1413        assert_eq!(elements3.len(), 4);
1414
1415        // First element should be a Complex with "1/3" key
1416        match &elements3[0] {
1417            WeightedSithElement::Complex(map) => {
1418                assert_eq!(map.len(), 1);
1419                let values = map.get("1/3").expect("Key 1/3 should exist");
1420                assert_eq!(values.len(), 3);
1421
1422                if let WeightedSithElement::Simple(val) = &values[0] {
1423                    assert_eq!(val, "1/2");
1424                } else {
1425                    panic!("Expected Simple element in complex map");
1426                }
1427            }
1428            _ => panic!("Expected Complex element"),
1429        }
1430
1431        // Second element should be a Simple "1/3"
1432        if let WeightedSithElement::Simple(val) = &elements3[1] {
1433            assert_eq!(val, "1/3");
1434        } else {
1435            panic!("Expected Simple element");
1436        }
1437
1438        // Third element should be a Simple "1/2"
1439        if let WeightedSithElement::Simple(val) = &elements3[2] {
1440            assert_eq!(val, "1/2");
1441        } else {
1442            panic!("Expected Simple element");
1443        }
1444
1445        // Fourth element should be a Complex with "1/2" key
1446        match &elements3[3] {
1447            WeightedSithElement::Complex(map) => {
1448                assert_eq!(map.len(), 1);
1449                let values = map.get("1/2").expect("Key 1/2 should exist");
1450                assert_eq!(values.len(), 2);
1451
1452                if let WeightedSithElement::Simple(val) = &values[0] {
1453                    assert_eq!(val, "1");
1454                } else {
1455                    panic!("Expected Simple element in complex map");
1456                }
1457            }
1458            _ => panic!("Expected Complex element"),
1459        }
1460
1461        // Test case 4: Deeply nested structure with mixed types
1462        let json_str4 = r#"[[{"1/3":["1/2", "1/2", "1/2"]}, "1/2", {"1/2": ["1", "1"]}], ["1/2", {"1/2": ["1", "1"]}]]"#;
1463        let elements4: Vec<Vec<WeightedSithElement>> = serde_json::from_str(json_str4)?;
1464
1465        assert_eq!(elements4.len(), 2);
1466        assert_eq!(elements4[0].len(), 3);
1467        assert_eq!(elements4[1].len(), 2);
1468
1469        // First element of first array should be a Complex with "1/3" key
1470        match &elements4[0][0] {
1471            WeightedSithElement::Complex(map) => {
1472                assert_eq!(map.len(), 1);
1473                let values = map.get("1/3").expect("Key 1/3 should exist");
1474                assert_eq!(values.len(), 3);
1475
1476                if let WeightedSithElement::Simple(val) = &values[0] {
1477                    assert_eq!(val, "1/2");
1478                } else {
1479                    panic!("Expected Simple element in complex map");
1480                }
1481            }
1482            _ => panic!("Expected Complex element"),
1483        }
1484
1485        // Second element of first array should be a Simple "1/2"
1486        if let WeightedSithElement::Simple(val) = &elements4[0][1] {
1487            assert_eq!(val, "1/2");
1488        } else {
1489            panic!("Expected Simple element");
1490        }
1491
1492        // Last element of second array should be a Complex with "1/2" key
1493        match &elements4[1][1] {
1494            WeightedSithElement::Complex(map) => {
1495                assert_eq!(map.len(), 1);
1496                let values = map.get("1/2").expect("Key 1/2 should exist");
1497                assert_eq!(values.len(), 2);
1498
1499                if let WeightedSithElement::Simple(val) = &values[0] {
1500                    assert_eq!(val, "1");
1501                } else {
1502                    panic!("Expected Simple element in complex map");
1503                }
1504            }
1505            _ => panic!("Expected Complex element"),
1506        }
1507
1508        // Additional test: validate we can parse nested Array elements
1509        let json_str5 = r#"["1/2", ["1/3", "1/3", "1/3"], "1/4"]"#;
1510        let elements5: Vec<WeightedSithElement> = serde_json::from_str(json_str5)?;
1511
1512        assert_eq!(elements5.len(), 3);
1513
1514        // Second element should be an Array
1515        match &elements5[1] {
1516            WeightedSithElement::Array(arr) => {
1517                assert_eq!(arr.len(), 3);
1518                if let WeightedSithElement::Simple(val) = &arr[0] {
1519                    assert_eq!(val, "1/3");
1520                } else {
1521                    panic!("Expected Simple element in array");
1522                }
1523            }
1524            _ => panic!("Expected Array element"),
1525        }
1526
1527        // Verify weight parsing works for these elements
1528        if let WeightedSithElement::Simple(val) = &elements1[0] {
1529            let weight = Tholder::weight(val)?;
1530            assert_eq!(weight, Rational32::new(1, 2));
1531        }
1532
1533        Ok(())
1534    }
1535
1536    #[test]
1537    fn test_deserialize_json_bytes() -> Result<(), Box<dyn std::error::Error>> {
1538        // Test deserializing from JSON bytes
1539        let json_bytes = br#"["1/2", "1/2", "1/4", "1/4", "1/4"]"#;
1540        let elements: Vec<WeightedSithElement> = serde_json::from_slice(json_bytes)?;
1541
1542        assert_eq!(elements.len(), 5);
1543        if let WeightedSithElement::Simple(val) = &elements[0] {
1544            assert_eq!(val, "1/2");
1545            let weight = Tholder::weight(val)?;
1546            assert_eq!(weight, Rational32::new(1, 2));
1547        } else {
1548            panic!("Expected Simple element");
1549        }
1550
1551        // Test more complex structure from bytes
1552        let complex_json_bytes =
1553            br#"[{"1/3":["1/2", "1/2", "1/2"]}, "1/3", "1/2", {"1/2": ["1", "1"]}]"#;
1554        let complex_elements: Vec<WeightedSithElement> =
1555            serde_json::from_slice(complex_json_bytes)?;
1556
1557        assert_eq!(complex_elements.len(), 4);
1558
1559        // Verify the "1/3" key exists in the first element
1560        match &complex_elements[0] {
1561            WeightedSithElement::Complex(map) => {
1562                assert!(map.contains_key("1/3"));
1563                let values = map.get("1/3").unwrap();
1564                assert_eq!(values.len(), 3);
1565            }
1566            _ => panic!("Expected Complex element"),
1567        }
1568
1569        Ok(())
1570    }
1571
1572    // Optional: Add a helper to demonstrate a real world usage scenario
1573    #[test]
1574    fn test_process_weighted_sith() -> Result<(), Box<dyn std::error::Error>> {
1575        // This test simulates how these deserializations might be used in a real application
1576
1577        let json_str = r#"["1/2", "1/2", "1/4", "1/4", "1/4"]"#;
1578        let elements: Vec<WeightedSithElement> = serde_json::from_str(json_str)?;
1579
1580        // Calculate total weight (in a real application this might determine if a threshold is met)
1581        let mut total_weight = Rational32::new(0, 1);
1582
1583        for element in &elements {
1584            if let WeightedSithElement::Simple(val) = element {
1585                total_weight = total_weight + Tholder::weight(val)?;
1586            }
1587        }
1588
1589        // Verify the total weight is greater than 1 (which would satisfy a threshold in a real app)
1590        assert!(total_weight > Rational32::new(1, 1));
1591        assert_eq!(total_weight, Rational32::new(7, 4)); // 1/2 + 1/2 + 1/4 + 1/4 + 1/4 = 7/4
1592
1593        Ok(())
1594    }
1595
1596    // TODO: Add a test for Tholder::satisfy_indices()
1597    // #[test]
1598    fn test_tholder_weighted() -> Result<(), Box<dyn std::error::Error>> {
1599        // Create string array of weighted thresholds
1600        let json_str = r#"["1/2", "1/2", "1/4", "1/4", "1/4"]"#;
1601        let weights: Vec<WeightedSithElement> = serde_json::from_str(json_str)?;
1602
1603        // Create Tholder with weighted threshold
1604        let tholder = Tholder::new(None, None, Some(TholderSith::Weights(weights)))?;
1605
1606        // Verify the weighted flag
1607        assert!(tholder.weighted());
1608        assert_eq!(tholder.size(), 5);
1609
1610        // Verify the parsed threshold structure
1611        if let TholderThold::Weighted(clauses) = tholder.thold() {
1612            // There should be one clause with 5 elements
1613            assert_eq!(clauses.len(), 1);
1614            assert_eq!(clauses[0].len(), 5);
1615
1616            // Check the fraction values
1617            if let WeightSpec::Simple(fraction) = clauses[0][0] {
1618                assert_eq!(fraction, Rational32::new(1, 2));
1619            } else {
1620                panic!("Expected Simple weight spec for first element");
1621            }
1622
1623            if let WeightSpec::Simple(fraction) = clauses[0][1] {
1624                assert_eq!(fraction, Rational32::new(1, 2));
1625            } else {
1626                panic!("Expected Simple weight spec for second element");
1627            }
1628
1629            if let WeightSpec::Simple(fraction) = clauses[0][2] {
1630                assert_eq!(fraction, Rational32::new(1, 4));
1631            } else {
1632                panic!("Expected Simple weight spec for third element");
1633            }
1634        } else {
1635            panic!("Expected Weighted threshold type");
1636        }
1637
1638        // Check the serialized limen
1639        assert_eq!(tholder.limen(), b"4AAFA1s2c1s2c1s4c1s4c1s4");
1640
1641        // Verify sith representation
1642        // Note: This requires a properly implemented sith() method for weighted thresholds
1643        if let TholderSith::Weights(weights) = tholder.sith() {
1644            assert_eq!(weights.len(), 5);
1645            if let WeightedSithElement::Simple(s) = &weights[0] {
1646                assert_eq!(s, "1/2");
1647            } else {
1648                panic!("Expected Simple weight element");
1649            }
1650        } else {
1651            panic!("Expected Weights sith type");
1652        }
1653
1654        // Verify JSON representation matches the input
1655        // This should return a JSON string representation of the threshold
1656        let expected_json = r#"["1/2","1/2","1/4","1/4","1/4"]"#;
1657        assert_eq!(tholder.json(), expected_json);
1658
1659        // Verify numeric threshold is None for weighted thresholds
1660        assert_eq!(tholder.num(), None);
1661
1662        // Now test the satisfy method with various signatures
1663        // This requires a functioning satisfy_weighted implementation
1664
1665        // These should all satisfy the threshold (weights sum to ≥ 1)
1666        assert!(tholder.satisfy(&[0, 2, 4])); // 1/2 + 1/4 + 1/4 = 1
1667        assert!(tholder.satisfy(&[0, 1])); // 1/2 + 1/2 = 1
1668        assert!(tholder.satisfy(&[1, 3, 4])); // 1/2 + 1/4 + 1/4 = 1
1669        assert!(tholder.satisfy(&[0, 1, 2, 3, 4])); // All weights
1670        assert!(tholder.satisfy(&[3, 2, 0])); // 1/4 + 1/4 + 1/2 = 1
1671        assert!(tholder.satisfy(&[0, 0, 1, 2, 1])); // Duplicates should be ignored in calculation
1672
1673        // These should not satisfy the threshold
1674        assert!(!tholder.satisfy(&[0, 2])); // 1/2 + 1/4 = 3/4 < 1
1675        assert!(!tholder.satisfy(&[2, 3, 4])); // 1/4 + 1/4 + 1/4 = 3/4 < 1
1676
1677        Ok(())
1678    }
1679    #[test]
1680    fn test_tholder_weighted_simple() -> Result<(), Box<dyn std::error::Error>> {
1681        // Test Tholder(sith=["1/2", "1/2", "1/4", "1/4", "1/4"])
1682        let json_str = r#"["1/2", "1/2", "1/4", "1/4", "1/4"]"#;
1683        let weights: Vec<WeightedSithElement> = serde_json::from_str(json_str)?;
1684        let tholder = Tholder::new(None, None, Some(TholderSith::Weights(weights)))?;
1685
1686        // Verify basic properties
1687        assert!(tholder.weighted());
1688        assert_eq!(tholder.size(), 5);
1689
1690        // Verify the parsed threshold structure
1691        if let TholderThold::Weighted(clauses) = tholder.thold() {
1692            assert_eq!(clauses.len(), 1); // Single clause
1693            assert_eq!(clauses[0].len(), 5); // 5 elements
1694
1695            // Check individual fraction values
1696            if let WeightSpec::Simple(fraction) = clauses[0][0] {
1697                assert_eq!(fraction, Rational32::new(1, 2));
1698            } else {
1699                panic!("Expected Simple weight spec for first element");
1700            }
1701
1702            if let WeightSpec::Simple(fraction) = clauses[0][1] {
1703                assert_eq!(fraction, Rational32::new(1, 2));
1704            } else {
1705                panic!("Expected Simple weight spec for second element");
1706            }
1707
1708            if let WeightSpec::Simple(fraction) = clauses[0][2] {
1709                assert_eq!(fraction, Rational32::new(1, 4));
1710            } else {
1711                panic!("Expected Simple weight spec for third element");
1712            }
1713
1714            if let WeightSpec::Simple(fraction) = clauses[0][3] {
1715                assert_eq!(fraction, Rational32::new(1, 4));
1716            } else {
1717                panic!("Expected Simple weight spec for fourth element");
1718            }
1719
1720            if let WeightSpec::Simple(fraction) = clauses[0][4] {
1721                assert_eq!(fraction, Rational32::new(1, 4));
1722            } else {
1723                panic!("Expected Simple weight spec for fifth element");
1724            }
1725        } else {
1726            panic!("Expected Weighted threshold type");
1727        }
1728
1729        // Check serialized limen
1730        assert_eq!(tholder.limen(), b"4AAFA1s2c1s2c1s4c1s4c1s4");
1731
1732        // Verify sith representation
1733        if let TholderSith::Weights(weights) = tholder.sith() {
1734            assert_eq!(weights.len(), 5);
1735            if let WeightedSithElement::Simple(s) = &weights[0] {
1736                assert_eq!(s, "1/2");
1737            } else {
1738                panic!("Expected Simple weight element");
1739            }
1740            if let WeightedSithElement::Simple(s) = &weights[4] {
1741                assert_eq!(s, "1/4");
1742            } else {
1743                panic!("Expected Simple weight element");
1744            }
1745        } else {
1746            panic!("Expected Weights sith type");
1747        }
1748
1749        // Verify JSON representation
1750        let expected_json = r#"["1/2","1/2","1/4","1/4","1/4"]"#;
1751        assert_eq!(tholder.json(), expected_json);
1752
1753        // Verify numeric threshold is None for weighted thresholds
1754        assert_eq!(tholder.num(), None);
1755
1756        // Test satisfaction scenarios that should pass
1757        assert!(tholder.satisfy(&[0, 2, 4])); // 1/2 + 1/4 + 1/4 = 1
1758        assert!(tholder.satisfy(&[0, 1])); // 1/2 + 1/2 = 1
1759        assert!(tholder.satisfy(&[1, 3, 4])); // 1/2 + 1/4 + 1/4 = 1
1760        assert!(tholder.satisfy(&[0, 1, 2, 3, 4])); // All weights
1761        assert!(tholder.satisfy(&[3, 2, 0])); // 1/4 + 1/4 + 1/2 = 1
1762        assert!(tholder.satisfy(&[0, 0, 1, 2, 1])); // Duplicates should be ignored
1763
1764        // Test satisfaction scenarios that should fail
1765        assert!(!tholder.satisfy(&[0, 2])); // 1/2 + 1/4 = 3/4 < 1
1766        assert!(!tholder.satisfy(&[2, 3, 4])); // 1/4 + 1/4 + 1/4 = 3/4 < 1
1767
1768        Ok(())
1769    }
1770
1771    #[test]
1772    fn test_tholder_weighted_with_zero() -> Result<(), Box<dyn std::error::Error>> {
1773        // Test Tholder(sith=["1/2", "1/2", "1/4", "1/4", "1/4", "0"])
1774        let json_str = r#"["1/2", "1/2", "1/4", "1/4", "1/4", "0"]"#;
1775        let weights: Vec<WeightedSithElement> = serde_json::from_str(json_str)?;
1776        let tholder = Tholder::new(None, None, Some(TholderSith::Weights(weights)))?;
1777
1778        // Verify basic properties
1779        assert!(tholder.weighted());
1780        assert_eq!(tholder.size(), 6);
1781
1782        // Verify the parsed threshold structure
1783        if let TholderThold::Weighted(clauses) = tholder.thold() {
1784            assert_eq!(clauses.len(), 1); // Single clause
1785            assert_eq!(clauses[0].len(), 6); // 6 elements
1786
1787            // Check that last element is zero
1788            if let WeightSpec::Simple(fraction) = clauses[0][5] {
1789                assert_eq!(fraction, Rational32::new(0, 1));
1790            } else {
1791                panic!("Expected Simple weight spec for last element");
1792            }
1793        } else {
1794            panic!("Expected Weighted threshold type");
1795        }
1796
1797        // Check serialized limen
1798        assert_eq!(tholder.limen(), b"6AAGAAA1s2c1s2c1s4c1s4c1s4c0");
1799
1800        // Verify sith representation
1801        if let TholderSith::Weights(weights) = tholder.sith() {
1802            assert_eq!(weights.len(), 6);
1803            if let WeightedSithElement::Simple(s) = &weights[5] {
1804                assert_eq!(s, "0");
1805            } else {
1806                panic!("Expected Simple weight element");
1807            }
1808        } else {
1809            panic!("Expected Weights sith type");
1810        }
1811
1812        // Verify JSON representation
1813        let expected_json = r#"["1/2","1/2","1/4","1/4","1/4","0"]"#;
1814        assert_eq!(tholder.json(), expected_json);
1815
1816        // Verify numeric threshold is None for weighted thresholds
1817        assert_eq!(tholder.num(), None);
1818
1819        // Test satisfaction scenarios that should pass
1820        assert!(tholder.satisfy(&[0, 2, 4])); // 1/2 + 1/4 + 1/4 = 1
1821        assert!(tholder.satisfy(&[0, 1])); // 1/2 + 1/2 = 1
1822        assert!(tholder.satisfy(&[1, 3, 4])); // 1/2 + 1/4 + 1/4 = 1
1823        assert!(tholder.satisfy(&[0, 1, 2, 3, 4])); // All weights
1824        assert!(tholder.satisfy(&[3, 2, 0])); // 1/4 + 1/4 + 1/2 = 1
1825        assert!(tholder.satisfy(&[0, 0, 1, 2, 1])); // Duplicates should be ignored
1826
1827        // Test satisfaction scenarios that should fail (including zero weight)
1828        assert!(!tholder.satisfy(&[0, 2, 5])); // 1/2 + 1/4 + 0 = 3/4 < 1
1829        assert!(!tholder.satisfy(&[2, 3, 4, 5])); // 1/4 + 1/4 + 1/4 + 0 = 3/4 < 1
1830
1831        Ok(())
1832    }
1833
1834    #[test]
1835    fn test_tholder_weighted_nested_single_clause() -> Result<(), Box<dyn std::error::Error>> {
1836        // Test Tholder(sith=[["1/2", "1/2", "1/4", "1/4", "1/4"]])
1837        let json_str = r#"[["1/2", "1/2", "1/4", "1/4", "1/4"]]"#;
1838        let nested_weights: Vec<Vec<WeightedSithElement>> = serde_json::from_str(json_str)?;
1839
1840        // For nested structure, use TholderSith::Json to handle multi-clause parsing
1841        let tholder = Tholder::new(None, None, Some(TholderSith::Json(json_str.to_string())))?;
1842
1843        // Verify basic properties
1844        assert!(tholder.weighted());
1845        assert_eq!(tholder.size(), 5);
1846
1847        // Verify the parsed threshold structure
1848        if let TholderThold::Weighted(clauses) = tholder.thold() {
1849            assert_eq!(clauses.len(), 1); // Single clause
1850            assert_eq!(clauses[0].len(), 5); // 5 elements
1851
1852            // Check individual fraction values
1853            if let WeightSpec::Simple(fraction) = clauses[0][0] {
1854                assert_eq!(fraction, Rational32::new(1, 2));
1855            } else {
1856                panic!("Expected Simple weight spec for first element");
1857            }
1858
1859            if let WeightSpec::Simple(fraction) = clauses[0][1] {
1860                assert_eq!(fraction, Rational32::new(1, 2));
1861            } else {
1862                panic!("Expected Simple weight spec for second element");
1863            }
1864
1865            if let WeightSpec::Simple(fraction) = clauses[0][2] {
1866                assert_eq!(fraction, Rational32::new(1, 4));
1867            } else {
1868                panic!("Expected Simple weight spec for third element");
1869            }
1870
1871            if let WeightSpec::Simple(fraction) = clauses[0][3] {
1872                assert_eq!(fraction, Rational32::new(1, 4));
1873            } else {
1874                panic!("Expected Simple weight spec for fourth element");
1875            }
1876
1877            if let WeightSpec::Simple(fraction) = clauses[0][4] {
1878                assert_eq!(fraction, Rational32::new(1, 4));
1879            } else {
1880                panic!("Expected Simple weight spec for fifth element");
1881            }
1882        } else {
1883            panic!("Expected Weighted threshold type");
1884        }
1885
1886        // Check serialized limen
1887        assert_eq!(tholder.limen(), b"4AAFA1s2c1s2c1s4c1s4c1s4");
1888
1889        // Verify sith representation (should be flattened for single clause)
1890        if let TholderSith::Weights(weights) = tholder.sith() {
1891            assert_eq!(weights.len(), 5);
1892            if let WeightedSithElement::Simple(s) = &weights[0] {
1893                assert_eq!(s, "1/2");
1894            } else {
1895                panic!("Expected Simple weight element");
1896            }
1897        } else {
1898            panic!("Expected Weights sith type");
1899        }
1900
1901        // Verify JSON representation
1902        let expected_json = r#"["1/2","1/2","1/4","1/4","1/4"]"#;
1903        assert_eq!(tholder.json(), expected_json);
1904
1905        // Verify numeric threshold is None for weighted thresholds
1906        assert_eq!(tholder.num(), None);
1907
1908        // Test satisfaction scenarios that should pass
1909        assert!(tholder.satisfy(&[1, 2, 3])); // 1/2 + 1/4 + 1/4 = 1
1910        assert!(tholder.satisfy(&[0, 1, 2])); // 1/2 + 1/2 + 1/4 = 5/4 > 1
1911        assert!(tholder.satisfy(&[1, 3, 4])); // 1/2 + 1/4 + 1/4 = 1
1912        assert!(tholder.satisfy(&[0, 1, 2, 3, 4])); // All weights
1913        assert!(tholder.satisfy(&[3, 2, 0])); // 1/4 + 1/4 + 1/2 = 1
1914        assert!(tholder.satisfy(&[0, 0, 1, 2, 1, 4, 4])); // Duplicates should be ignored
1915
1916        // Test satisfaction scenarios that should fail
1917        assert!(!tholder.satisfy(&[0, 2])); // 1/2 + 1/4 = 3/4 < 1
1918        assert!(!tholder.satisfy(&[2, 3, 4])); // 1/4 + 1/4 + 1/4 = 3/4 < 1
1919
1920        Ok(())
1921    }
1922
1923    #[test]
1924    fn test_tholder_weighted_multi_clause() -> Result<(), Box<dyn std::error::Error>> {
1925        // Test Tholder(sith=[["1/2", "1/2", "1/4", "1/4", "1/4"], ["1/1", "1"]])
1926        let json_str = r#"[["1/2", "1/2", "1/4", "1/4", "1/4"], ["1", "1"]]"#;
1927        let nested_weights: Vec<Vec<WeightedSithElement>> = serde_json::from_str(json_str)?;
1928
1929        // For multi-clause, we need to handle this differently
1930        // Convert to a structure that represents multiple clauses
1931        let mut all_clauses = Vec::new();
1932
1933        for clause_weights in nested_weights {
1934            let mut clause_specs = Vec::new();
1935            for weight_element in clause_weights {
1936                if let WeightedSithElement::Simple(weight_str) = weight_element {
1937                    let weight = Tholder::weight(&weight_str)?;
1938                    clause_specs.push(WeightSpec::Simple(weight));
1939                }
1940            }
1941            all_clauses.push(clause_specs);
1942        }
1943
1944        let tholder = Tholder::new(Some(TholderThold::Weighted(all_clauses)), None, None)?;
1945
1946        // Verify basic properties
1947        assert!(tholder.weighted());
1948        assert_eq!(tholder.size(), 7); // 5 + 2 = 7 total elements
1949
1950        // Verify the parsed threshold structure
1951        if let TholderThold::Weighted(clauses) = tholder.thold() {
1952            assert_eq!(clauses.len(), 2); // Two clauses
1953            assert_eq!(clauses[0].len(), 5); // First clause has 5 elements
1954            assert_eq!(clauses[1].len(), 2); // Second clause has 2 elements
1955
1956            // Check first clause elements
1957            if let WeightSpec::Simple(fraction) = clauses[0][0] {
1958                assert_eq!(fraction, Rational32::new(1, 2));
1959            } else {
1960                panic!("Expected Simple weight spec");
1961            }
1962
1963            // Check second clause elements
1964            if let WeightSpec::Simple(fraction) = clauses[1][0] {
1965                assert_eq!(fraction, Rational32::new(1, 1));
1966            } else {
1967                panic!("Expected Simple weight spec");
1968            }
1969
1970            if let WeightSpec::Simple(fraction) = clauses[1][1] {
1971                assert_eq!(fraction, Rational32::new(1, 1));
1972            } else {
1973                panic!("Expected Simple weight spec");
1974            }
1975        } else {
1976            panic!("Expected Weighted threshold type");
1977        }
1978
1979        // Check serialized limen
1980        assert_eq!(tholder.limen(), b"4AAGA1s2c1s2c1s4c1s4c1s4a1c1");
1981
1982        // Verify sith representation (should be nested)
1983        if let TholderSith::Json(json_str) = tholder.sith() {
1984            let expected_nested = r#"[["1/2","1/2","1/4","1/4","1/4"],["1","1"]]"#;
1985            assert_eq!(json_str, expected_nested);
1986        } else {
1987            panic!("Expected Json sith type for multi-clause");
1988        }
1989
1990        // Verify JSON representation
1991        let expected_json = r#"[["1/2","1/2","1/4","1/4","1/4"],["1","1"]]"#;
1992        assert_eq!(tholder.json(), expected_json);
1993
1994        // Verify numeric threshold is None for weighted thresholds
1995        assert_eq!(tholder.num(), None);
1996
1997        // Test satisfaction scenarios that should pass
1998        // Both clauses must be satisfied (AND logic)
1999        assert!(tholder.satisfy(&[1, 2, 3, 5])); // First: 1/2+1/4+1/4=1, Second: 1=1 ✓
2000        assert!(tholder.satisfy(&[0, 1, 6])); // First: 1/2+1/2=1, Second: 1=1 ✓
2001
2002        // Test satisfaction scenarios that should fail
2003        assert!(!tholder.satisfy(&[0, 1])); // First: 1/2+1/2=1 ✓, Second: 0<1 ✗
2004        assert!(!tholder.satisfy(&[5, 6])); // First: 0<1 ✗, Second: 1+1=2≥1 ✓
2005        assert!(!tholder.satisfy(&[2, 3, 4])); // First: 1/4+1/4+1/4=3/4<1 ✗, Second: 0<1 ✗
2006        assert!(!tholder.satisfy(&[])); // Empty indices
2007
2008        Ok(())
2009    }
2010
2011    #[test]
2012    fn test_tholder_json_string_multi_clause() -> Result<(), Box<dyn std::error::Error>> {
2013        // Test Tholder(sith='[["1/2", "1/2", "1/4", "1/4", "1/4"], ["1/1", "1"]]')
2014        let json_str = r#"[["1/2", "1/2", "1/4", "1/4", "1/4"], ["1", "1"]]"#;
2015        let tholder = Tholder::new(None, None, Some(TholderSith::Json(json_str.to_string())))?;
2016
2017        // Verify basic properties
2018        assert!(tholder.weighted());
2019        assert_eq!(tholder.size(), 7); // 5 + 2 = 7 total elements
2020
2021        // Verify the parsed threshold structure
2022        if let TholderThold::Weighted(clauses) = tholder.thold() {
2023            assert_eq!(clauses.len(), 2); // Two clauses
2024            assert_eq!(clauses[0].len(), 5); // First clause has 5 elements
2025            assert_eq!(clauses[1].len(), 2); // Second clause has 2 elements
2026
2027            // Check first clause elements
2028            if let WeightSpec::Simple(fraction) = clauses[0][0] {
2029                assert_eq!(fraction, Rational32::new(1, 2));
2030            } else {
2031                panic!("Expected Simple weight spec");
2032            }
2033
2034            if let WeightSpec::Simple(fraction) = clauses[0][1] {
2035                assert_eq!(fraction, Rational32::new(1, 2));
2036            } else {
2037                panic!("Expected Simple weight spec");
2038            }
2039
2040            if let WeightSpec::Simple(fraction) = clauses[0][2] {
2041                assert_eq!(fraction, Rational32::new(1, 4));
2042            } else {
2043                panic!("Expected Simple weight spec");
2044            }
2045
2046            // Check second clause elements
2047            if let WeightSpec::Simple(fraction) = clauses[1][0] {
2048                assert_eq!(fraction, Rational32::new(1, 1));
2049            } else {
2050                panic!("Expected Simple weight spec");
2051            }
2052
2053            if let WeightSpec::Simple(fraction) = clauses[1][1] {
2054                assert_eq!(fraction, Rational32::new(1, 1));
2055            } else {
2056                panic!("Expected Simple weight spec");
2057            }
2058        } else {
2059            panic!("Expected Weighted threshold type");
2060        }
2061
2062        // Check serialized limen
2063        assert_eq!(tholder.limen(), b"4AAGA1s2c1s2c1s4c1s4c1s4a1c1");
2064
2065        // Verify sith representation (should be nested)
2066        if let TholderSith::Json(json_str) = tholder.sith() {
2067            let expected_nested = r#"[["1/2","1/2","1/4","1/4","1/4"],["1","1"]]"#;
2068            assert_eq!(json_str, expected_nested);
2069        } else {
2070            panic!("Expected Json sith type for multi-clause");
2071        }
2072
2073        // Verify JSON representation
2074        let expected_json = r#"[["1/2","1/2","1/4","1/4","1/4"],["1","1"]]"#;
2075        assert_eq!(tholder.json(), expected_json);
2076
2077        // Verify numeric threshold is None for weighted thresholds
2078        assert_eq!(tholder.num(), None);
2079
2080        // Test satisfaction scenarios that should pass
2081        // Both clauses must be satisfied (AND logic)
2082        assert!(tholder.satisfy(&[1, 2, 3, 5])); // First: 1/2+1/4+1/4=1, Second: 1=1 ✓
2083        assert!(tholder.satisfy(&[0, 1, 6])); // First: 1/2+1/2=1, Second: 1=1 ✓
2084
2085        // Test satisfaction scenarios that should fail
2086        assert!(!tholder.satisfy(&[0, 1])); // First: 1/2+1/2=1 ✓, Second: 0<1 ✗
2087        assert!(!tholder.satisfy(&[5, 6])); // First: 0<1 ✗, Second: 1+1=2≥1 ✓
2088        assert!(!tholder.satisfy(&[2, 3, 4])); // First: 1/4+1/4+1/4=3/4<1 ✗, Second: 0<1 ✗
2089        assert!(!tholder.satisfy(&[])); // Empty indices
2090
2091        Ok(())
2092    }
2093
2094    #[test]
2095    fn test_tholder_json_string_single_clause_nested() -> Result<(), Box<dyn std::error::Error>> {
2096        // Test Tholder(sith='[["1/2", "1/2", "1/4", "1/4", "1/4"]]')
2097        let json_str = r#"[["1/2", "1/2", "1/4", "1/4", "1/4"]]"#;
2098        let tholder = Tholder::new(None, None, Some(TholderSith::Json(json_str.to_string())))?;
2099
2100        // Verify basic properties
2101        assert!(tholder.weighted());
2102        assert_eq!(tholder.size(), 5);
2103
2104        // Verify the parsed threshold structure
2105        if let TholderThold::Weighted(clauses) = tholder.thold() {
2106            assert_eq!(clauses.len(), 1); // Single clause
2107            assert_eq!(clauses[0].len(), 5); // 5 elements
2108
2109            // Check individual fraction values
2110            if let WeightSpec::Simple(fraction) = clauses[0][0] {
2111                assert_eq!(fraction, Rational32::new(1, 2));
2112            } else {
2113                panic!("Expected Simple weight spec for first element");
2114            }
2115
2116            if let WeightSpec::Simple(fraction) = clauses[0][1] {
2117                assert_eq!(fraction, Rational32::new(1, 2));
2118            } else {
2119                panic!("Expected Simple weight spec for second element");
2120            }
2121
2122            if let WeightSpec::Simple(fraction) = clauses[0][2] {
2123                assert_eq!(fraction, Rational32::new(1, 4));
2124            } else {
2125                panic!("Expected Simple weight spec for third element");
2126            }
2127
2128            if let WeightSpec::Simple(fraction) = clauses[0][3] {
2129                assert_eq!(fraction, Rational32::new(1, 4));
2130            } else {
2131                panic!("Expected Simple weight spec for fourth element");
2132            }
2133
2134            if let WeightSpec::Simple(fraction) = clauses[0][4] {
2135                assert_eq!(fraction, Rational32::new(1, 4));
2136            } else {
2137                panic!("Expected Simple weight spec for fifth element");
2138            }
2139        } else {
2140            panic!("Expected Weighted threshold type");
2141        }
2142
2143        // Check serialized limen
2144        assert_eq!(tholder.limen(), b"4AAFA1s2c1s2c1s4c1s4c1s4");
2145
2146        // Verify sith representation (should be flattened for single clause)
2147        if let TholderSith::Weights(weights) = tholder.sith() {
2148            assert_eq!(weights.len(), 5);
2149            if let WeightedSithElement::Simple(s) = &weights[0] {
2150                assert_eq!(s, "1/2");
2151            } else {
2152                panic!("Expected Simple weight element");
2153            }
2154        } else {
2155            panic!("Expected Weights sith type");
2156        }
2157
2158        // Verify JSON representation
2159        let expected_json = r#"["1/2","1/2","1/4","1/4","1/4"]"#;
2160        assert_eq!(tholder.json(), expected_json);
2161
2162        // Verify numeric threshold is None for weighted thresholds
2163        assert_eq!(tholder.num(), None);
2164
2165        // Test satisfaction scenarios that should pass
2166        assert!(tholder.satisfy(&[1, 2, 3])); // 1/2 + 1/4 + 1/4 = 1
2167        assert!(tholder.satisfy(&[0, 1, 2])); // 1/2 + 1/2 + 1/4 = 5/4 > 1
2168        assert!(tholder.satisfy(&[1, 3, 4])); // 1/2 + 1/4 + 1/4 = 1
2169        assert!(tholder.satisfy(&[0, 1, 2, 3, 4])); // All weights
2170        assert!(tholder.satisfy(&[3, 2, 0])); // 1/4 + 1/4 + 1/2 = 1
2171        assert!(tholder.satisfy(&[0, 0, 1, 2, 1, 4, 4])); // Duplicates should be ignored
2172
2173        // Test satisfaction scenarios that should fail
2174        assert!(!tholder.satisfy(&[0, 2])); // 1/2 + 1/4 = 3/4 < 1
2175        assert!(!tholder.satisfy(&[2, 3, 4])); // 1/4 + 1/4 + 1/4 = 3/4 < 1
2176
2177        Ok(())
2178    }
2179
2180    #[test]
2181    fn test_tholder_json_string_simple_array() -> Result<(), Box<dyn std::error::Error>> {
2182        // Test Tholder(sith='["1/2", "1/2", "1/4", "1/4", "1/4", "0"]')
2183        let json_str = r#"["1/2", "1/2", "1/4", "1/4", "1/4", "0"]"#;
2184        let tholder = Tholder::new(None, None, Some(TholderSith::Json(json_str.to_string())))?;
2185
2186        // Verify basic properties
2187        assert!(tholder.weighted());
2188        assert_eq!(tholder.size(), 6);
2189
2190        // Verify the parsed threshold structure
2191        if let TholderThold::Weighted(clauses) = tholder.thold() {
2192            assert_eq!(clauses.len(), 1); // Single clause
2193            assert_eq!(clauses[0].len(), 6); // 6 elements
2194
2195            // Check individual fraction values
2196            if let WeightSpec::Simple(fraction) = clauses[0][0] {
2197                assert_eq!(fraction, Rational32::new(1, 2));
2198            } else {
2199                panic!("Expected Simple weight spec for first element");
2200            }
2201
2202            if let WeightSpec::Simple(fraction) = clauses[0][1] {
2203                assert_eq!(fraction, Rational32::new(1, 2));
2204            } else {
2205                panic!("Expected Simple weight spec for second element");
2206            }
2207
2208            if let WeightSpec::Simple(fraction) = clauses[0][2] {
2209                assert_eq!(fraction, Rational32::new(1, 4));
2210            } else {
2211                panic!("Expected Simple weight spec for third element");
2212            }
2213
2214            if let WeightSpec::Simple(fraction) = clauses[0][3] {
2215                assert_eq!(fraction, Rational32::new(1, 4));
2216            } else {
2217                panic!("Expected Simple weight spec for fourth element");
2218            }
2219
2220            if let WeightSpec::Simple(fraction) = clauses[0][4] {
2221                assert_eq!(fraction, Rational32::new(1, 4));
2222            } else {
2223                panic!("Expected Simple weight spec for fifth element");
2224            }
2225
2226            // Check that last element is zero
2227            if let WeightSpec::Simple(fraction) = clauses[0][5] {
2228                assert_eq!(fraction, Rational32::new(0, 1));
2229            } else {
2230                panic!("Expected Simple weight spec for last element");
2231            }
2232        } else {
2233            panic!("Expected Weighted threshold type");
2234        }
2235
2236        // Check serialized limen
2237        assert_eq!(tholder.limen(), b"6AAGAAA1s2c1s2c1s4c1s4c1s4c0");
2238
2239        // Verify sith representation (should be flattened for single clause)
2240        if let TholderSith::Weights(weights) = tholder.sith() {
2241            assert_eq!(weights.len(), 6);
2242            if let WeightedSithElement::Simple(s) = &weights[0] {
2243                assert_eq!(s, "1/2");
2244            } else {
2245                panic!("Expected Simple weight element");
2246            }
2247            if let WeightedSithElement::Simple(s) = &weights[5] {
2248                assert_eq!(s, "0");
2249            } else {
2250                panic!("Expected Simple weight element");
2251            }
2252        } else {
2253            panic!("Expected Weights sith type");
2254        }
2255
2256        // Verify JSON representation
2257        let expected_json = r#"["1/2","1/2","1/4","1/4","1/4","0"]"#;
2258        assert_eq!(tholder.json(), expected_json);
2259
2260        // Verify numeric threshold is None for weighted thresholds
2261        assert_eq!(tholder.num(), None);
2262
2263        // Test satisfaction scenarios that should pass
2264        assert!(tholder.satisfy(&[0, 2, 4])); // 1/2 + 1/4 + 1/4 = 1
2265        assert!(tholder.satisfy(&[0, 1])); // 1/2 + 1/2 = 1
2266        assert!(tholder.satisfy(&[1, 3, 4])); // 1/2 + 1/4 + 1/4 = 1
2267        assert!(tholder.satisfy(&[0, 1, 2, 3, 4])); // All weights
2268        assert!(tholder.satisfy(&[3, 2, 0])); // 1/4 + 1/4 + 1/2 = 1
2269        assert!(tholder.satisfy(&[0, 0, 1, 2, 1])); // Duplicates should be ignored
2270
2271        // Test satisfaction scenarios that should fail (including zero weight)
2272        assert!(!tholder.satisfy(&[0, 2, 5])); // 1/2 + 1/4 + 0 = 3/4 < 1
2273        assert!(!tholder.satisfy(&[2, 3, 4, 5])); // 1/4 + 1/4 + 1/4 + 0 = 3/4 < 1
2274
2275        Ok(())
2276    }
2277
2278    #[test]
2279    fn test_tholder_from_limen_multi_clause() -> Result<(), Box<dyn std::error::Error>> {
2280        // Test Tholder(limen=b'4AAGA1s2c1s2c1s4c1s4c1s4a1c1')
2281        let limen = b"4AAGA1s2c1s2c1s4c1s4c1s4a1c1".to_vec();
2282        let tholder = Tholder::new(None, Some(limen), None)?;
2283
2284        // Verify basic properties
2285        assert!(tholder.weighted());
2286        assert_eq!(tholder.size(), 7); // 5 + 2 = 7 total elements
2287
2288        // Verify the parsed threshold structure
2289        if let TholderThold::Weighted(clauses) = tholder.thold() {
2290            assert_eq!(clauses.len(), 2); // Two clauses
2291            assert_eq!(clauses[0].len(), 5); // First clause has 5 elements
2292            assert_eq!(clauses[1].len(), 2); // Second clause has 2 elements
2293
2294            // Check first clause elements
2295            if let WeightSpec::Simple(fraction) = clauses[0][0] {
2296                assert_eq!(fraction, Rational32::new(1, 2));
2297            } else {
2298                panic!("Expected Simple weight spec");
2299            }
2300
2301            if let WeightSpec::Simple(fraction) = clauses[0][1] {
2302                assert_eq!(fraction, Rational32::new(1, 2));
2303            } else {
2304                panic!("Expected Simple weight spec");
2305            }
2306
2307            if let WeightSpec::Simple(fraction) = clauses[0][2] {
2308                assert_eq!(fraction, Rational32::new(1, 4));
2309            } else {
2310                panic!("Expected Simple weight spec");
2311            }
2312
2313            if let WeightSpec::Simple(fraction) = clauses[0][3] {
2314                assert_eq!(fraction, Rational32::new(1, 4));
2315            } else {
2316                panic!("Expected Simple weight spec");
2317            }
2318
2319            if let WeightSpec::Simple(fraction) = clauses[0][4] {
2320                assert_eq!(fraction, Rational32::new(1, 4));
2321            } else {
2322                panic!("Expected Simple weight spec");
2323            }
2324
2325            // Check second clause elements
2326            if let WeightSpec::Simple(fraction) = clauses[1][0] {
2327                assert_eq!(fraction, Rational32::new(1, 1));
2328            } else {
2329                panic!("Expected Simple weight spec");
2330            }
2331
2332            if let WeightSpec::Simple(fraction) = clauses[1][1] {
2333                assert_eq!(fraction, Rational32::new(1, 1));
2334            } else {
2335                panic!("Expected Simple weight spec");
2336            }
2337        } else {
2338            panic!("Expected Weighted threshold type");
2339        }
2340
2341        // Check serialized limen
2342        assert_eq!(tholder.limen(), b"4AAGA1s2c1s2c1s4c1s4c1s4a1c1");
2343
2344        // Verify sith representation (should be nested)
2345        if let TholderSith::Json(json_str) = tholder.sith() {
2346            let expected_nested = r#"[["1/2","1/2","1/4","1/4","1/4"],["1","1"]]"#;
2347            assert_eq!(json_str, expected_nested);
2348        } else {
2349            panic!("Expected Json sith type for multi-clause");
2350        }
2351
2352        // Verify JSON representation
2353        let expected_json = r#"[["1/2","1/2","1/4","1/4","1/4"],["1","1"]]"#;
2354        assert_eq!(tholder.json(), expected_json);
2355
2356        // Verify numeric threshold is None for weighted thresholds
2357        assert_eq!(tholder.num(), None);
2358
2359        // Test satisfaction scenarios that should pass
2360        // Both clauses must be satisfied (AND logic)
2361        assert!(tholder.satisfy(&[1, 2, 3, 5])); // First: 1/2+1/4+1/4=1, Second: 1=1 ✓
2362        assert!(tholder.satisfy(&[0, 1, 6])); // First: 1/2+1/2=1, Second: 1=1 ✓
2363
2364        // Test satisfaction scenarios that should fail
2365        assert!(!tholder.satisfy(&[0, 1])); // First: 1/2+1/2=1 ✓, Second: 0<1 ✗
2366        assert!(!tholder.satisfy(&[5, 6])); // First: 0<1 ✗, Second: 1+1=2≥1 ✓
2367        assert!(!tholder.satisfy(&[2, 3, 4])); // First: 1/4+1/4+1/4=3/4<1 ✗, Second: 0<1 ✗
2368        assert!(!tholder.satisfy(&[])); // Empty indices
2369
2370        Ok(())
2371    }
2372
2373    #[test]
2374    fn test_tholder_from_thold_multi_clause() -> Result<(), Box<dyn std::error::Error>> {
2375        // Test Tholder(thold=[[Fraction(1, 2), Fraction(1, 2), Fraction(1, 4), Fraction(1, 4), Fraction(1, 4)],
2376        //                     [Fraction(1, 1), Fraction(1, 1)]])
2377        let thold = TholderThold::Weighted(vec![
2378            vec![
2379                WeightSpec::Simple(Rational32::new(1, 2)),
2380                WeightSpec::Simple(Rational32::new(1, 2)),
2381                WeightSpec::Simple(Rational32::new(1, 4)),
2382                WeightSpec::Simple(Rational32::new(1, 4)),
2383                WeightSpec::Simple(Rational32::new(1, 4)),
2384            ],
2385            vec![
2386                WeightSpec::Simple(Rational32::new(1, 1)),
2387                WeightSpec::Simple(Rational32::new(1, 1)),
2388            ],
2389        ]);
2390
2391        let tholder = Tholder::new(Some(thold), None, None)?;
2392
2393        // Verify basic properties
2394        assert!(tholder.weighted());
2395        assert_eq!(tholder.size(), 7); // 5 + 2 = 7 total elements
2396
2397        // Verify the parsed threshold structure
2398        if let TholderThold::Weighted(clauses) = tholder.thold() {
2399            assert_eq!(clauses.len(), 2); // Two clauses
2400            assert_eq!(clauses[0].len(), 5); // First clause has 5 elements
2401            assert_eq!(clauses[1].len(), 2); // Second clause has 2 elements
2402
2403            // Check first clause elements
2404            if let WeightSpec::Simple(fraction) = clauses[0][0] {
2405                assert_eq!(fraction, Rational32::new(1, 2));
2406            } else {
2407                panic!("Expected Simple weight spec");
2408            }
2409
2410            if let WeightSpec::Simple(fraction) = clauses[0][1] {
2411                assert_eq!(fraction, Rational32::new(1, 2));
2412            } else {
2413                panic!("Expected Simple weight spec");
2414            }
2415
2416            if let WeightSpec::Simple(fraction) = clauses[0][2] {
2417                assert_eq!(fraction, Rational32::new(1, 4));
2418            } else {
2419                panic!("Expected Simple weight spec");
2420            }
2421
2422            if let WeightSpec::Simple(fraction) = clauses[0][3] {
2423                assert_eq!(fraction, Rational32::new(1, 4));
2424            } else {
2425                panic!("Expected Simple weight spec");
2426            }
2427
2428            if let WeightSpec::Simple(fraction) = clauses[0][4] {
2429                assert_eq!(fraction, Rational32::new(1, 4));
2430            } else {
2431                panic!("Expected Simple weight spec");
2432            }
2433
2434            // Check second clause elements
2435            if let WeightSpec::Simple(fraction) = clauses[1][0] {
2436                assert_eq!(fraction, Rational32::new(1, 1));
2437            } else {
2438                panic!("Expected Simple weight spec");
2439            }
2440
2441            if let WeightSpec::Simple(fraction) = clauses[1][1] {
2442                assert_eq!(fraction, Rational32::new(1, 1));
2443            } else {
2444                panic!("Expected Simple weight spec");
2445            }
2446        } else {
2447            panic!("Expected Weighted threshold type");
2448        }
2449
2450        // Check serialized limen
2451        assert_eq!(tholder.limen(), b"4AAGA1s2c1s2c1s4c1s4c1s4a1c1");
2452
2453        // Verify sith representation (should be nested)
2454        if let TholderSith::Json(json_str) = tholder.sith() {
2455            let expected_nested = r#"[["1/2","1/2","1/4","1/4","1/4"],["1","1"]]"#;
2456            assert_eq!(json_str, expected_nested);
2457        } else {
2458            panic!("Expected Json sith type for multi-clause");
2459        }
2460
2461        // Verify JSON representation
2462        let expected_json = r#"[["1/2","1/2","1/4","1/4","1/4"],["1","1"]]"#;
2463        assert_eq!(tholder.json(), expected_json);
2464
2465        // Verify numeric threshold is None for weighted thresholds
2466        assert_eq!(tholder.num(), None);
2467
2468        // Test satisfaction scenarios that should pass
2469        // Both clauses must be satisfied (AND logic)
2470        assert!(tholder.satisfy(&[1, 2, 3, 5])); // First: 1/2+1/4+1/4=1, Second: 1=1 ✓
2471        assert!(tholder.satisfy(&[0, 1, 6])); // First: 1/2+1/2=1, Second: 1=1 ✓
2472
2473        // Test satisfaction scenarios that should fail
2474        assert!(!tholder.satisfy(&[0, 1])); // First: 1/2+1/2=1 ✓, Second: 0<1 ✗
2475        assert!(!tholder.satisfy(&[5, 6])); // First: 0<1 ✗, Second: 1+1=2≥1 ✓
2476        assert!(!tholder.satisfy(&[2, 3, 4])); // First: 1/4+1/4+1/4=3/4<1 ✗, Second: 0<1 ✗
2477        assert!(!tholder.satisfy(&[])); // Empty indices
2478
2479        Ok(())
2480    }
2481
2482    #[test]
2483    fn test_tholder_nested_weighted_single_clause() -> Result<(), Box<dyn std::error::Error>> {
2484        // Test single clause with complex weighted mapping
2485        // [{"1/3":["1/2", "1/2", "1/2"]}, "1/3", "1/2", {"1/2": ["1", "1"]}]
2486        let json_str = r#"[{"1/3":["1/2", "1/2", "1/2"]}, "1/3", "1/2", {"1/2": ["1", "1"]}]"#;
2487        let tholder = Tholder::new(None, None, Some(TholderSith::Json(json_str.to_string())))?;
2488
2489        // Verify basic properties
2490        assert!(tholder.weighted());
2491        assert_eq!(tholder.size(), 7); // 3 + 1 + 1 + 2 = 7 total elements
2492
2493        // Verify the parsed threshold structure
2494        if let TholderThold::Weighted(clauses) = tholder.thold() {
2495            assert_eq!(clauses.len(), 1); // Single clause
2496            assert_eq!(clauses[0].len(), 4); // Four elements in clause
2497
2498            // Check first element: WeightedMap with key "1/3" and values ["1/2", "1/2", "1/2"]
2499            if let WeightSpec::WeightedMap(key_weight, nested_weights) = &clauses[0][0] {
2500                assert_eq!(*key_weight, Rational32::new(1, 3));
2501                assert_eq!(nested_weights.len(), 3);
2502                assert_eq!(nested_weights[0], Rational32::new(1, 2));
2503                assert_eq!(nested_weights[1], Rational32::new(1, 2));
2504                assert_eq!(nested_weights[2], Rational32::new(1, 2));
2505            } else {
2506                panic!("Expected WeightedMap for first element");
2507            }
2508
2509            // Check second element: Simple "1/3"
2510            if let WeightSpec::Simple(weight) = clauses[0][1] {
2511                assert_eq!(weight, Rational32::new(1, 3));
2512            } else {
2513                panic!("Expected Simple weight for second element");
2514            }
2515
2516            // Check third element: Simple "1/2"
2517            if let WeightSpec::Simple(weight) = clauses[0][2] {
2518                assert_eq!(weight, Rational32::new(1, 2));
2519            } else {
2520                panic!("Expected Simple weight for third element");
2521            }
2522
2523            // Check fourth element: WeightedMap with key "1/2" and values ["1", "1"]
2524            if let WeightSpec::WeightedMap(key_weight, nested_weights) = &clauses[0][3] {
2525                assert_eq!(*key_weight, Rational32::new(1, 2));
2526                assert_eq!(nested_weights.len(), 2);
2527                assert_eq!(nested_weights[0], Rational32::new(1, 1));
2528                assert_eq!(nested_weights[1], Rational32::new(1, 1));
2529            } else {
2530                panic!("Expected WeightedMap for fourth element");
2531            }
2532        } else {
2533            panic!("Expected Weighted threshold type");
2534        }
2535
2536        // Check serialized limen
2537        assert_eq!(tholder.limen(), b"4AAIA1s3k1s2v1s2v1s2c1s3c1s2c1s2k1v1");
2538
2539        // Verify sith representation (should be flattened for single clause)
2540        if let TholderSith::Weights(weights) = tholder.sith() {
2541            assert_eq!(weights.len(), 4);
2542
2543            // First element should be Complex with "1/3" key
2544            if let WeightedSithElement::Complex(map) = &weights[0] {
2545                assert!(map.contains_key("1/3"));
2546                let values = map.get("1/3").unwrap();
2547                assert_eq!(values.len(), 3);
2548            } else {
2549                panic!("Expected Complex element for first weight");
2550            }
2551
2552            // Second element should be Simple "1/3"
2553            if let WeightedSithElement::Simple(s) = &weights[1] {
2554                assert_eq!(s, "1/3");
2555            } else {
2556                panic!("Expected Simple element for second weight");
2557            }
2558
2559            // Third element should be Simple "1/2"
2560            if let WeightedSithElement::Simple(s) = &weights[2] {
2561                assert_eq!(s, "1/2");
2562            } else {
2563                panic!("Expected Simple element for third weight");
2564            }
2565
2566            // Fourth element should be Complex with "1/2" key
2567            if let WeightedSithElement::Complex(map) = &weights[3] {
2568                assert!(map.contains_key("1/2"));
2569                let values = map.get("1/2").unwrap();
2570                assert_eq!(values.len(), 2);
2571            } else {
2572                panic!("Expected Complex element for fourth weight");
2573            }
2574        } else {
2575            panic!("Expected Weights sith type");
2576        }
2577
2578        // Verify JSON representation
2579        let expected_json = r#"[{"1/3":["1/2","1/2","1/2"]},"1/3","1/2",{"1/2":["1","1"]}]"#;
2580        assert_eq!(tholder.json(), expected_json);
2581
2582        // Verify numeric threshold is None for weighted thresholds
2583        assert_eq!(tholder.num(), None);
2584
2585        // Test satisfaction scenarios that should pass
2586        // Need to satisfy: first weighted map (1/3 if nested ≥1) + 1/3 + 1/2 + second weighted map (1/2 if nested ≥1) ≥ 1
2587        // Index mapping: [0,1,2] for first map, [3] for "1/3", [4] for "1/2", [5,6] for second map
2588        assert!(tholder.satisfy(&[0, 2, 3, 6])); // First map: 1/2+1/2=1→1/3, plus 1/3+1/2 = 1.33 ≥ 1
2589        assert!(tholder.satisfy(&[3, 4, 5])); // Skip first map, 1/3+1/2 = 0.83, second map: 1→1/2, total = 1.33 ≥ 1
2590        assert!(tholder.satisfy(&[1, 2, 3, 4])); // First map: 1/2+1/2=1→1/3, plus 1/3+1/2 = 1.33 ≥ 1
2591        assert!(tholder.satisfy(&[4, 6])); // Skip first map, only 1/2, second map: 1→1/2, total = 1 ≥ 1
2592        assert!(tholder.satisfy(&[4, 2, 0, 3])); // First map: 1/2+1/2=1→1/3, plus 1/3+1/2 = 1.33 ≥ 1
2593        assert!(tholder.satisfy(&[0, 0, 1, 2, 1, 5, 6, 3])); // Duplicates ignored, all conditions met
2594
2595        // Test satisfaction scenarios that should fail
2596        assert!(!tholder.satisfy(&[0, 2, 5])); // First map: 1/2+1/2=1→1/3, second map: 1→1/2, total = 0.83 < 1
2597        assert!(!tholder.satisfy(&[2, 3, 4])); // First map: 1/2<1→0, plus 1/3+1/2 = 0.83 < 1
2598
2599        Ok(())
2600    }
2601
2602    #[test]
2603    fn test_tholder_nested_weighted_from_limen() -> Result<(), Box<dyn std::error::Error>> {
2604        // Test creating from limen bytes
2605        let limen = b"4AAIA1s3k1s2v1s2v1s2c1s3c1s2c1s2k1v1".to_vec();
2606        let tholder = Tholder::new(None, Some(limen), None)?;
2607
2608        // Verify basic properties
2609        assert!(tholder.weighted());
2610        assert_eq!(tholder.size(), 7);
2611
2612        // Verify the parsed threshold structure matches expected
2613        if let TholderThold::Weighted(clauses) = tholder.thold() {
2614            assert_eq!(clauses.len(), 1);
2615            assert_eq!(clauses[0].len(), 4);
2616
2617            // Verify structure matches the JSON case
2618            if let WeightSpec::WeightedMap(key_weight, nested_weights) = &clauses[0][0] {
2619                assert_eq!(*key_weight, Rational32::new(1, 3));
2620                assert_eq!(nested_weights.len(), 3);
2621            } else {
2622                panic!("Expected WeightedMap for first element");
2623            }
2624        } else {
2625            panic!("Expected Weighted threshold type");
2626        }
2627
2628        // Check serialized limen
2629        assert_eq!(tholder.limen(), b"4AAIA1s3k1s2v1s2v1s2c1s3c1s2c1s2k1v1");
2630
2631        // Verify JSON representation
2632        let expected_json = r#"[{"1/3":["1/2","1/2","1/2"]},"1/3","1/2",{"1/2":["1","1"]}]"#;
2633        assert_eq!(tholder.json(), expected_json);
2634
2635        assert_eq!(tholder.num(), None);
2636
2637        Ok(())
2638    }
2639
2640    #[test]
2641    fn test_tholder_nested_weighted_from_thold() -> Result<(), Box<dyn std::error::Error>> {
2642        // Test creating from direct thold structure
2643        let thold = TholderThold::Weighted(vec![vec![
2644            WeightSpec::WeightedMap(
2645                Rational32::new(1, 3),
2646                vec![
2647                    Rational32::new(1, 2),
2648                    Rational32::new(1, 2),
2649                    Rational32::new(1, 2),
2650                ],
2651            ),
2652            WeightSpec::Simple(Rational32::new(1, 3)),
2653            WeightSpec::Simple(Rational32::new(1, 2)),
2654            WeightSpec::WeightedMap(
2655                Rational32::new(1, 2),
2656                vec![Rational32::new(1, 1), Rational32::new(1, 1)],
2657            ),
2658        ]]);
2659
2660        let tholder = Tholder::new(Some(thold), None, None)?;
2661
2662        // Verify basic properties
2663        assert!(tholder.weighted());
2664        assert_eq!(tholder.size(), 7);
2665
2666        // Check serialized limen
2667        assert_eq!(tholder.limen(), b"4AAIA1s3k1s2v1s2v1s2c1s3c1s2c1s2k1v1");
2668
2669        // Verify JSON representation
2670        let expected_json = r#"[{"1/3":["1/2","1/2","1/2"]},"1/3","1/2",{"1/2":["1","1"]}]"#;
2671        assert_eq!(tholder.json(), expected_json);
2672
2673        assert_eq!(tholder.num(), None);
2674
2675        Ok(())
2676    }
2677
2678    #[test]
2679    fn test_tholder_nested_weighted_multi_clause() -> Result<(), Box<dyn std::error::Error>> {
2680        // Test multi-clause with complex weighted mapping
2681        let json_str = r#"[[{"1/3":["1/2", "1/2", "1/2"]}, "1/2", {"1/2": ["1", "1"]}], ["1/2", {"1/2": ["1", "1"]}]]"#;
2682        let tholder = Tholder::new(None, None, Some(TholderSith::Json(json_str.to_string())))?;
2683
2684        // Verify basic properties
2685        assert!(tholder.weighted());
2686        assert_eq!(tholder.size(), 9); // First clause: 3+1+2=6, Second clause: 1+2=3, Total: 9
2687
2688        // Verify the parsed threshold structure
2689        if let TholderThold::Weighted(clauses) = tholder.thold() {
2690            assert_eq!(clauses.len(), 2); // Two clauses
2691            assert_eq!(clauses[0].len(), 3); // First clause has 3 elements
2692            assert_eq!(clauses[1].len(), 2); // Second clause has 2 elements
2693
2694            // Check first clause, first element: WeightedMap
2695            if let WeightSpec::WeightedMap(key_weight, nested_weights) = &clauses[0][0] {
2696                assert_eq!(*key_weight, Rational32::new(1, 3));
2697                assert_eq!(nested_weights.len(), 3);
2698            } else {
2699                panic!("Expected WeightedMap for first clause first element");
2700            }
2701
2702            // Check second clause, second element: WeightedMap
2703            if let WeightSpec::WeightedMap(key_weight, nested_weights) = &clauses[1][1] {
2704                assert_eq!(*key_weight, Rational32::new(1, 2));
2705                assert_eq!(nested_weights.len(), 2);
2706            } else {
2707                panic!("Expected WeightedMap for second clause second element");
2708            }
2709        } else {
2710            panic!("Expected Weighted threshold type");
2711        }
2712
2713        // Check serialized limen
2714        assert_eq!(
2715            tholder.limen(),
2716            b"4AAKA1s3k1s2v1s2v1s2c1s2c1s2k1v1a1s2c1s2k1v1"
2717        );
2718
2719        // Verify sith representation (should be nested for multi-clause)
2720        if let TholderSith::Json(json_str) = tholder.sith() {
2721            let expected_nested = r#"[[{"1/3":["1/2","1/2","1/2"]},"1/2",{"1/2":["1","1"]}],["1/2",{"1/2":["1","1"]}]]"#;
2722            assert_eq!(json_str, expected_nested);
2723        } else {
2724            panic!("Expected Json sith type for multi-clause");
2725        }
2726
2727        // Verify JSON representation
2728        let expected_json =
2729            r#"[[{"1/3":["1/2","1/2","1/2"]},"1/2",{"1/2":["1","1"]}],["1/2",{"1/2":["1","1"]}]]"#;
2730        assert_eq!(tholder.json(), expected_json);
2731
2732        assert_eq!(tholder.num(), None);
2733
2734        // Test satisfaction scenarios
2735        // Index mapping: [0,1,2] first map, [3] simple, [4,5] second map | [6] simple, [7,8] third map
2736        assert!(tholder.satisfy(&[0, 2, 3, 5, 6, 7])); // Both clauses satisfied
2737        assert!(tholder.satisfy(&[3, 4, 5, 6, 8])); // Both clauses satisfied
2738        assert!(tholder.satisfy(&[1, 2, 3, 4, 6, 7])); // Both clauses satisfied
2739        assert!(tholder.satisfy(&[4, 2, 0, 3, 8, 6])); // Both clauses satisfied
2740        assert!(tholder.satisfy(&[0, 0, 1, 2, 1, 8, 3, 5, 6, 3])); // Duplicates ignored, both clauses satisfied
2741
2742        // Test failure cases
2743        assert!(!tholder.satisfy(&[0, 2, 5])); // First clause not satisfied (missing simple weights)
2744        assert!(!tholder.satisfy(&[6, 7, 8])); // Second clause satisfied but first clause not satisfied
2745
2746        Ok(())
2747    }
2748
2749    #[test]
2750    fn test_tholder_nested_weighted_multi_clause_from_limen(
2751    ) -> Result<(), Box<dyn std::error::Error>> {
2752        // Test creating multi-clause from limen
2753        let limen = b"4AAKA1s3k1s2v1s2v1s2c1s2c1s2k1v1a1s2c1s2k1v1".to_vec();
2754        let tholder = Tholder::new(None, Some(limen), None)?;
2755
2756        assert!(tholder.weighted());
2757        assert_eq!(tholder.size(), 9);
2758        assert_eq!(
2759            tholder.limen(),
2760            b"4AAKA1s3k1s2v1s2v1s2c1s2c1s2k1v1a1s2c1s2k1v1"
2761        );
2762
2763        let expected_json =
2764            r#"[[{"1/3":["1/2","1/2","1/2"]},"1/2",{"1/2":["1","1"]}],["1/2",{"1/2":["1","1"]}]]"#;
2765        assert_eq!(tholder.json(), expected_json);
2766
2767        assert_eq!(tholder.num(), None);
2768
2769        Ok(())
2770    }
2771
2772    #[test]
2773    fn test_tholder_nested_weighted_multi_clause_from_thold(
2774    ) -> Result<(), Box<dyn std::error::Error>> {
2775        // Test creating multi-clause from direct thold structure
2776        let thold = TholderThold::Weighted(vec![
2777            vec![
2778                WeightSpec::WeightedMap(
2779                    Rational32::new(1, 3),
2780                    vec![
2781                        Rational32::new(1, 2),
2782                        Rational32::new(1, 2),
2783                        Rational32::new(1, 2),
2784                    ],
2785                ),
2786                WeightSpec::Simple(Rational32::new(1, 2)),
2787                WeightSpec::WeightedMap(
2788                    Rational32::new(1, 2),
2789                    vec![Rational32::new(1, 1), Rational32::new(1, 1)],
2790                ),
2791            ],
2792            vec![
2793                WeightSpec::Simple(Rational32::new(1, 2)),
2794                WeightSpec::WeightedMap(
2795                    Rational32::new(1, 2),
2796                    vec![Rational32::new(1, 1), Rational32::new(1, 1)],
2797                ),
2798            ],
2799        ]);
2800
2801        let tholder = Tholder::new(Some(thold), None, None)?;
2802
2803        assert!(tholder.weighted());
2804        assert_eq!(tholder.size(), 9);
2805        assert_eq!(
2806            tholder.limen(),
2807            b"4AAKA1s3k1s2v1s2v1s2c1s2c1s2k1v1a1s2c1s2k1v1"
2808        );
2809
2810        let expected_json =
2811            r#"[[{"1/3":["1/2","1/2","1/2"]},"1/2",{"1/2":["1","1"]}],["1/2",{"1/2":["1","1"]}]]"#;
2812        assert_eq!(tholder.json(), expected_json);
2813
2814        assert_eq!(tholder.num(), None);
2815
2816        Ok(())
2817    }
2818
2819    #[test]
2820    fn test_tholder_nested_weighted_validation_errors() -> Result<(), Box<dyn std::error::Error>> {
2821        // Test error case: nested weights don't sum to >= 1
2822        let json_str1 = r#"[{"1/3":["1/3", "1/3", "1/4"]}, "1/3", "1/2", {"1/2": ["1", "1"]}]"#;
2823        let result1 = Tholder::new(None, None, Some(TholderSith::Json(json_str1.to_string())));
2824        assert!(result1.is_err());
2825
2826        // Test error case: nested weights don't sum to >= 1 in second map
2827        let json_str2 = r#"[{"1/3":["1/2", "1/2", "1/2"]}, "1/3", "1/2", {"1/2": ["2/3", "1/4"]}]"#;
2828        let result2 = Tholder::new(None, None, Some(TholderSith::Json(json_str2.to_string())));
2829        assert!(result2.is_err());
2830
2831        // Test error case: top-level weights don't sum to >= 1
2832        let json_str3 = r#"[{"1/5":["1/2", "1/2", "1/2"]}, "1/4", "1/5", {"1/5": ["1", "1"]}]"#;
2833        let result3 = Tholder::new(None, None, Some(TholderSith::Json(json_str3.to_string())));
2834        assert!(result3.is_err());
2835
2836        // Test error case: multi-clause with invalid nested weights
2837        let json_str4 = r#"[[{"1/3":["1/2", "1/2", "1/2"]}, "1/2", {"1/2": ["1", "1"]}], ["1/2", {"1/3": ["1", "1"]}]]"#;
2838        let result4 = Tholder::new(None, None, Some(TholderSith::Json(json_str4.to_string())));
2839        assert!(result4.is_err());
2840
2841        // Test error case: multi-clause with insufficient nested weights
2842        let json_str5 = r#"[[{"1/3":["1/3", "1/4", "1/3"]}, "1/2", {"1/2": ["1", "1"]}], ["1/2", {"1/2": ["1/2", "1/2"]}]]"#;
2843        let result5 = Tholder::new(None, None, Some(TholderSith::Json(json_str5.to_string())));
2844        assert!(result5.is_err());
2845
2846        Ok(())
2847    }
2848}