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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
/// Comprehensive Configuration System Tests
/// Tests all configuration loading methods, formats, and features of the API
///
/// This test suite covers:
/// - Level 3 API: Configuration file loading (YAML, JSON, TOML)
/// - Level 2 API: Builder pattern with various options
/// - ConfigManager features: Profile loading, switching, validation
/// - Built-in profiles: Accessing and using all default profiles
/// - Custom profiles: Creating and using custom scoring profiles
/// - Error handling: Invalid configs, missing files, malformed data
use std::fs;
use tempfile::tempdir;
use webpage_quality_analyzer::async_runtime::DefaultRuntime;
use webpage_quality_analyzer::*;

// ==================== Helper Functions ====================

/// Create a minimal valid YAML config
fn create_minimal_yaml_config() -> String {
    r#"
active_profile: "test_profile"

presets:
  test_profile:
    metadata:
      name: "Test Profile"
      description: "Minimal test configuration"
      target_content_types: ["article"]
      version: "1.0.0"
      author: "test"
      created_at: "2025-01-01T00:00:00Z"
      tags: ["test"]
    category_weights:
      content: 0.4
      seo: 0.3
      technical: 0.2
      accessibility: 0.1
      structure: 0.0
      media: 0.0
      links: 0.0
      mobile: 0.0
      authority: 0.0
      language: 0.0
      forms: 0.0
      structureddata: 0.0
      branding: 0.0
      userexperience: 0.0
      business: 0.0
      internationalization: 0.0
      performance: 0.0
      security: 0.0
      analytics: 0.0
      errorhandling: 0.0
    metric_overrides: {}
    content_expectations:
      min_word_count: 100
      min_paragraph_count: 3
      min_heading_count: 2
      expected_heading_structure: ["h1", "h2"]
      min_main_text_ratio: 0.5
      min_image_alt_coverage: 0.8
      required_meta_tags: ["description"]
      recommended_meta_tags: ["keywords", "author"]
    quality_bands:
      excellent: 85.0
      good: 65.0
      fair: 45.0
      poor: 25.0
    penalties:
      severe_penalties: {}
      moderate_penalties: {}
      light_penalties: {}
    bonuses:
      excellence_bonuses: {}
      achievement_bonuses: {}
      synergy_bonuses: {}

output:
  include_debug: false
  include_raw_metrics: true
  timestamp_format: "ISO8601"
  float_precision: 2
"#
    .to_string()
}

/// Create a JSON config with custom metric overrides
fn create_json_config_with_overrides() -> String {
    r#"{
  "active_profile": "custom_profile",
  "presets": {
    "custom_profile": {
      "metadata": {
        "name": "Custom Profile",
        "description": "Profile with custom metric weights",
        "target_content_types": ["blog", "article"],
        "version": "1.0.0",
        "author": "test",
        "created_at": "2025-01-01T00:00:00Z",
        "tags": ["custom", "test"]
      },
      "category_weights": {
        "content": 0.5,
        "seo": 0.2,
        "technical": 0.15,
        "accessibility": 0.15,
        "structure": 0.0,
        "media": 0.0,
        "links": 0.0,
        "mobile": 0.0,
        "authority": 0.0,
        "language": 0.0,
        "forms": 0.0,
        "structureddata": 0.0,
        "branding": 0.0,
        "userexperience": 0.0,
        "business": 0.0,
        "internationalization": 0.0,
        "performance": 0.0,
        "security": 0.0,
        "analytics": 0.0,
        "errorhandling": 0.0
      },
      "metric_overrides": {
        "word_count": {
          "weight": 2.0,
          "enabled": true,
          "thresholds": null,
          "penalty_multiplier": 1.0,
          "bonus_conditions": [],
          "scoring_function_override": null
        },
        "readability_fk": {
          "weight": 1.5,
          "enabled": true,
          "thresholds": null,
          "penalty_multiplier": 1.0,
          "bonus_conditions": [],
          "scoring_function_override": null
        }
      },
      "content_expectations": {
        "min_word_count": 500,
        "min_paragraph_count": 5,
        "min_heading_count": 3,
        "expected_heading_structure": ["h1", "h2", "h3"],
        "min_main_text_ratio": 0.6,
        "min_image_alt_coverage": 0.9,
        "required_meta_tags": ["description", "keywords"],
        "recommended_meta_tags": ["author", "publish_date"]
      },
      "quality_bands": {
        "excellent": 90.0,
        "good": 70.0,
        "fair": 50.0,
        "poor": 30.0
      },
      "penalties": {
        "severe_penalties": {},
        "moderate_penalties": {},
        "light_penalties": {}
      },
      "bonuses": {
        "excellence_bonuses": {},
        "achievement_bonuses": {},
        "synergy_bonuses": {}
      }
    }
  },
  "output": {
    "include_debug": true,
    "include_raw_metrics": true,
    "timestamp_format": "ISO8601",
    "float_precision": 3
  }
}"#
    .to_string()
}

