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
use crate::metrics::definitions::{BonusCondition, ThresholdSet};
/// Enhanced Profile Configuration Models for Phase 2
/// Provides rich, hierarchical profile configurations with comprehensive content expectations
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Configuration error types
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    #[error("Invalid configuration: {0}")]
    InvalidConfig(String),
    #[error("Missing required field: {0}")]
    MissingField(String),
    #[error("Validation error: {0}")]
    ValidationError(String),
}

/// Content type enumeration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ContentType {
    Article,
    Product,
    News,
    Blog,
    Documentation,
    LandingPage,
    Portfolio,
    ECommerce,
    LongFormArticle,
    ProductPage,
}

impl ContentType {
    pub fn as_str(&self) -> &'static str {
        match self {
            ContentType::Article => "article",
            ContentType::Product => "product",
            ContentType::News => "news",
            ContentType::Blog => "blog",
            ContentType::Documentation => "documentation",
            ContentType::LandingPage => "landing_page",
            ContentType::Portfolio => "portfolio",
            ContentType::ECommerce => "ecommerce",
            ContentType::LongFormArticle => "long_form_article",
            ContentType::ProductPage => "product_page",
        }
    }
}

impl Default for ContentType {
    fn default() -> Self {
        ContentType::Article
    }
}

/// Profile configuration (alias for compatibility)
pub type ProfileConfig = EnhancedScoringProfile;

/// Comparison operators for triggers
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ComparisonOperator {
    LessThan,
    GreaterThan,
    Equals,
    NotEquals,
    LessThanOrEqual,
    GreaterThanOrEqual,
}

/// Penalty trigger conditions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PenaltyTrigger {
    MetricThreshold {
        metric_name: String,
        operator: ComparisonOperator,
        threshold: f32,
    },
    ContentDeficiency {
        deficiency_type: String,
        severity: f32,
    },
    MultipleConditions {
        conditions: Vec<PenaltyTrigger>,
        operator: LogicalOperator,
    },
    MetricBelow {
        metric: String,
        threshold: f32,
    },
    MetricAbove {
        metric: String,
        threshold: f32,
    },
    MetricEquals {
        metric: String,
        value: f32,
    },
    MetricMissing {
        metric: String,
    },
}

/// Legacy alias for compatibility
pub type PenaltyTriggerCondition = PenaltyTrigger;

/// Bonus trigger conditions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum BonusTrigger {
    MetricThreshold {
        metric_name: String,
        operator: ComparisonOperator,
        threshold: f32,
    },
    ContentQuality {
        quality_type: String,
        requirement: String,
    },
    SynergyBonus {
        metrics: Vec<String>,
        combined_threshold: f32,
    },
    MetricExcellence {
        metric: String,
        threshold: f32,
    },
    MultipleMetricsGood {
        metrics: Vec<String>,
        threshold: f32,
    },
    CategoryExcellence {
        category: String,
        threshold: f32,
    },
}

/// Legacy alias for compatibility
pub type BonusTriggerCondition = BonusTrigger;

/// Logical operators
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LogicalOperator {
    And,
    Or,
}

/// Penalty amount types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PenaltyAmount {
    Fixed(f32),
    Percentage(f32),
    Multiplier(f32),
}

/// Legacy penalty type alias
pub type GlobalPenaltyType = PenaltyAmount;

/// Bonus amount types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum BonusAmount {
    Fixed(f32),
    Percentage(f32),
    Multiplier(f32),
}

/// Penalty severity levels
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PenaltySeverity {
    Low,
    Medium,
    High,
    Critical,
}

/// Enhanced scoring profile with complete configuration capabilities
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnhancedScoringProfile {
    pub metadata: ProfileMetadata,
    pub category_weights: CategoryWeights,
    pub metric_overrides: HashMap<String, MetricOverride>,
    pub content_expectations: ContentExpectations,
    pub quality_bands: QualityBandConfig,
    pub penalties: PenaltyConfig,
    pub bonuses: BonusConfig,
}

impl Default for EnhancedScoringProfile {
    fn default() -> Self {
        Self {
            metadata: ProfileMetadata::default(),
            category_weights: CategoryWeights::default(),
            metric_overrides: HashMap::new(),
            content_expectations: ContentExpectations::default(),
            quality_bands: QualityBandConfig::default(),
            penalties: PenaltyConfig::default(),
            bonuses: BonusConfig::default(),
        }
    }
}

impl EnhancedScoringProfile {
    pub fn default_with_name(name: &str) -> Self {
        let mut profile = Self::default();
        profile.metadata.name = name.to_string();
        profile.metadata.description = format!("Profile for {}", name);
        profile
    }
}

