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
//! Profile Builder API for creating custom Enhanced Scoring Profiles
//!
//! This module provides a fluent API for building custom profiles programmatically.
//! The ProfileBuilder allows users to easily create profiles tailored to specific
//! content types with custom metric weights, thresholds, and content expectations.
//!
//! # Example
//!
//! ```rust
//! use webpage_quality_analyzer::config::profile_builder::{ProfileBuilder, ContentType};
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let profile = ProfileBuilder::new("my_custom_blog")
//!     .for_content_type(ContentType::LongFormArticle)
//!     .with_metric_weight("word_count", 0.30)
//!     .unwrap()
//!     .build()
//!     .unwrap();
//! # Ok(())
//! # }
//! ```

use crate::config::enhanced_models::*;
use crate::config::profile_validator::ProfileValidator;
use crate::metrics::ThresholdSet;
use chrono::Utc;
use std::collections::HashMap;

/// Error types that can occur during profile building
#[derive(Debug, Clone)]
pub enum BuilderError {
    /// Unknown metric name provided
    UnknownMetric(String),
    /// Invalid weight value (must be 0.0-1.0)
    InvalidWeight(String),
    /// Invalid threshold configuration
    InvalidThreshold(String),
    /// Profile validation failed
    ValidationFailed(String),
    /// Missing required fields
    MissingRequiredField(String),
}

impl std::fmt::Display for BuilderError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BuilderError::UnknownMetric(msg) => write!(f, "Unknown metric: {}", msg),
            BuilderError::InvalidWeight(msg) => write!(f, "Invalid weight: {}", msg),
            BuilderError::InvalidThreshold(msg) => write!(f, "Invalid threshold: {}", msg),
            BuilderError::ValidationFailed(msg) => write!(f, "Validation failed: {}", msg),
            BuilderError::MissingRequiredField(msg) => write!(f, "Missing required field: {}", msg),
        }
    }
}

impl std::error::Error for BuilderError {}

/// Content types for pre-configured profile templates
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContentType {
    /// Long-form articles, blog posts, editorial content (800-2500 words optimal)
    LongFormArticle,
    /// News articles, press releases (300-800 words optimal)
    NewsArticle,
    /// E-commerce product pages
    ProductPage,
    /// Marketing landing pages
    LandingPage,
    /// Portfolio/showcase pages
    Portfolio,
    /// Documentation pages
    Documentation,
    /// About/Company pages
    AboutPage,
}

/// Fluent API builder for creating EnhancedScoringProfile instances
///
/// The ProfileBuilder provides a convenient way to create custom profiles
/// with sensible defaults and type-safe configuration methods.
pub struct ProfileBuilder {
    profile: EnhancedScoringProfile,
    validator: ProfileValidator,
}

impl ProfileBuilder {
    /// Create a new ProfileBuilder with the given profile name
    ///
    /// # Arguments
    ///
    /// * `profile_name` - The name for the new profile
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use webpage_quality_analyzer::config::profile_builder::ProfileBuilder;
    ///
    /// let builder = ProfileBuilder::new("my_profile");
    /// ```
    pub fn new(profile_name: &str) -> Self {
        let mut profile = EnhancedScoringProfile::default_with_name(profile_name);

        // Set default category weights
        profile.category_weights.insert("content".to_string(), 0.40);
        profile.category_weights.insert("seo".to_string(), 0.25);
        profile
            .category_weights
            .insert("technical".to_string(), 0.15);
        profile
            .category_weights
            .insert("structure".to_string(), 0.15);
        profile
            .category_weights
            .insert("accessibility".to_string(), 0.05);

        Self {
            profile,
            validator: ProfileValidator::new(),
        }
    }