/// Create a TOML config
fn create_toml_config() -> String {
    r#"
active_profile = "toml_profile"

[output]
include_debug = false
include_raw_metrics = false
timestamp_format = "ISO8601"
float_precision = 2

[presets.toml_profile.metadata]
name = "TOML Profile"
description = "Testing TOML configuration format"
target_content_types = ["article"]
version = "1.0.0"
author = "test"
created_at = "2025-01-01T00:00:00Z"
tags = ["toml", "test"]

[presets.toml_profile.category_weights]
content = 0.6
seo = 0.2
technical = 0.1
accessibility = 0.1
structure = 0.0
media = 0.0
links = 0.0
mobile = 0.0
authority = 0.0
language = 0.0
forms = 0.0
structureddata = 0.0
branding = 0.0
userexperience = 0.0
business = 0.0
internationalization = 0.0
performance = 0.0
security = 0.0
analytics = 0.0
errorhandling = 0.0

[presets.toml_profile.metric_overrides]

[presets.toml_profile.content_expectations]
min_word_count = 200
min_paragraph_count = 4
min_heading_count = 2
expected_heading_structure = ["h1", "h2"]
min_main_text_ratio = 0.5
min_image_alt_coverage = 0.75
required_meta_tags = ["description"]
recommended_meta_tags = ["keywords"]

[presets.toml_profile.quality_bands]
excellent = 85.0
good = 65.0
fair = 45.0
poor = 25.0

[presets.toml_profile.penalties]
severe_penalties = {}
moderate_penalties = {}
light_penalties = {}

[presets.toml_profile.bonuses]
excellence_bonuses = {}
achievement_bonuses = {}
synergy_bonuses = {}
"#
    .to_string()
}

/// Sample HTML for testing
fn get_test_html() -> &'static str {
    r#"
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Test Article - Quality Analysis</title>
        <meta name="description" content="This is a comprehensive test article for configuration testing">
        <meta name="keywords" content="test, quality, analysis">
        <meta name="author" content="Test Author">
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <header>
            <h1>Test Article Title</h1>
        </header>
        <main>
            <article>
                <h2>Introduction</h2>
                <p>This is the first paragraph with substantial content. It contains enough words to be considered meaningful for quality analysis purposes. We want to ensure that all configuration options are properly tested.</p>
                <p>Here's a second paragraph providing more context and content depth. The analyzer should process this content according to the active configuration profile settings.</p>
                
                <h2>Main Content Section</h2>
                <p>This section contains the primary content of our test article. It includes multiple paragraphs, proper heading structure, and various HTML elements to trigger different metrics.</p>
                <p>Another paragraph with more detailed information. Quality analyzers need substantial content to provide accurate scoring and recommendations.</p>
                <p>A third paragraph ensures we meet minimum content requirements. Configuration profiles can specify different thresholds for word count, paragraph count, and other content metrics.</p>
                
                <h3>Subsection with Details</h3>
                <p>Nested heading structures are important for SEO and content organization. This subsection provides additional detail and demonstrates proper HTML hierarchy.</p>
                <p>More content here to ensure we have enough text for various analysis metrics including readability scores and content density calculations.</p>
                
                <h2>Conclusion</h2>
                <p>The final section wraps up the content with concluding remarks. This ensures we have a complete article structure with beginning, middle, and end.</p>
                <p>Last paragraph providing closure and maintaining content quality throughout the entire document.</p>
            </article>
        </main>
        <footer>
            <p>&copy; 2025 Test Organization</p>
        </footer>
    </body>
    </html>
    "#
}