/// Profile metadata and descriptive information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileMetadata {
    pub name: String,
    pub description: String,
    pub target_content_types: Vec<String>,
    pub version: String,
    pub author: String,
    pub created_at: String,
    pub tags: Vec<String>,
}

impl Default for ProfileMetadata {
    fn default() -> Self {
        Self {
            name: "Unnamed Profile".to_string(),
            description: "Custom profile configuration".to_string(),
            target_content_types: vec!["general".to_string()],
            version: "1.0.0".to_string(),
            author: "user".to_string(),
            created_at: chrono::Utc::now().to_rfc3339(),
            tags: Vec::new(),
        }
    }
}

/// Category weight configuration
pub type CategoryWeights = HashMap<String, f32>;

/// Enhanced metric override configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricOverride {
    pub weight: f32,
    pub enabled: bool,
    pub thresholds: Option<ThresholdSet>,
    pub penalty_multiplier: f32,
    pub bonus_conditions: Vec<BonusCondition>,
    pub scoring_function_override: Option<ScoringFunctionOverride>,
}

impl Default for MetricOverride {
    fn default() -> Self {
        Self {
            weight: 1.0,
            enabled: true,
            thresholds: None,
            penalty_multiplier: 1.0,
            bonus_conditions: Vec::new(),
            scoring_function_override: None,
        }
    }
}

/// Scoring function override options
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ScoringFunctionOverride {
    Linear {
        min_value: f32,
        max_value: f32,
        reverse_scoring: bool,
    },
    Logarithmic {
        base: f32,
        scaling_factor: f32,
    },
    StepFunction {
        steps: Vec<(f32, f32)>, // (threshold, score)
    },
    CustomFunction {
        function_name: String,
    },
}

/// Content expectations for different profile types
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ContentExpectations {
    pub word_count: Option<WordCountExpectation>,
    pub heading_structure: Option<HeadingExpectation>,
    pub media_requirements: Option<MediaExpectation>,
    pub technical_requirements: Option<TechnicalExpectation>,
    pub seo_requirements: Option<SeoExpectation>,
}

/// Word count expectations and penalties
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WordCountExpectation {
    pub minimum: usize,
    pub optimal_range: (usize, usize),
    pub maximum_useful: Option<usize>, // Beyond this, more words don't help
    pub penalty_curve: PenaltyCurve,
}

/// Heading structure requirements
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HeadingExpectation {
    pub require_h1: bool,
    pub minimum_headings: usize,
    pub maximum_heading_depth: usize,
    pub logical_hierarchy: bool,
    pub heading_length_limits: Option<(usize, usize)>, // (min, max) characters per heading
}

/// Media content requirements
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MediaExpectation {
    pub minimum_images: usize,
    pub image_to_text_ratio: Option<(f32, f32)>, // (min, max) ratio
    pub alt_text_coverage: f32,                  // Required percentage of images with alt text
    pub require_audio: Option<bool>,
    pub require_video: Option<bool>,
    pub audio_duration_minimum: Option<usize>, // Seconds
    pub video_duration_minimum: Option<usize>, // Seconds
    pub transcript_preferred: Option<bool>,
}

/// Technical requirements for the page
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TechnicalExpectation {
    pub max_page_size_kb: Option<usize>,
    pub min_mobile_score: Option<f32>,
    pub required_meta_tags: Vec<String>,
    pub max_load_time_ms: Option<usize>,
    pub min_lighthouse_performance: Option<f32>,
    pub ssl_required: bool,
}

/// SEO-specific requirements
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SeoExpectation {
    pub title_length_range: Option<(usize, usize)>,
    pub meta_description_required: bool,
    pub meta_description_length_range: Option<(usize, usize)>,
    pub canonical_url_required: bool,
    pub structured_data_required: bool,
    pub open_graph_required: bool,
    pub keywords_density_range: Option<(f32, f32)>,
}

/// Penalty curve types for content deficiencies
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PenaltyCurve {
    Linear,
    Exponential { base: f32 },
    StepFunction { steps: Vec<(f32, f32)> },
}

/// Quality band configuration for score classification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityBandConfig {
    pub excellent: f32, // 90-100 score range
    pub good: f32,      // 70-89 score range
    pub fair: f32,      // 50-69 score range
    pub poor: f32,      // 30-49 score range
                        // Below poor = 0-29 range
}

impl Default for QualityBandConfig {
    fn default() -> Self {
        Self {
            excellent: 85.0,
            good: 70.0,
            fair: 50.0,
            poor: 30.0,
        }
    }
}

/// Global penalty configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PenaltyConfig {
    pub severe_penalties: HashMap<String, GlobalPenalty>,
    pub moderate_penalties: HashMap<String, GlobalPenalty>,
    pub light_penalties: HashMap<String, GlobalPenalty>,
}

