webpage_quality_analyzer 1.0.2

High-performance webpage quality analyzer with 115 comprehensive metrics - Rust library with WASM, C++, and Python bindings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
/// Profile Modification System
///
/// Provides runtime profile modification without mutating base profiles.
/// Enables per-metric customization, custom penalties/bonuses, and dynamic configuration.
use crate::config::enhanced_models::{
    EnhancedScoringProfile, GlobalBonus, GlobalPenalty, MetricOverride,
};
use crate::metrics::definitions::{ThresholdSet, METRIC_REGISTRY};
use crate::AnalyzeError; // Use the re-exported error type
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

/// Result type for profile modification operations
pub type ModifierResult<T> = Result<T, AnalyzeError>;

/// Runtime profile modification system
///
/// Uses a non-destructive modification pattern that preserves the original profile
/// and applies changes on demand. This allows for composable modifications and
/// ensures thread safety through immutability.
#[derive(Debug, Clone)]
pub struct ProfileModifier {
    base_profile: Arc<EnhancedScoringProfile>,
    modifications: ProfileModifications,
}

/// Collection of all modifications to apply to a profile
#[derive(Debug, Clone, Default)]
pub struct ProfileModifications {
    /// Per-metric customizations (weight, enabled, thresholds)
    pub metric_overrides: HashMap<String, MetricOverrideModification>,
    /// Custom penalties to apply globally
    pub custom_penalties: Vec<GlobalPenalty>,
    /// Custom bonuses to apply globally
    pub custom_bonuses: Vec<GlobalBonus>,
    /// Set of metric names that should be disabled
    pub disabled_metrics: HashSet<String>,
}

/// Modifications to apply to a specific metric
#[derive(Debug, Clone, Default)]
pub struct MetricOverrideModification {
    /// Override the metric's weight (if Some)
    pub weight: Option<f32>,
    /// Override the metric's enabled state (if Some)
    pub enabled: Option<bool>,
    /// Override the metric's thresholds (if Some)
    /// Format: [min, optimal_min, optimal_max, max] for 4-value thresholds
    /// Or: [poor, fair, good, excellent] for compatibility with old system
    pub thresholds: Option<Vec<f32>>,
    /// Override the penalty multiplier (if Some)
    pub penalty_multiplier: Option<f32>,
}

impl ProfileModifier {
    /// Create a new ProfileModifier wrapping a base profile
    ///
    /// # Arguments
    /// * `base_profile` - The profile to use as a foundation (wrapped in Arc for efficiency)
    pub fn new(base_profile: Arc<EnhancedScoringProfile>) -> Self {
        Self {
            base_profile,
            modifications: ProfileModifications::default(),
        }
    }

    /// Apply all accumulated modifications to create a new profile
    ///
    /// This clones the base profile and applies all modifications,
    /// returning a new EnhancedScoringProfile ready for use.
    pub fn apply_modifications(&self) -> EnhancedScoringProfile {
        let mut modified = (*self.base_profile).clone();

        // Apply metric overrides
        for (metric_name, override_mod) in &self.modifications.metric_overrides {
            // Get or create metric override in the profile
            let metric_override = modified
                .metric_overrides
                .entry(metric_name.clone())
                .or_insert_with(MetricOverride::default);

            // Apply weight override
            if let Some(weight) = override_mod.weight {
                metric_override.weight = weight;
            }

            // Apply enabled override
            if let Some(enabled) = override_mod.enabled {
                metric_override.enabled = enabled;
            }

            // Apply threshold override
            if let Some(ref thresholds) = override_mod.thresholds {
                // Convert Vec<f32> to ThresholdSet
                // If 4 values: [min, optimal_min, optimal_max, max] -> convert to ThresholdSet
                // The ProfileCompiler will handle the actual conversion during scoring
                if thresholds.len() == 4 {
                    metric_override.thresholds = Some(ThresholdSet {
                        poor: thresholds[0],      // min
                        fair: thresholds[1],      // optimal_min
                        good: thresholds[2],      // optimal_max
                        excellent: thresholds[3], // max
                    });
                } else if thresholds.len() >= 4 {
                    // Use first 4 values if more provided
                    metric_override.thresholds = Some(ThresholdSet {
                        poor: thresholds[0],
                        fair: thresholds[1],
                        good: thresholds[2],
                        excellent: thresholds[3],
                    });
                }
            }

            // Apply penalty multiplier override
            if let Some(penalty_multiplier) = override_mod.penalty_multiplier {
                metric_override.penalty_multiplier = penalty_multiplier;
            }
        }

        // Apply disabled metrics
        for metric_name in &self.modifications.disabled_metrics {
            let metric_override = modified
                .metric_overrides
                .entry(metric_name.clone())
                .or_insert_with(MetricOverride::default);
            metric_override.enabled = false;
        }

        // Apply custom penalties
        // Note: GlobalPenalty configuration doesn't have a simple append point in current structure
        // For now, we'll add them to the severe_penalties map with generated keys
        for (idx, penalty) in self.modifications.custom_penalties.iter().enumerate() {
            let key = format!("custom_penalty_{}", idx);
            modified
                .penalties
                .severe_penalties
                .insert(key, penalty.clone());
        }

        // Apply custom bonuses
        // Similarly, add to excellence_bonuses with generated keys
        for (idx, bonus) in self.modifications.custom_bonuses.iter().enumerate() {
            let key = format!("custom_bonus_{}", idx);
            modified
                .bonuses
                .excellence_bonuses
                .insert(key, bonus.clone());
        }

        modified
    }