// ==================== Level 3 API Tests: Configuration File Loading ====================

#[tokio::test]
async fn test_yaml_config_file_loading() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("test.yaml");

    fs::write(&config_path, create_minimal_yaml_config()).unwrap();

    let result = from_config_file(&config_path);
    assert!(
        result.is_ok(),
        "Failed to load YAML config: {:?}",
        result.err()
    );

    let analyzer = result.unwrap();
    let profile_name = analyzer.get_active_profile_name().unwrap();
    assert_eq!(profile_name, "test_profile");
}

#[tokio::test]
async fn test_json_config_file_loading() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("test.json");

    fs::write(&config_path, create_json_config_with_overrides()).unwrap();

    let result = from_config_file(&config_path);
    assert!(
        result.is_ok(),
        "Failed to load JSON config: {:?}",
        result.err()
    );

    let analyzer = result.unwrap();
    let profile_name = analyzer.get_active_profile_name().unwrap();
    assert_eq!(profile_name, "custom_profile");
}

#[tokio::test]
async fn test_toml_config_file_loading() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("test.toml");

    fs::write(&config_path, create_toml_config()).unwrap();

    let result = from_config_file(&config_path);
    assert!(
        result.is_ok(),
        "Failed to load TOML config: {:?}",
        result.err()
    );

    let analyzer = result.unwrap();
    let profile_name = analyzer.get_active_profile_name().unwrap();
    assert_eq!(profile_name, "toml_profile");
}

#[tokio::test]
async fn test_config_file_analysis_execution() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("analysis_test.yaml");

    fs::write(&config_path, create_minimal_yaml_config()).unwrap();

    let analyzer = from_config_file(&config_path).unwrap();
    let html = get_test_html();

    let result = analyzer.run("https://example.com/test", Some(html)).await;
    assert!(result.is_ok(), "Analysis failed: {:?}", result.err());

    let report = result.unwrap();
    assert!(report.score >= 0.0 && report.score <= 100.0);
    assert!(report.metrics.html_analysis.content.word_count > 0);
}