/// Individual penalty definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GlobalPenalty {
    pub trigger_condition: PenaltyTrigger,
    pub penalty_type: PenaltyType,
    pub description: String,
    pub enabled: bool,
}

// Penalty trigger conditions already defined above

/// Penalty types and magnitudes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PenaltyType {
    FixedPoints { points: f32 },
    Multiplier { factor: f32 },
    CategoryPenalty { category: String, multiplier: f32 },
}

/// Content deficiency severity levels
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DeficiencySeverity {
    Minimal,  // 0-25% below expectation
    Moderate, // 25-50% below expectation
    Severe,   // 50-75% below expectation
    Critical, // 75%+ below expectation
}

/// Global bonus configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct BonusConfig {
    pub excellence_bonuses: HashMap<String, GlobalBonus>,
    pub achievement_bonuses: HashMap<String, GlobalBonus>,
    pub synergy_bonuses: HashMap<String, GlobalBonus>,
}

/// Individual bonus definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GlobalBonus {
    pub trigger_condition: BonusTrigger,
    pub bonus_points: f32,
    pub description: String,
    pub enabled: bool,
}

// Bonus trigger conditions already defined above

// Content type enumeration and impl already defined above

/// Validation result for profile configurations
#[derive(Debug, Clone)]
pub struct ValidationReport {
    pub is_valid: bool,
    pub warnings: Vec<String>,
    pub errors: Vec<String>,
    pub suggestions: Vec<String>,
}

impl ValidationReport {
    pub fn new() -> Self {
        Self {
            is_valid: true,
            warnings: Vec::new(),
            errors: Vec::new(),
            suggestions: Vec::new(),
        }
    }

    pub fn add_error(&mut self, error: String) {
        self.errors.push(error);
        self.is_valid = false;
    }

    pub fn add_warning(&mut self, warning: String) {
        self.warnings.push(warning);
    }

    pub fn add_suggestion(&mut self, suggestion: String) {
        self.suggestions.push(suggestion);
    }
}

/// Content validation results
#[derive(Debug, Clone)]
pub struct ContentValidationResult {
    pub violations: Vec<ContentViolation>,
    pub penalties: Vec<ContentPenalty>,
    pub compliance_score: f32,
}

/// Content violation types
#[derive(Debug, Clone)]
pub enum ContentViolation {
    InsufficientWordCount {
        actual: usize,
        minimum: usize,
        severity: DeficiencySeverity,
    },
    ExcessiveWordCount {
        actual: usize,
        maximum_useful: usize,
    },
    MissingHeadings {
        actual: usize,
        minimum: usize,
    },
    InvalidHeadingStructure {
        issue: String,
    },
    InsufficientMedia {
        media_type: String,
        actual: usize,
        minimum: usize,
    },
    TechnicalRequirementMissing {
        requirement: String,
    },
    SeoRequirementMissing {
        requirement: String,
    },
}

/// Content penalty applied for violations
#[derive(Debug, Clone)]
pub struct ContentPenalty {
    pub violation_type: String,
    pub penalty_points: f32,
    pub description: String,
}

/// Phase 3 compatibility ensured through existing types

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

    #[test]
    fn test_enhanced_profile_creation() {
        let profile = EnhancedScoringProfile::default_with_name("Test Profile");
        assert_eq!(profile.metadata.name, "Test Profile");
        assert_eq!(profile.metadata.description, "Profile for Test Profile");
        assert!(!profile.metadata.created_at.is_empty());
    }

    #[test]
    fn test_content_expectations_default() {
        let expectations = ContentExpectations::default();
        assert!(expectations.word_count.is_none());
        assert!(expectations.heading_structure.is_none());
        assert!(expectations.media_requirements.is_none());
    }

    #[test]
    fn test_quality_band_defaults() {
        let bands = QualityBandConfig::default();
        assert_eq!(bands.excellent, 85.0);
        assert_eq!(bands.good, 70.0);
        assert_eq!(bands.fair, 50.0);
        assert_eq!(bands.poor, 30.0);
    }

    #[test]
    fn test_validation_report() {
        let mut report = ValidationReport::new();
        assert!(report.is_valid);

        report.add_error("Test error".to_string());
        assert!(!report.is_valid);
        assert_eq!(report.errors.len(), 1);

        report.add_warning("Test warning".to_string());
        assert_eq!(report.warnings.len(), 1);
    }

    #[test]
    fn test_content_type_string_conversion() {
        assert_eq!(ContentType::LongFormArticle.as_str(), "long_form_article");
        assert_eq!(ContentType::ProductPage.as_str(), "product_page");
        assert_eq!(ContentType::Article.as_str(), "article");
        assert_eq!(ContentType::News.as_str(), "news");
    }
}