    /// Enable a specific metric
    ///
    /// # Arguments
    /// * `metric_name` - Name of the metric to enable (must exist in METRIC_REGISTRY)
    ///
    /// # Returns
    /// &mut Self for method chaining
    pub fn enable_metric(&mut self, metric_name: &str) -> ModifierResult<&mut Self> {
        self.validate_metric_name(metric_name)?;

        // Remove from disabled set if present
        self.modifications.disabled_metrics.remove(metric_name);

        // Add explicit override to enable
        let override_mod = self
            .modifications
            .metric_overrides
            .entry(metric_name.to_string())
            .or_insert_with(MetricOverrideModification::default);
        override_mod.enabled = Some(true);

        Ok(self)
    }

    /// Disable a specific metric
    ///
    /// # Arguments
    /// * `metric_name` - Name of the metric to disable (must exist in METRIC_REGISTRY)
    ///
    /// # Returns
    /// &mut Self for method chaining
    pub fn disable_metric(&mut self, metric_name: &str) -> ModifierResult<&mut Self> {
        self.validate_metric_name(metric_name)?;

        // Add to disabled set
        self.modifications
            .disabled_metrics
            .insert(metric_name.to_string());

        // Add explicit override to disable
        let override_mod = self
            .modifications
            .metric_overrides
            .entry(metric_name.to_string())
            .or_insert_with(MetricOverrideModification::default);
        override_mod.enabled = Some(false);

        Ok(self)
    }

    /// Set custom thresholds for a metric
    ///
    /// # Arguments
    /// * `metric_name` - Name of the metric (must exist in METRIC_REGISTRY)
    /// * `thresholds` - Vec of threshold values. Expected format: [min, optimal_min, optimal_max, max]
    ///
    /// # Returns
    /// &mut Self for method chaining
    pub fn set_threshold(
        &mut self,
        metric_name: &str,
        thresholds: Vec<f32>,
    ) -> ModifierResult<&mut Self> {
        self.validate_metric_name(metric_name)?;
        self.validate_threshold_vec(&thresholds)?;

        let override_mod = self
            .modifications
            .metric_overrides
            .entry(metric_name.to_string())
            .or_insert_with(MetricOverrideModification::default);
        override_mod.thresholds = Some(thresholds);

        Ok(self)
    }

    /// Set custom weight for a metric
    ///
    /// # Arguments
    /// * `metric_name` - Name of the metric (must exist in METRIC_REGISTRY)
    /// * `weight` - Weight value (0.0 to 10.0, where 1.0 is default)
    ///
    /// # Returns
    /// &mut Self for method chaining
    pub fn set_weight(&mut self, metric_name: &str, weight: f32) -> ModifierResult<&mut Self> {
        self.validate_metric_name(metric_name)?;
        self.validate_weight(weight)?;

        let override_mod = self
            .modifications
            .metric_overrides
            .entry(metric_name.to_string())
            .or_insert_with(MetricOverrideModification::default);
        override_mod.weight = Some(weight);

        Ok(self)
    }