#[tokio::test]
async fn test_config_file_with_multiple_profiles() {
    let config = r#"
active_profile: "profile_a"

presets:
  profile_a:
    metadata:
      name: "Profile A"
      description: "First profile"
      target_content_types: ["article"]
      version: "1.0.0"
      author: "test"
      created_at: "2025-01-01T00:00:00Z"
      tags: ["test"]
    category_weights:
      content: 0.5
      seo: 0.3
      technical: 0.2
      accessibility: 0.0
      structure: 0.0
      media: 0.0
      links: 0.0
      mobile: 0.0
      authority: 0.0
      language: 0.0
      forms: 0.0
      structureddata: 0.0
      branding: 0.0
      userexperience: 0.0
      business: 0.0
      internationalization: 0.0
      performance: 0.0
      security: 0.0
      analytics: 0.0
      errorhandling: 0.0
    metric_overrides: {}
    content_expectations:
      min_word_count: 100
      min_paragraph_count: 2
      min_heading_count: 1
      expected_heading_structure: []
      min_main_text_ratio: 0.5
      min_image_alt_coverage: 0.7
      required_meta_tags: []
      recommended_meta_tags: []
    quality_bands:
      excellent: 85.0
      good: 65.0
      fair: 45.0
      poor: 25.0
    penalties:
      severe_penalties: {}
      moderate_penalties: {}
      light_penalties: {}
    bonuses:
      excellence_bonuses: {}
      achievement_bonuses: {}
      synergy_bonuses: {}
  
  profile_b:
    metadata:
      name: "Profile B"
      description: "Second profile"
      target_content_types: ["blog"]
      version: "1.0.0"
      author: "test"
      created_at: "2025-01-01T00:00:00Z"
      tags: ["test"]
    category_weights:
      content: 0.4
      seo: 0.4
      technical: 0.2
      accessibility: 0.0
      structure: 0.0
      media: 0.0
      links: 0.0
      mobile: 0.0
      authority: 0.0
      language: 0.0
      forms: 0.0
      structureddata: 0.0
      branding: 0.0
      userexperience: 0.0
      business: 0.0
      internationalization: 0.0
      performance: 0.0
      security: 0.0
      analytics: 0.0
      errorhandling: 0.0
    metric_overrides: {}
    content_expectations:
      min_word_count: 200
      min_paragraph_count: 3
      min_heading_count: 2
      expected_heading_structure: []
      min_main_text_ratio: 0.6
      min_image_alt_coverage: 0.8
      required_meta_tags: []
      recommended_meta_tags: []
    quality_bands:
      excellent: 90.0
      good: 70.0
      fair: 50.0
      poor: 30.0
    penalties:
      severe_penalties: {}
      moderate_penalties: {}
      light_penalties: {}
    bonuses:
      excellence_bonuses: {}
      achievement_bonuses: {}
      synergy_bonuses: {}
"#;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("multi_profile.yaml");
    fs::write(&config_path, config).unwrap();

    let analyzer = from_config_file(&config_path).unwrap();

    // Verify active profile is profile_a
    let active_profile = analyzer.get_active_profile_name().unwrap();
    assert_eq!(active_profile, "profile_a");
}

// ==================== Level 2 API Tests: Builder Pattern ====================

#[tokio::test]
async fn test_builder_with_default_profile() {
    let result = Analyzer::<DefaultRuntime>::builder().with_profile_name("content_article");

    assert!(result.is_ok(), "Failed to set profile: {:?}", result.err());

    let builder_result = result.unwrap().build();
    assert!(
        builder_result.is_ok(),
        "Failed to build analyzer: {:?}",
        builder_result.err()
    );
}

#[tokio::test]
async fn test_builder_with_all_built_in_profiles() {
    let profiles = vec!["content_article", "news", "blog", "product", "general"];

    for profile_name in profiles {
        let result = Analyzer::<DefaultRuntime>::builder()
            .with_profile_name(profile_name)
            .and_then(|b| b.build());

        assert!(
            result.is_ok(),
            "Failed to build analyzer with '{}' profile: {:?}",
            profile_name,
            result.err()
        );
    }
}

#[tokio::test]
async fn test_builder_with_linkcheck_enabled() {
    let analyzer = Analyzer::<DefaultRuntime>::builder()
        .with_profile_name("content_article")
        .unwrap()
        .enable_linkcheck(true)
        .build()
        .unwrap();

    // Run analysis to ensure linkcheck doesn't break
    let html = get_test_html();
    let result = analyzer.run("https://example.com", Some(html)).await;
    assert!(result.is_ok());
}

#[tokio::test]
async fn test_builder_with_nlp_enabled() {
    let analyzer = Analyzer::<DefaultRuntime>::builder()
        .with_profile_name("content_article")
        .unwrap()
        .enable_nlp(true)
        .build()
        .unwrap();

    let html = get_test_html();
    let result = analyzer.run("https://example.com", Some(html)).await;
    assert!(result.is_ok());
}

#[tokio::test]
async fn test_builder_with_custom_linkcheck_sample() {
    let analyzer = Analyzer::<DefaultRuntime>::builder()
        .with_profile_name("content_article")
        .unwrap()
        .enable_linkcheck(true)
        .linkcheck_sample(10)
        .build()
        .unwrap();

    let html = get_test_html();
    let result = analyzer.run("https://example.com", Some(html)).await;
    assert!(result.is_ok());
}