    /// Configure the profile for a specific content type with appropriate defaults
    ///
    /// This method applies pre-configured settings optimized for different content types.
    ///
    /// # Arguments
    ///
    /// * `content_type` - The type of content this profile will analyze
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use webpage_quality_analyzer::config::profile_builder::{ProfileBuilder, ContentType};
    ///
    /// let profile = ProfileBuilder::new("blog")
    ///     .for_content_type(ContentType::LongFormArticle)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn for_content_type(mut self, content_type: ContentType) -> Self {
        match content_type {
            ContentType::LongFormArticle => {
                self.profile
                    .category_weights
                    .insert("content".to_string(), 0.80);
                self.profile
                    .category_weights
                    .insert("structure".to_string(), 0.08);
                self.profile
                    .category_weights
                    .insert("seo".to_string(), 0.05);
                self.profile
                    .category_weights
                    .insert("technical".to_string(), 0.04);
                self.profile
                    .category_weights
                    .insert("accessibility".to_string(), 0.03);

                self.profile.content_expectations.word_count = Some(WordCountExpectation {
                    minimum: 500,
                    optimal_range: (1000, 3000),
                    maximum_useful: Some(8000),
                    penalty_curve: PenaltyCurve::Exponential { base: 2.0 },
                });

                self.profile.metadata.target_content_types = vec![
                    "article".to_string(),
                    "blog_post".to_string(),
                    "editorial".to_string(),
                ];
            }
            ContentType::NewsArticle => {
                self.profile
                    .category_weights
                    .insert("content".to_string(), 0.40);
                self.profile
                    .category_weights
                    .insert("structure".to_string(), 0.15);
                self.profile
                    .category_weights
                    .insert("seo".to_string(), 0.30);
                self.profile
                    .category_weights
                    .insert("technical".to_string(), 0.10);
                self.profile
                    .category_weights
                    .insert("accessibility".to_string(), 0.05);

                self.profile.content_expectations.word_count = Some(WordCountExpectation {
                    minimum: 150,
                    optimal_range: (300, 800),
                    maximum_useful: Some(1500),
                    penalty_curve: PenaltyCurve::Linear,
                });

                self.profile.metadata.target_content_types =
                    vec!["news".to_string(), "press_release".to_string()];
            }
            ContentType::ProductPage => {
                self.profile
                    .category_weights
                    .insert("content".to_string(), 0.25);
                self.profile
                    .category_weights
                    .insert("structure".to_string(), 0.15);
                self.profile
                    .category_weights
                    .insert("seo".to_string(), 0.35);
                self.profile
                    .category_weights
                    .insert("technical".to_string(), 0.15);
                self.profile
                    .category_weights
                    .insert("accessibility".to_string(), 0.10);

                self.profile.content_expectations.word_count = Some(WordCountExpectation {
                    minimum: 100,
                    optimal_range: (200, 500),
                    maximum_useful: Some(1000),
                    penalty_curve: PenaltyCurve::Linear,
                });

                self.profile.metadata.target_content_types =
                    vec!["product".to_string(), "ecommerce".to_string()];
            }
            ContentType::LandingPage => {
                self.profile
                    .category_weights
                    .insert("content".to_string(), 0.30);
                self.profile
                    .category_weights
                    .insert("structure".to_string(), 0.20);
                self.profile
                    .category_weights
                    .insert("seo".to_string(), 0.30);
                self.profile
                    .category_weights
                    .insert("technical".to_string(), 0.15);
                self.profile
                    .category_weights
                    .insert("accessibility".to_string(), 0.05);

                self.profile.content_expectations.word_count = Some(WordCountExpectation {
                    minimum: 200,
                    optimal_range: (300, 800),
                    maximum_useful: Some(1500),
                    penalty_curve: PenaltyCurve::Linear,
                });
            }
            ContentType::Portfolio => {
                self.profile
                    .category_weights
                    .insert("content".to_string(), 0.20);
                self.profile
                    .category_weights
                    .insert("structure".to_string(), 0.25);
                self.profile
                    .category_weights
                    .insert("seo".to_string(), 0.15);
                self.profile
                    .category_weights
                    .insert("technical".to_string(), 0.30);
                self.profile
                    .category_weights
                    .insert("accessibility".to_string(), 0.10);

                self.profile.content_expectations.word_count = Some(WordCountExpectation {
                    minimum: 100,
                    optimal_range: (200, 500),
                    maximum_useful: Some(1000),
                    penalty_curve: PenaltyCurve::Linear,
                });
            }
            ContentType::Documentation => {
                self.profile
                    .category_weights
                    .insert("content".to_string(), 0.50);
                self.profile
                    .category_weights
                    .insert("structure".to_string(), 0.25);
                self.profile
                    .category_weights
                    .insert("seo".to_string(), 0.10);
                self.profile
                    .category_weights
                    .insert("technical".to_string(), 0.10);
                self.profile
                    .category_weights
                    .insert("accessibility".to_string(), 0.05);

                self.profile.content_expectations.word_count = Some(WordCountExpectation {
                    minimum: 300,
                    optimal_range: (500, 2000),
                    maximum_useful: Some(5000),
                    penalty_curve: PenaltyCurve::Linear,
                });
            }
            ContentType::AboutPage => {
                self.profile
                    .category_weights
                    .insert("content".to_string(), 0.45);
                self.profile
                    .category_weights
                    .insert("structure".to_string(), 0.20);
                self.profile
                    .category_weights
                    .insert("seo".to_string(), 0.20);
                self.profile
                    .category_weights
                    .insert("technical".to_string(), 0.10);
                self.profile
                    .category_weights
                    .insert("accessibility".to_string(), 0.05);

                self.profile.content_expectations.word_count = Some(WordCountExpectation {
                    minimum: 200,
                    optimal_range: (400, 1000),
                    maximum_useful: Some(2000),
                    penalty_curve: PenaltyCurve::Linear,
                });
            }
        }