    /// Set penalty multiplier for a metric
    ///
    /// # Arguments
    /// * `metric_name` - Name of the metric (must exist in METRIC_REGISTRY)
    /// * `multiplier` - Penalty multiplier (0.0 to 10.0, where 1.0 is default)
    ///
    /// # Returns
    /// &mut Self for method chaining
    pub fn set_penalty_multiplier(
        &mut self,
        metric_name: &str,
        multiplier: f32,
    ) -> ModifierResult<&mut Self> {
        self.validate_metric_name(metric_name)?;
        self.validate_penalty_multiplier(multiplier)?;

        let override_mod = self
            .modifications
            .metric_overrides
            .entry(metric_name.to_string())
            .or_insert_with(MetricOverrideModification::default);
        override_mod.penalty_multiplier = Some(multiplier);

        Ok(self)
    }

    /// Add a custom penalty
    ///
    /// # Arguments
    /// * `penalty` - The GlobalPenalty configuration to add
    ///
    /// # Returns
    /// &mut Self for method chaining
    pub fn add_penalty(&mut self, penalty: GlobalPenalty) -> &mut Self {
        self.modifications.custom_penalties.push(penalty);
        self
    }

    /// Add a custom bonus
    ///
    /// # Arguments
    /// * `bonus` - The GlobalBonus configuration to add
    ///
    /// # Returns
    /// &mut Self for method chaining
    pub fn add_bonus(&mut self, bonus: GlobalBonus) -> &mut Self {
        self.modifications.custom_bonuses.push(bonus);
        self
    }

    /// Get the base profile (for inspection)
    pub fn base_profile(&self) -> &EnhancedScoringProfile {
        &self.base_profile
    }

    /// Get the modifications (for inspection)
    pub fn modifications(&self) -> &ProfileModifications {
        &self.modifications
    }

    /// Check if a metric is disabled by modifications
    pub fn is_metric_disabled(&self, metric_name: &str) -> bool {
        self.modifications.disabled_metrics.contains(metric_name)
            || self
                .modifications
                .metric_overrides
                .get(metric_name)
                .and_then(|m| m.enabled)
                == Some(false)
    }

    /// Clear all modifications (reset to base profile)
    pub fn clear_modifications(&mut self) -> &mut Self {
        self.modifications = ProfileModifications::default();
        self
    }

    // Validation helpers

    fn validate_metric_name(&self, metric_name: &str) -> ModifierResult<()> {
        if METRIC_REGISTRY.get_metric_definition(metric_name).is_none() {
            return Err(AnalyzeError::InvalidMetricName(format!(
                "Unknown metric: '{}'. Check METRIC_REGISTRY for valid metric names.",
                metric_name
            )));
        }
        Ok(())
    }

    fn validate_threshold_vec(&self, thresholds: &[f32]) -> ModifierResult<()> {
        // Must have exactly 4 values: [min, optimal_min, optimal_max, max]
        if thresholds.len() != 4 {
            return Err(AnalyzeError::InvalidThreshold(format!(
                "Threshold vector must have exactly 4 values [min, optimal_min, optimal_max, max], got {}",
                thresholds.len()
            )));
        }

        let min = thresholds[0];
        let optimal_min = thresholds[1];
        let optimal_max = thresholds[2];
        let max = thresholds[3];

        // Validate ordering: min < optimal_min <= optimal_max < max
        if !(min < optimal_min) {
            return Err(AnalyzeError::InvalidThreshold(format!(
                "min ({}) must be < optimal_min ({})",
                min, optimal_min
            )));
        }
        if !(optimal_min <= optimal_max) {
            return Err(AnalyzeError::InvalidThreshold(format!(
                "optimal_min ({}) must be <= optimal_max ({})",
                optimal_min, optimal_max
            )));
        }
        if !(optimal_max < max) {
            return Err(AnalyzeError::InvalidThreshold(format!(
                "optimal_max ({}) must be < max ({})",
                optimal_max, max
            )));
        }

        // Validate all values are finite and non-negative
        for (i, &val) in thresholds.iter().enumerate() {
            if !val.is_finite() {
                let names = ["min", "optimal_min", "optimal_max", "max"];
                return Err(AnalyzeError::InvalidThreshold(format!(
                    "{} value must be finite (got {})",
                    names[i], val
                )));
            }
            if val < 0.0 {
                let names = ["min", "optimal_min", "optimal_max", "max"];
                return Err(AnalyzeError::InvalidThreshold(format!(
                    "{} value cannot be negative (got {})",
                    names[i], val
                )));
            }
        }

        Ok(())
    }