#[tokio::test]
async fn test_builder_with_config_path() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("builder_test.yaml");
    fs::write(&config_path, create_minimal_yaml_config()).unwrap();

    let result = Analyzer::<DefaultRuntime>::builder().with_config_path(&config_path);

    assert!(
        result.is_ok(),
        "Failed to load config path: {:?}",
        result.err()
    );

    let analyzer = result.unwrap().build().unwrap();
    let html = get_test_html();
    let report = analyzer
        .run("https://example.com", Some(html))
        .await
        .unwrap();

    assert!(report.score >= 0.0);
}

#[tokio::test]
async fn test_builder_chaining_multiple_options() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("chain_test.yaml");
    fs::write(&config_path, create_minimal_yaml_config()).unwrap();

    let analyzer = Analyzer::<DefaultRuntime>::builder()
        .with_config_path(&config_path)
        .unwrap()
        .enable_nlp(true)
        .enable_linkcheck(false)
        .add_report(true)
        .build()
        .unwrap();

    let html = get_test_html();
    let result = analyzer.run("https://example.com", Some(html)).await;
    assert!(result.is_ok());
}

// ==================== ConfigManager Tests ====================

#[test]
fn test_config_manager_creation() {
    let manager = ConfigManager::new();

    // Default profile should be loaded
    let active_profile = manager.get_active_profile_name();
    assert!(active_profile.is_ok());
}

#[test]
fn test_config_manager_get_profile() {
    let manager = ConfigManager::new();

    // Should be able to get default profile
    let profile = manager.get_profile("content_article");
    assert!(
        profile.is_some(),
        "Default profile 'content_article' should exist"
    );
}

#[test]
fn test_config_manager_from_yaml_file() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("manager_test.yaml");
    fs::write(&config_path, create_minimal_yaml_config()).unwrap();

    let result = ConfigManager::from_file(&config_path);
    assert!(
        result.is_ok(),
        "Failed to load ConfigManager from YAML: {:?}",
        result.err()
    );

    let manager = result.unwrap();
    let profile = manager.get_profile("test_profile");
    assert!(profile.is_some());
}

#[test]
fn test_config_manager_from_json_file() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("manager_test.json");
    fs::write(&config_path, create_json_config_with_overrides()).unwrap();

    let result = ConfigManager::from_file(&config_path);
    assert!(
        result.is_ok(),
        "Failed to load ConfigManager from JSON: {:?}",
        result.err()
    );
}

#[test]
fn test_config_manager_from_toml_file() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("manager_test.toml");
    fs::write(&config_path, create_toml_config()).unwrap();

    let result = ConfigManager::from_file(&config_path);
    assert!(
        result.is_ok(),
        "Failed to load ConfigManager from TOML: {:?}",
        result.err()
    );
}