        self
    }

    /// Set a custom weight for a specific metric
    ///
    /// # Arguments
    ///
    /// * `metric_name` - The name of the metric to configure
    /// * `weight` - The weight value (0.0 to 1.0)
    ///
    /// # Errors
    ///
    /// Returns BuilderError::InvalidWeight if weight is outside 0.0-1.0 range
    pub fn with_metric_weight(
        mut self,
        metric_name: &str,
        weight: f32,
    ) -> Result<Self, BuilderError> {
        if !(0.0..=1.0).contains(&weight) {
            return Err(BuilderError::InvalidWeight(format!(
                "Weight must be between 0.0 and 1.0, got {}",
                weight
            )));
        }

        let metric_override = self
            .profile
            .metric_overrides
            .entry(metric_name.to_string())
            .or_insert_with(MetricOverride::default);
        metric_override.weight = weight;

        Ok(self)
    }

    /// Set custom thresholds for a specific metric
    ///
    /// # Arguments
    ///
    /// * `metric_name` - The name of the metric to configure
    /// * `thresholds` - The threshold values for excellent/good/fair/poor scoring
    pub fn with_custom_threshold(
        mut self,
        metric_name: &str,
        thresholds: ThresholdSet,
    ) -> Result<Self, BuilderError> {
        let metric_override = self
            .profile
            .metric_overrides
            .entry(metric_name.to_string())
            .or_insert_with(MetricOverride::default);
        metric_override.thresholds = Some(thresholds);

        Ok(self)
    }

    /// Set content expectations for the profile
    pub fn with_content_expectations(mut self, expectations: ContentExpectations) -> Self {
        self.profile.content_expectations = expectations;
        self
    }

    /// Set a description for the profile
    pub fn with_description(mut self, description: &str) -> Self {
        self.profile.metadata.description = description.to_string();
        self
    }

    /// Add tags to the profile metadata
    pub fn with_tags(mut self, tags: Vec<String>) -> Self {
        self.profile.metadata.tags = tags;
        self
    }

    /// Set category weights directly
    pub fn with_category_weights(mut self, weights: HashMap<String, f32>) -> Self {
        self.profile.category_weights = weights;
        self
    }

    /// Set quality band thresholds
    pub fn with_quality_bands(mut self, bands: QualityBandConfig) -> Self {
        self.profile.quality_bands = bands;
        self
    }

    /// Enable or disable a specific metric
    pub fn with_metric_enabled(mut self, metric_name: &str, enabled: bool) -> Self {
        let metric_override = self
            .profile
            .metric_overrides
            .entry(metric_name.to_string())
            .or_insert_with(MetricOverride::default);
        metric_override.enabled = enabled;
        self
    }

    /// Build and validate the profile
    ///
    /// This method finalizes the profile creation, validates all settings,
    /// and normalizes weights to sum to 1.0.
    ///
    /// # Errors
    ///
    /// Returns BuilderError::ValidationFailed if the profile configuration is invalid
    pub fn build(self) -> Result<EnhancedScoringProfile, BuilderError> {
        let mut profile = self.profile;

        // Set metadata timestamps
        profile.metadata.created_at = Utc::now().to_rfc3339();

        // Validate the profile
        let validation_result = self
            .validator
            .validate_profile(&profile)
            .map_err(|e| BuilderError::ValidationFailed(e.to_string()))?;

        if !validation_result.is_valid {
            return Err(BuilderError::ValidationFailed(format!(
                "Profile validation failed: {:?}",
                validation_result.errors
            )));
        }

        // Normalize weights
        self.validator
            .normalize_profile(&mut profile)
            .map_err(|e| BuilderError::ValidationFailed(e.to_string()))?;

        Ok(profile)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_builder_basic() {
        let profile = ProfileBuilder::new("test_profile")
            .with_description("A test profile")
            .build();

        if let Err(e) = &profile {
            eprintln!("Profile build failed: {:?}", e);
        }
        assert!(profile.is_ok());
        let profile = profile.unwrap();
        assert_eq!(profile.metadata.name, "test_profile");
    }

    #[test]
    fn test_builder_with_content_type() {
        let profile = ProfileBuilder::new("blog")
            .for_content_type(ContentType::LongFormArticle)
            .build();

        assert!(profile.is_ok());
        let profile = profile.unwrap();

        // Long-form articles should have high content weight
        assert!(profile.category_weights.get("content").unwrap() > &0.5);
        assert!(profile.content_expectations.word_count.is_some());
    }

    #[test]
    fn test_builder_with_custom_weights() {
        let profile = ProfileBuilder::new("custom")
            .for_content_type(ContentType::NewsArticle)
            .with_metric_weight("word_count", 0.30)
            .unwrap()
            .build();

        assert!(profile.is_ok());
        let profile = profile.unwrap();

        // Check custom metric override was applied
        assert!(profile.metric_overrides.contains_key("word_count"));
        let word_count_override = profile.metric_overrides.get("word_count").unwrap();
        assert_eq!(word_count_override.weight, 0.30);
    }

    #[test]
    fn test_builder_invalid_weight() {
        let result = ProfileBuilder::new("test").with_metric_weight("word_count", 1.5);

        assert!(result.is_err());
    }

    #[test]
    fn test_builder_all_content_types() {
        let content_types = vec![
            ContentType::LongFormArticle,
            ContentType::NewsArticle,
            ContentType::ProductPage,
            ContentType::LandingPage,
            ContentType::Portfolio,
            ContentType::Documentation,
            ContentType::AboutPage,
        ];

        for ct in content_types {
            let profile = ProfileBuilder::new("test").for_content_type(ct).build();

            assert!(
                profile.is_ok(),
                "Content type {:?} should build successfully",
                ct
            );
        }
    }
}