    fn validate_thresholds(&self, thresholds: &ThresholdSet) -> ModifierResult<()> {
        // Validate threshold ordering: poor <= fair <= good <= excellent
        if thresholds.poor > thresholds.fair {
            return Err(AnalyzeError::InvalidThreshold(format!(
                "poor ({}) must be <= fair ({})",
                thresholds.poor, thresholds.fair
            )));
        }
        if thresholds.fair > thresholds.good {
            return Err(AnalyzeError::InvalidThreshold(format!(
                "fair ({}) must be <= good ({})",
                thresholds.fair, thresholds.good
            )));
        }
        if thresholds.good > thresholds.excellent {
            return Err(AnalyzeError::InvalidThreshold(format!(
                "good ({}) must be <= excellent ({})",
                thresholds.good, thresholds.excellent
            )));
        }
        Ok(())
    }

    fn validate_weight(&self, weight: f32) -> ModifierResult<()> {
        if !weight.is_finite() {
            return Err(AnalyzeError::InvalidWeight(format!(
                "Weight must be finite, got {}",
                weight
            )));
        }
        if weight < 0.0 || weight > 10.0 {
            return Err(AnalyzeError::InvalidWeight(format!(
                "Weight must be between 0.0 and 10.0, got {}",
                weight
            )));
        }
        Ok(())
    }