#[test]
fn test_config_manager_profile_switching() {
    let config = r#"
active_profile: "profile_one"

presets:
  profile_one:
    metadata:
      name: "Profile One"
      description: "First profile"
      target_content_types: ["article"]
      version: "1.0.0"
      author: "test"
      created_at: "2025-01-01T00:00:00Z"
      tags: ["test"]
    category_weights:
      content: 1.0
      seo: 0.0
      technical: 0.0
      accessibility: 0.0
      structure: 0.0
      media: 0.0
      links: 0.0
      mobile: 0.0
      authority: 0.0
      language: 0.0
      forms: 0.0
      structureddata: 0.0
      branding: 0.0
      userexperience: 0.0
      business: 0.0
      internationalization: 0.0
      performance: 0.0
      security: 0.0
      analytics: 0.0
      errorhandling: 0.0
    metric_overrides: {}
    content_expectations:
      min_word_count: 50
      min_paragraph_count: 1
      min_heading_count: 1
      expected_heading_structure: []
      min_main_text_ratio: 0.5
      min_image_alt_coverage: 0.7
      required_meta_tags: []
      recommended_meta_tags: []
    quality_bands:
      excellent: 85.0
      good: 65.0
      fair: 45.0
      poor: 25.0
    penalties:
      severe_penalties: {}
      moderate_penalties: {}
      light_penalties: {}
    bonuses:
      excellence_bonuses: {}
      achievement_bonuses: {}
      synergy_bonuses: {}
  
  profile_two:
    metadata:
      name: "Profile Two"
      description: "Second profile"
      target_content_types: ["blog"]
      version: "1.0.0"
      author: "test"
      created_at: "2025-01-01T00:00:00Z"
      tags: ["test"]
    category_weights:
      content: 0.5
      seo: 0.5
      technical: 0.0
      accessibility: 0.0
      structure: 0.0
      media: 0.0
      links: 0.0
      mobile: 0.0
      authority: 0.0
      language: 0.0
      forms: 0.0
      structureddata: 0.0
      branding: 0.0
      userexperience: 0.0
      business: 0.0
      internationalization: 0.0
      performance: 0.0
      security: 0.0
      analytics: 0.0
      errorhandling: 0.0
    metric_overrides: {}
    content_expectations:
      min_word_count: 100
      min_paragraph_count: 2
      min_heading_count: 1
      expected_heading_structure: []
      min_main_text_ratio: 0.5
      min_image_alt_coverage: 0.7
      required_meta_tags: []
      recommended_meta_tags: []
    quality_bands:
      excellent: 85.0
      good: 65.0
      fair: 45.0
      poor: 25.0
    penalties:
      severe_penalties: {}
      moderate_penalties: {}
      light_penalties: {}
    bonuses:
      excellence_bonuses: {}
      achievement_bonuses: {}
      synergy_bonuses: {}
"#;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("switch_test.yaml");
    fs::write(&config_path, config).unwrap();

    let mut manager = ConfigManager::from_file(&config_path).unwrap();

    // Initially should be profile_one
    assert_eq!(manager.get_active_profile_name().unwrap(), "profile_one");

    // Switch to profile_two
    let result = manager.set_active_profile("profile_two");
    assert!(
        result.is_ok(),
        "Failed to switch profile: {:?}",
        result.err()
    );

    assert_eq!(manager.get_active_profile_name().unwrap(), "profile_two");
}

// ==================== Error Handling Tests ====================

#[test]
fn test_nonexistent_config_file() {
    let result = from_config_file("nonexistent_file.yaml");
    assert!(result.is_err(), "Should fail with nonexistent file");
}

#[test]
fn test_invalid_yaml_config() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("invalid.yaml");
    fs::write(&config_path, "invalid: yaml: content:").unwrap();

    let result = from_config_file(&config_path);
    assert!(result.is_err(), "Should fail with invalid YAML");
}

#[test]
fn test_invalid_json_config() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("invalid.json");
    fs::write(&config_path, r#"{"invalid": "json"#).unwrap();

    let result = from_config_file(&config_path);
    assert!(result.is_err(), "Should fail with invalid JSON");
}

#[test]
fn test_unsupported_file_extension() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("config.txt");
    fs::write(&config_path, "some content").unwrap();

    let result = from_config_file(&config_path);
    assert!(result.is_err(), "Should fail with unsupported extension");
}

#[tokio::test]
async fn test_builder_with_invalid_profile_name() {
    let result = Analyzer::<DefaultRuntime>::builder()
        .with_profile_name("nonexistent_profile")
        .and_then(|b| b.build());

    assert!(result.is_err(), "Should fail with invalid profile name");
}

#[test]
fn test_config_with_missing_required_fields() {
    let incomplete_config = r#"
active_profile: "incomplete"

presets:
  incomplete:
    metadata:
      name: "Incomplete"
"#;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("incomplete.yaml");
    fs::write(&config_path, incomplete_config).unwrap();

    let result = ConfigManager::from_file(&config_path);
    assert!(result.is_err(), "Should fail with missing required fields");
}

// ==================== Built-in Profile Tests ====================

#[tokio::test]
async fn test_all_builtin_profiles_work() {
    let profiles = vec!["content_article", "news", "blog", "product", "general"];

    let html = get_test_html();

    for profile in profiles {
        let result = analyze_with_profile("https://example.com", Some(html), profile).await;
        assert!(
            result.is_ok(),
            "Profile '{}' should work: {:?}",
            profile,
            result.err()
        );

        let report = result.unwrap();
        assert!(report.score >= 0.0 && report.score <= 100.0);
    }
}

#[tokio::test]
async fn test_profile_affects_scoring() {
    let html = r#"
        <html>
        <head>
            <title>SEO Optimized Page</title>
            <meta name="description" content="Great description">
            <meta name="keywords" content="seo, test">
        </head>
        <body>
            <h1>Title</h1>
            <p>Some content here.</p>
        </body>
        </html>
    "#;

    let report_article = analyze_with_profile("https://example.com", Some(html), "content_article")
        .await
        .unwrap();

    let report_product = analyze_with_profile("https://example.com", Some(html), "product")
        .await
        .unwrap();

    // Both should produce valid scores
    assert!(report_article.score >= 0.0 && report_article.score <= 100.0);
    assert!(report_product.score >= 0.0 && report_product.score <= 100.0);

    println!("Article score: {}", report_article.score);
    println!("Product score: {}", report_product.score);
}

// ==================== Output Configuration Tests ====================

#[tokio::test]
async fn test_output_configuration_options() {
    let config = r#"
active_profile: "test_output"

presets:
  test_output:
    metadata:
      name: "Output Test"
      description: "Testing output configuration"
      target_content_types: ["article"]
      version: "1.0.0"
      author: "test"
      created_at: "2025-01-01T00:00:00Z"
      tags: ["test"]
    category_weights:
      content: 1.0
      seo: 0.0
      technical: 0.0
      accessibility: 0.0
      structure: 0.0
      media: 0.0
      links: 0.0
      mobile: 0.0
      authority: 0.0
      language: 0.0
      forms: 0.0
      structureddata: 0.0
      branding: 0.0
      userexperience: 0.0
      business: 0.0
      internationalization: 0.0
      performance: 0.0
      security: 0.0
      analytics: 0.0
      errorhandling: 0.0
    metric_overrides: {}
    content_expectations:
      min_word_count: 50
      min_paragraph_count: 1
      min_heading_count: 1
      expected_heading_structure: []
      min_main_text_ratio: 0.5
      min_image_alt_coverage: 0.7
      required_meta_tags: []
      recommended_meta_tags: []
    quality_bands:
      excellent: 85.0
      good: 65.0
      fair: 45.0
      poor: 25.0
    penalties:
      severe_penalties: {}
      moderate_penalties: {}
      light_penalties: {}
    bonuses:
      excellence_bonuses: {}
      achievement_bonuses: {}
      synergy_bonuses: {}

output:
  include_debug: true
  include_raw_metrics: true
  timestamp_format: "ISO8601"
  float_precision: 3
"#;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("output_test.yaml");
    fs::write(&config_path, config).unwrap();

    let analyzer = from_config_file(&config_path).unwrap();
    let html = get_test_html();

    let report = analyzer
        .run("https://example.com", Some(html))
        .await
        .unwrap();

    // Verify report was generated successfully
    assert!(report.score >= 0.0);
    assert!(report.metrics.html_analysis.content.word_count > 0);
}

// ==================== Integration Tests ====================

#[tokio::test]
async fn test_full_workflow_with_custom_config() {
    // Create custom config
    let config = create_json_config_with_overrides();
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("workflow.json");
    fs::write(&config_path, config).unwrap();

    // Load via Level 3 API
    let analyzer = from_config_file(&config_path).unwrap();

    // Run analysis
    let html = get_test_html();
    let report = analyzer
        .run("https://example.com/article", Some(html))
        .await
        .unwrap();

    // Verify results
    assert!(report.score >= 0.0 && report.score <= 100.0);
    assert_eq!(report.url, "https://example.com/article");
    assert!(report.metrics.html_analysis.content.word_count > 0);

    // Verify metadata is present
    assert!(report.fetched_at.is_some());
}