    fn validate_penalty_multiplier(&self, multiplier: f32) -> ModifierResult<()> {
        if multiplier < 0.0 || multiplier > 10.0 {
            return Err(AnalyzeError::InvalidPenaltyMultiplier(format!(
                "Penalty multiplier must be between 0.0 and 10.0, got {}",
                multiplier
            )));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::enhanced_models::{
        BonusTrigger, GlobalBonus, GlobalPenalty, PenaltyTrigger, PenaltyType,
    };

    fn create_test_profile() -> Arc<EnhancedScoringProfile> {
        Arc::new(EnhancedScoringProfile::default_with_name("test_profile"))
    }

    #[test]
    fn test_new_profile_modifier() {
        let profile = create_test_profile();
        let modifier = ProfileModifier::new(profile.clone());

        assert_eq!(modifier.base_profile().metadata.name, profile.metadata.name);
        assert!(modifier.modifications().metric_overrides.is_empty());
        assert!(modifier.modifications().custom_penalties.is_empty());
        assert!(modifier.modifications().custom_bonuses.is_empty());
    }

    #[test]
    fn test_enable_metric() {
        let profile = create_test_profile();
        let mut modifier = ProfileModifier::new(profile);

        // Test enabling a valid metric
        let result = modifier.enable_metric("word_count");
        assert!(result.is_ok());
        assert!(!modifier.is_metric_disabled("word_count"));
    }

    #[test]
    fn test_disable_metric() {
        let profile = create_test_profile();
        let mut modifier = ProfileModifier::new(profile);

        // Test disabling a valid metric
        let result = modifier.disable_metric("word_count");
        assert!(result.is_ok());
        assert!(modifier.is_metric_disabled("word_count"));
    }

    #[test]
    fn test_invalid_metric_name() {
        let profile = create_test_profile();
        let mut modifier = ProfileModifier::new(profile);

        // Test with invalid metric name
        let result = modifier.enable_metric("nonexistent_metric");
        assert!(result.is_err());
    }

    #[test]
    fn test_set_weight() {
        let profile = create_test_profile();
        let mut modifier = ProfileModifier::new(profile);

        // Test setting valid weight
        let result = modifier.set_weight("word_count", 2.5);
        assert!(result.is_ok());

        // Test invalid weight (too high)
        let result = modifier.set_weight("word_count", 15.0);
        assert!(result.is_err());

        // Test invalid weight (negative)
        let result = modifier.set_weight("word_count", -1.0);
        assert!(result.is_err());
    }

    #[test]
    fn test_set_threshold() {
        let profile = create_test_profile();
        let mut modifier = ProfileModifier::new(profile);

        // Test with 4-value threshold vector: [min, optimal_min, optimal_max, max]
        let thresholds = vec![100.0, 500.0, 2000.0, 5000.0];

        let result = modifier.set_threshold("word_count", thresholds);
        assert!(result.is_ok());
    }

    #[test]
    fn test_invalid_threshold_ordering() {
        let profile = create_test_profile();
        let mut modifier = ProfileModifier::new(profile);

        // Invalid: min >= optimal_min
        let thresholds = vec![500.0, 100.0, 2000.0, 5000.0];
        let result = modifier.set_threshold("word_count", thresholds);
        assert!(result.is_err());

        // Invalid: optimal_max >= max
        let thresholds = vec![100.0, 500.0, 5000.0, 2000.0];
        let result = modifier.set_threshold("word_count", thresholds);
        assert!(result.is_err());

        // Invalid: wrong number of values
        let thresholds = vec![100.0, 500.0];
        let result = modifier.set_threshold("word_count", thresholds);
        assert!(result.is_err());
    }

    #[test]
    fn test_add_penalty() {
        let profile = create_test_profile();
        let mut modifier = ProfileModifier::new(profile);

        let penalty = GlobalPenalty {
            trigger_condition: PenaltyTrigger::MetricBelow {
                metric: "word_count".to_string(),
                threshold: 100.0,
            },
            penalty_type: PenaltyType::FixedPoints { points: 5.0 },
            description: "Test penalty".to_string(),
            enabled: true,
        };

        modifier.add_penalty(penalty);
        assert_eq!(modifier.modifications().custom_penalties.len(), 1);
    }

    #[test]
    fn test_add_bonus() {
        let profile = create_test_profile();
        let mut modifier = ProfileModifier::new(profile);

        let bonus = GlobalBonus {
            trigger_condition: BonusTrigger::MetricExcellence {
                metric: "word_count".to_string(),
                threshold: 1000.0,
            },
            bonus_points: 5.0,
            description: "Test bonus".to_string(),
            enabled: true,
        };

        modifier.add_bonus(bonus);
        assert_eq!(modifier.modifications().custom_bonuses.len(), 1);
    }

    #[test]
    fn test_apply_modifications() {
        let profile = create_test_profile();
        let mut modifier = ProfileModifier::new(profile);

        // Apply various modifications
        modifier.enable_metric("word_count").unwrap();
        modifier.set_weight("word_count", 2.0).unwrap();
        modifier.disable_metric("title_len").unwrap();

        // Apply modifications
        let modified_profile = modifier.apply_modifications();

        // Verify modifications were applied
        assert!(modified_profile.metric_overrides.contains_key("word_count"));
        assert_eq!(
            modified_profile
                .metric_overrides
                .get("word_count")
                .unwrap()
                .weight,
            2.0
        );

        assert!(modified_profile.metric_overrides.contains_key("title_len"));
        assert_eq!(
            modified_profile
                .metric_overrides
                .get("title_len")
                .unwrap()
                .enabled,
            false
        );
    }

    #[test]
    fn test_clear_modifications() {
        let profile = create_test_profile();
        let mut modifier = ProfileModifier::new(profile);

        // Add modifications
        modifier.enable_metric("word_count").unwrap();
        modifier.set_weight("word_count", 2.0).unwrap();

        // Clear modifications
        modifier.clear_modifications();

        // Verify all modifications are gone
        assert!(modifier.modifications().metric_overrides.is_empty());
        assert!(modifier.modifications().custom_penalties.is_empty());
        assert!(modifier.modifications().custom_bonuses.is_empty());
    }

    #[test]
    fn test_method_chaining() {
        let profile = create_test_profile();
        let mut modifier = ProfileModifier::new(profile);

        // Test method chaining
        let result = modifier
            .enable_metric("word_count")
            .and_then(|m| m.set_weight("word_count", 2.0))
            .and_then(|m| {
                m.set_threshold(
                    "word_count",
                    vec![50.0, 100.0, 500.0, 1000.0], // [min, optimal_min, optimal_max, max]
                )
            });

        assert!(result.is_ok());
    }
}