#[tokio::test]
async fn test_compare_level1_and_level3_apis() {
    // Level 1: Simple API
    let html = get_test_html();
    let report_level1 = analyze("https://example.com", Some(html)).await.unwrap();

    // Level 3: Config file with default-like settings
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("compare.yaml");
    fs::write(&config_path, create_minimal_yaml_config()).unwrap();

    let analyzer = from_config_file(&config_path).unwrap();
    let report_level3 = analyzer
        .run("https://example.com", Some(html))
        .await
        .unwrap();

    // Both should produce valid results
    assert!(report_level1.score >= 0.0);
    assert!(report_level3.score >= 0.0);

    // Both should analyze the same content
    assert_eq!(
        report_level1.metrics.html_analysis.content.word_count,
        report_level3.metrics.html_analysis.content.word_count
    );
}

#[tokio::test]
async fn test_config_persistence_across_multiple_analyses() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("persist.yaml");
    fs::write(&config_path, create_minimal_yaml_config()).unwrap();

    let analyzer = from_config_file(&config_path).unwrap();

    // Run multiple analyses
    let html1 = get_test_html();
    let html2 = "<html><head><title>Different</title></head><body><p>Content</p></body></html>";

    let report1 = analyzer
        .run("https://example.com/page1", Some(html1))
        .await
        .unwrap();
    let report2 = analyzer
        .run("https://example.com/page2", Some(html2))
        .await
        .unwrap();

    // Both analyses should succeed
    assert!(report1.score >= 0.0);
    assert!(report2.score >= 0.0);

    // Different content should produce different scores
    assert_ne!(
        report1.metrics.html_analysis.content.word_count,
        report2.metrics.html_analysis.content.word_count
    );
}

#[test]
fn test_config_format_auto_detection() {
    let temp_dir = tempdir().unwrap();

    // Test YAML detection
    let yaml_path = temp_dir.path().join("test.yaml");
    fs::write(&yaml_path, create_minimal_yaml_config()).unwrap();
    assert!(ConfigManager::from_file(&yaml_path).is_ok());

    // Test YML detection
    let yml_path = temp_dir.path().join("test.yml");
    fs::write(&yml_path, create_minimal_yaml_config()).unwrap();
    assert!(ConfigManager::from_file(&yml_path).is_ok());

    // Test JSON detection
    let json_path = temp_dir.path().join("test.json");
    fs::write(&json_path, create_json_config_with_overrides()).unwrap();
    assert!(ConfigManager::from_file(&json_path).is_ok());

    // Test TOML detection
    let toml_path = temp_dir.path().join("test.toml");
    fs::write(&toml_path, create_toml_config()).unwrap();
    assert!(ConfigManager::from_file(&toml_path).is_ok());
}

// ==================== Performance Tests ====================

#[tokio::test]
async fn test_config_loading_performance() {
    use std::time::Instant;

    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("perf.yaml");
    fs::write(&config_path, create_minimal_yaml_config()).unwrap();

    let start = Instant::now();
    let _ = from_config_file(&config_path).unwrap();
    let duration = start.elapsed();

    // Config loading should be fast (< 100ms)
    assert!(
        duration.as_millis() < 100,
        "Config loading took {:?}",
        duration
    );
}

#[tokio::test]
async fn test_analysis_with_config_performance() {
    let temp_dir = tempdir().unwrap();
    let config_path = temp_dir.path().join("analysis_perf.yaml");
    fs::write(&config_path, create_minimal_yaml_config()).unwrap();

    let analyzer = from_config_file(&config_path).unwrap();
    let html = get_test_html();

    use std::time::Instant;
    let start = Instant::now();
    let _ = analyzer
        .run("https://example.com", Some(html))
        .await
        .unwrap();
    let duration = start.elapsed();

    // Analysis should complete in reasonable time (< 2 seconds for test HTML)
    assert!(duration.as_secs() < 2, "Analysis took {:?}", duration);
}