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
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
//! WASM bindings for webpage-quality-analyzer
//!
//! **Version**: 1.0.2
//!
//! This module provides WebAssembly bindings using wasm-bindgen to expose
//! the full analyzer functionality to JavaScript/TypeScript environments.
//!
//! **What's New in 1.0.2**:
//! - Product profile restored to e-commerce focus (breaking: use "general" for software)
//! - Login page validation stricter (Forms weight: 40%)
//! - Homepage/General profiles more balanced
//! - Fixed MetricEquals penalty trigger
//!
//! # Features
//! - Full async support via JavaScript Promises
//! - Profile-aware scoring with all Phase 3 features
//! - All 115 metrics calculated
//! - Batch processing support
//! - Custom profile configurations

use serde::{Deserialize, Serialize};
use wasm_bindgen::prelude::*;

#[cfg(target_arch = "wasm32")]
use crate::async_runtime::WasmRuntime;

#[cfg(not(target_arch = "wasm32"))]
type WasmRuntime = crate::async_runtime::DefaultRuntime;

use crate::{AnalyzeError, Analyzer, PageQualityReport};

/// WASM wrapper for the webpage quality analyzer
///
/// This provides a JavaScript-friendly interface to the full Rust analyzer,
/// bridging async Rust to JavaScript Promises via wasm-bindgen-futures.
#[wasm_bindgen]
pub struct WasmAnalyzer {
    analyzer: Analyzer<WasmRuntime>,
}

/// Configuration options for creating a WasmAnalyzer
///
/// This struct is not directly exposed to JavaScript. Use the methods
/// on WasmAnalyzer to configure instead.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct WasmAnalyzerConfig {
    /// Profile name to use (e.g., "default", "news", "blog", "ecommerce")
    profile: Option<String>,

    /// Enable NLP features (language detection, keyword extraction)
    enable_nlp: bool,

    /// Add detailed report sections
    add_report: bool,
}

impl WasmAnalyzerConfig {
    fn new() -> Self {
        WasmAnalyzerConfig {
            profile: None,
            enable_nlp: true,
            add_report: true,
        }
    }
}

impl Default for WasmAnalyzerConfig {
    fn default() -> Self {
        Self::new()
    }
}

#[wasm_bindgen]
impl WasmAnalyzer {
    /// Create a new analyzer with default configuration
    #[wasm_bindgen(constructor)]
    pub fn new() -> Result<WasmAnalyzer, JsValue> {
        // Set panic hook for better error messages in browser console
        #[cfg(feature = "console_error_panic_hook")]
        console_error_panic_hook::set_once();

        let analyzer = Analyzer::<WasmRuntime>::builder()
            .build()
            .map_err(|e| JsValue::from_str(&format!("Failed to create analyzer: {}", e)))?;

        Ok(WasmAnalyzer { analyzer })
    }

    /// Create analyzer with custom configuration
    ///
    /// # Arguments
    /// * `profile` - Optional profile name ("default", "news", "blog", etc.)
    /// * `enable_nlp` - Enable NLP features (default: true)
    /// * `add_report` - Include detailed report sections (default: true)
    #[wasm_bindgen(js_name = withConfig)]
    pub fn with_config(
        profile: Option<String>,
        enable_nlp: Option<bool>,
        add_report: Option<bool>,
    ) -> Result<WasmAnalyzer, JsValue> {
        #[cfg(feature = "console_error_panic_hook")]
        console_error_panic_hook::set_once();

        let mut builder = Analyzer::<WasmRuntime>::builder();

        if let Some(profile_name) = profile {
            builder = builder
                .with_profile_name(&profile_name)
                .map_err(|e| JsValue::from_str(&format!("Invalid profile: {}", e)))?;
        }

        #[cfg(feature = "nlp")]
        if let Some(nlp) = enable_nlp {
            builder = builder.enable_nlp(nlp);
        }

        if let Some(report) = add_report {
            builder = builder.add_report(report);
        }

        let analyzer = builder
            .build()
            .map_err(|e| JsValue::from_str(&format!("Failed to create analyzer: {}", e)))?;

        Ok(WasmAnalyzer { analyzer })
    }

    /// Analyze HTML content
    ///
    /// # Arguments
    /// * `html` - HTML content as string
    ///
    /// # Returns
    /// Promise that resolves to a PageQualityReport JSON object
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const analyzer = new WasmAnalyzer();
    /// const report = await analyzer.analyze('<html>...</html>');
    /// console.log(`Score: ${report.score}, Quality: ${report.verdict}`);
    /// ```
    #[wasm_bindgen]
    pub async fn analyze(&self, html: String) -> Result<JsValue, JsValue> {
        let report = self
            .analyzer
            .run("http://unknown.local", Some(&html))
            .await
            .map_err(|e| convert_error(e))?;

        serde_wasm_bindgen::to_value(&report)
            .map_err(|e| JsValue::from_str(&format!("Serialization failed: {}", e)))
    }

    /// Analyze HTML with a specific URL context
    ///
    /// # Arguments
    /// * `url` - URL of the page (used for context, not fetched)
    /// * `html` - HTML content as string
    ///
    /// # Returns
    /// Promise that resolves to a PageQualityReport JSON object
    #[wasm_bindgen(js_name = analyzeWithUrl)]
    pub async fn analyze_with_url(&self, url: String, html: String) -> Result<JsValue, JsValue> {
        let report = self
            .analyzer
            .run(&url, Some(&html))
            .await
            .map_err(|e| convert_error(e))?;

        serde_wasm_bindgen::to_value(&report)
            .map_err(|e| JsValue::from_str(&format!("Serialization failed: {}", e)))
    }

    /// Fetch and analyze a URL using browser's fetch API
    ///
    /// # Arguments
    /// * `url` - URL to fetch and analyze
    ///
    /// # Returns
    /// Promise that resolves to a PageQualityReport JSON object
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const analyzer = new WasmAnalyzer();
    /// const report = await analyzer.fetchAndAnalyze('https://example.com');
    /// ```
    #[wasm_bindgen(js_name = fetchAndAnalyze)]
    pub async fn fetch_and_analyze(&self, url: String) -> Result<JsValue, JsValue> {
        let report = self
            .analyzer
            .run(&url, None) // None triggers fetch via WasmRuntime
            .await
            .map_err(|e| convert_error(e))?;

        serde_wasm_bindgen::to_value(&report)
            .map_err(|e| JsValue::from_str(&format!("Serialization failed: {}", e)))
    }

    /// Get available profile names
    ///
    /// # Returns
    /// Array of profile names as strings (from enhanced_profiles.json)
    #[wasm_bindgen(js_name = getAvailableProfiles)]
    pub fn get_available_profiles() -> Vec<String> {
        vec![
            "general".to_string(),
            "news".to_string(),
            "content_article".to_string(),
            "blog".to_string(),
            "product".to_string(),
            "login_page".to_string(),
            "homepage".to_string(),
            "portfolio".to_string(),
        ]
    }

    /// Get version information
    #[wasm_bindgen(js_name = getVersion)]
    pub fn get_version() -> String {
        env!("CARGO_PKG_VERSION").to_string()
    }
}

/// Batch analysis result container
#[wasm_bindgen]
pub struct WasmBatchResult {
    results: Vec<Result<PageQualityReport, AnalyzeError>>,
}

#[wasm_bindgen]
impl WasmBatchResult {
    /// Get number of results
    #[wasm_bindgen(js_name = getCount)]
    pub fn get_count(&self) -> usize {
        self.results.len()
    }

    /// Get number of successful analyses
    #[wasm_bindgen(js_name = getSuccessCount)]
    pub fn get_success_count(&self) -> usize {
        self.results.iter().filter(|r| r.is_ok()).count()
    }

    /// Get number of failed analyses
    #[wasm_bindgen(js_name = getFailureCount)]
    pub fn get_failure_count(&self) -> usize {
        self.results.iter().filter(|r| r.is_err()).count()
    }

    /// Get all results as JSON array
    ///
    /// Each element is either:
    /// - `{ success: true, report: PageQualityReport }`
    /// - `{ success: false, error: string }`
    #[wasm_bindgen(js_name = getResults)]
    pub fn get_results(&self) -> Result<JsValue, JsValue> {
        #[derive(Serialize)]
        #[serde(tag = "success")]
        enum BatchItem {
            #[serde(rename = "true")]
            Success { report: PageQualityReport },
            #[serde(rename = "false")]
            Failure { error: String },
        }

        let items: Vec<BatchItem> = self
            .results
            .iter()
            .map(|result| match result {
                Ok(report) => BatchItem::Success {
                    report: report.clone(),
                },
                Err(e) => BatchItem::Failure {
                    error: e.to_string(),
                },
            })
            .collect();

        serde_wasm_bindgen::to_value(&items)
            .map_err(|e| JsValue::from_str(&format!("Serialization failed: {}", e)))
    }
}

/// Batch analyzer for processing multiple HTML documents
#[wasm_bindgen]
pub struct WasmBatchAnalyzer {
    analyzer: Analyzer<WasmRuntime>,
}

#[wasm_bindgen]
impl WasmBatchAnalyzer {
    /// Create new batch analyzer
    #[wasm_bindgen(constructor)]
    pub fn new() -> Result<WasmBatchAnalyzer, JsValue> {
        #[cfg(feature = "console_error_panic_hook")]
        console_error_panic_hook::set_once();

        let analyzer = Analyzer::<WasmRuntime>::builder()
            .build()
            .map_err(|e| JsValue::from_str(&format!("Failed to create analyzer: {}", e)))?;

        Ok(WasmBatchAnalyzer { analyzer })
    }

    /// Analyze multiple HTML documents in batch
    ///
    /// # Arguments
    /// * `html_documents` - Array of HTML strings
    ///
    /// # Returns
    /// Promise that resolves to WasmBatchResult
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const batch = new WasmBatchAnalyzer();
    /// const result = await batch.analyzeBatch([
    ///   '<html>page 1</html>',
    ///   '<html>page 2</html>',
    /// ]);
    /// console.log(`${result.getSuccessCount()} succeeded`);
    /// const reports = result.getResults();
    /// ```
    #[wasm_bindgen(js_name = analyzeBatch)]
    pub async fn analyze_batch(
        &self,
        html_documents: Vec<String>,
    ) -> Result<WasmBatchResult, JsValue> {
        let mut results = Vec::new();

        for html in html_documents {
            let result = self.analyzer.run("unknown", Some(&html)).await;
            results.push(result);
        }

        Ok(WasmBatchResult { results })
    }
}

// ============================================================================
// Phase 1: Custom Field Selection Support
// ============================================================================

/// WASM wrapper for FieldSelector - enables custom output field filtering
///
/// This allows JavaScript/TypeScript to select only specific fields from the
/// analysis report, reducing JSON payload size by 60-70% for production use.
///
/// # Example (JavaScript)
/// ```js
/// const analyzer = new WasmAnalyzer();
/// const report = await analyzer.analyzeWithFields(html, ['url', 'score', 'metadata']);
/// // Returns only the 3 requested fields
/// ```
#[wasm_bindgen]
pub struct WasmFieldSelector {
    include_fields: Vec<String>,
    exclude_fields: Vec<String>,
    include_sections: Vec<String>,
    exclude_sections: Vec<String>,
}

#[wasm_bindgen]
impl WasmFieldSelector {
    /// Create a new empty field selector
    #[wasm_bindgen(constructor)]
    pub fn new() -> WasmFieldSelector {
        WasmFieldSelector {
            include_fields: Vec::new(),
            exclude_fields: Vec::new(),
            include_sections: Vec::new(),
            exclude_sections: Vec::new(),
        }
    }

    /// Add fields to include (chainable)
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const selector = new WasmFieldSelector()
    ///   .includeFields(['url', 'score', 'metadata']);
    /// ```
    #[wasm_bindgen(js_name = includeFields)]
    pub fn include_fields(mut self, fields: Vec<String>) -> Self {
        self.include_fields.extend(fields);
        self
    }

    /// Add fields to exclude (chainable)
    #[wasm_bindgen(js_name = excludeFields)]
    pub fn exclude_fields(mut self, fields: Vec<String>) -> Self {
        self.exclude_fields.extend(fields);
        self
    }

    /// Add sections to include (chainable)
    #[wasm_bindgen(js_name = includeSections)]
    pub fn include_sections(mut self, sections: Vec<String>) -> Self {
        self.include_sections.extend(sections);
        self
    }

    /// Add sections to exclude (chainable)
    #[wasm_bindgen(js_name = excludeSections)]
    pub fn exclude_sections(mut self, sections: Vec<String>) -> Self {
        self.exclude_sections.extend(sections);
        self
    }

    /// Convert to internal FieldSelector
    fn to_field_selector(&self) -> crate::utils::json_optimizer::FieldSelector {
        use crate::utils::json_optimizer::FieldSelector;

        let mut builder = FieldSelector::builder();

        if !self.include_fields.is_empty() {
            builder = builder.include_fields(self.include_fields.clone());
        }

        if !self.exclude_fields.is_empty() {
            builder = builder.exclude_fields(self.exclude_fields.clone());
        }

        if !self.include_sections.is_empty() {
            builder = builder.include_sections(self.include_sections.clone());
        }

        if !self.exclude_sections.is_empty() {
            builder = builder.exclude_sections(self.exclude_sections.clone());
        }

        builder.build()
    }
}

#[wasm_bindgen]
impl WasmAnalyzer {
    /// Analyze HTML with custom field selection
    ///
    /// This method allows you to select only specific fields from the analysis
    /// report, reducing bandwidth usage by 60-70% for production deployments.
    ///
    /// # Arguments
    /// * `html` - HTML content to analyze
    /// * `fields` - Array of field names to include (e.g., ['url', 'score', 'metadata'])
    ///
    /// # Returns
    /// Promise that resolves to a filtered PageQualityReport with only requested fields
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const analyzer = new WasmAnalyzer();
    /// const report = await analyzer.analyzeWithFields(html, [
    ///   'url',
    ///   'score',
    ///   'metadata',
    ///   'processed_document'
    /// ]);
    /// // Returns only these 4 fields (60-70% smaller JSON)
    /// ```
    #[wasm_bindgen(js_name = analyzeWithFields)]
    pub async fn analyze_with_fields(
        &self,
        html: String,
        fields: Vec<String>,
    ) -> Result<JsValue, JsValue> {
        use crate::utils::json_optimizer::{
            FieldSelector, OptimizedSerializer, SerializationOptions,
        };

        // Run full analysis
        let report = self
            .analyzer
            .run("unknown", Some(&html))
            .await
            .map_err(|e| convert_error(e))?;

        // Build field selector from provided fields
        let selector = FieldSelector::builder().include_fields(fields).build();

        // Serialize with field selection (minimal format for bandwidth)
        let opts = SerializationOptions::minimal();
        let json = OptimizedSerializer::serialize_with_selector(&report, &selector, Some(&opts))
            .map_err(|e| JsValue::from_str(&format!("Serialization failed: {}", e)))?;

        // Parse JSON string back to JsValue for JavaScript consumption
        let json_value: serde_json::Value = serde_json::from_str(&json)
            .map_err(|e| JsValue::from_str(&format!("JSON parse failed: {}", e)))?;

        serde_wasm_bindgen::to_value(&json_value)
            .map_err(|e| JsValue::from_str(&format!("WASM serialization failed: {}", e)))
    }

    /// Analyze HTML with advanced field selector
    ///
    /// Provides full control over field selection including sections,
    /// include/exclude rules, and nested field access.
    ///
    /// # Arguments
    /// * `html` - HTML content to analyze
    /// * `selector` - WasmFieldSelector with custom rules
    ///
    /// # Returns
    /// Promise that resolves to a filtered PageQualityReport
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const selector = new WasmFieldSelector()
    ///   .includeFields(['url', 'score'])
    ///   .includeSections(['metadata'])
    ///   .excludeFields(['metadata.og_tags']);
    ///
    /// const report = await analyzer.analyzeWithSelector(html, selector);
    /// ```
    #[wasm_bindgen(js_name = analyzeWithSelector)]
    pub async fn analyze_with_selector(
        &self,
        html: String,
        selector: &WasmFieldSelector,
    ) -> Result<JsValue, JsValue> {
        use crate::utils::json_optimizer::{OptimizedSerializer, SerializationOptions};

        // Run full analysis
        let report = self
            .analyzer
            .run("unknown", Some(&html))
            .await
            .map_err(|e| convert_error(e))?;

        // Convert WASM selector to internal selector
        let field_selector = selector.to_field_selector();

        // Serialize with field selection
        let opts = SerializationOptions::minimal();
        let json =
            OptimizedSerializer::serialize_with_selector(&report, &field_selector, Some(&opts))
                .map_err(|e| JsValue::from_str(&format!("Serialization failed: {}", e)))?;

        // Parse JSON string back to JsValue
        let json_value: serde_json::Value = serde_json::from_str(&json)
            .map_err(|e| JsValue::from_str(&format!("JSON parse failed: {}", e)))?;

        serde_wasm_bindgen::to_value(&json_value)
            .map_err(|e| JsValue::from_str(&format!("WASM serialization failed: {}", e)))
    }
}

#[wasm_bindgen]
impl WasmBatchAnalyzer {
    /// Analyze batch with custom field selection
    ///
    /// Analyze multiple HTML documents and return only selected fields,
    /// optimizing bandwidth for production batch processing.
    ///
    /// # Arguments
    /// * `html_documents` - Array of HTML strings
    /// * `fields` - Array of field names to include
    ///
    /// # Returns
    /// Promise that resolves to array of filtered reports
    #[wasm_bindgen(js_name = analyzeBatchWithFields)]
    pub async fn analyze_batch_with_fields(
        &self,
        html_documents: Vec<String>,
        fields: Vec<String>,
    ) -> Result<JsValue, JsValue> {
        use crate::utils::json_optimizer::{
            FieldSelector, OptimizedSerializer, SerializationOptions,
        };

        let mut reports = Vec::new();

        // Analyze all documents
        for html in html_documents {
            match self.analyzer.run("unknown", Some(&html)).await {
                Ok(report) => reports.push(report),
                Err(_) => continue, // Skip failed analyses
            }
        }

        // Build field selector
        let selector = FieldSelector::builder().include_fields(fields).build();

        // Serialize batch with field selection
        let opts = SerializationOptions {
            compact: true,
            skip_empty_fields: true,
            minimal_output: false,
            streaming: true,
            buffer_size: 16384,
        };

        let json =
            OptimizedSerializer::serialize_batch_with_selector(&reports, &selector, Some(&opts))
                .map_err(|e| JsValue::from_str(&format!("Batch serialization failed: {}", e)))?;

        // Parse JSON string back to JsValue
        let json_value: serde_json::Value = serde_json::from_str(&json)
            .map_err(|e| JsValue::from_str(&format!("JSON parse failed: {}", e)))?;

        serde_wasm_bindgen::to_value(&json_value)
            .map_err(|e| JsValue::from_str(&format!("WASM serialization failed: {}", e)))
    }
}

// ============================================================================
// Phase 2: Config File Loading Support
// ============================================================================

#[wasm_bindgen]
impl WasmAnalyzer {
    /// Create analyzer from JSON configuration
    ///
    /// Since WASM cannot directly read files, pass the config as a JSON string.
    /// In browser environments, fetch the config file and pass its content.
    ///
    /// # Arguments
    /// * `config_json` - JSON string containing profile configuration
    ///
    /// # Returns
    /// New WasmAnalyzer configured with the provided settings
    ///
    /// # Example (JavaScript - Browser)
    /// ```js
    /// const configJson = await fetch('/configs/my-config.json').then(r => r.text());
    /// const analyzer = WasmAnalyzer.fromConfig(configJson);
    /// ```
    ///
    /// # Example (JavaScript - Node.js)
    /// ```js
    /// const fs = require('fs');
    /// const configJson = fs.readFileSync('config.json', 'utf-8');
    /// const analyzer = WasmAnalyzer.fromConfig(configJson);
    /// ```
    #[wasm_bindgen(js_name = fromConfig)]
    pub fn from_config(config_json: String) -> Result<WasmAnalyzer, JsValue> {
        #[cfg(feature = "console_error_panic_hook")]
        console_error_panic_hook::set_once();

        // Parse JSON to extract profile name
        // Expected format: { "profile": "news", "enable_nlp": true, ... }
        let config_value: serde_json::Value = serde_json::from_str(&config_json)
            .map_err(|e| JsValue::from_str(&format!("Invalid JSON: {}", e)))?;

        // Extract profile name (default to 'general' if not specified)
        let profile_name = config_value["profile"].as_str().unwrap_or("general");

        // Build analyzer with profile name
        let analyzer = Analyzer::<WasmRuntime>::builder()
            .with_profile_name(profile_name)
            .map_err(|e| JsValue::from_str(&format!("Failed to set profile: {}", e)))?
            .build()
            .map_err(|e| JsValue::from_str(&format!("Failed to create analyzer: {}", e)))?;

        Ok(WasmAnalyzer { analyzer })
    }

    /// Get the current profile configuration as JSON string
    ///
    /// Returns the active profile configuration, which can be:
    /// - Saved to a file
    /// - Modified and reloaded
    /// - Shared across team members
    ///
    /// # Returns
    /// JSON string of the current ProfileConfig
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const analyzer = new WasmAnalyzer();
    /// const configJson = analyzer.getConfig();
    /// console.log('Current config:', JSON.parse(configJson));
    ///
    /// // Save to file or modify
    /// localStorage.setItem('analyzer-config', configJson);
    /// ```
    #[wasm_bindgen(js_name = getConfig)]
    pub fn get_config(&self) -> Result<String, JsValue> {
        // Get the profile config from analyzer (requires exposing it in Analyzer struct)
        // For now, return a placeholder - need to add config getter to Analyzer
        Err(JsValue::from_str(
            "getConfig not yet implemented - requires Analyzer to expose config",
        ))
    }
}

// ============================================================================
// Phase 3: Per-Metric Configuration & Builder Pattern
// ============================================================================

/// WASM Analyzer Builder for advanced configuration
///
/// Provides a fluent API for customizing analyzer behavior including:
/// - Profile selection
/// - Metric toggling (enable/disable specific metrics)
/// - Custom thresholds per metric
/// - NLP and grammar features
///
/// # Example (JavaScript)
/// ```js
/// const analyzer = WasmAnalyzer.builder()
///   .withProfile('news')
///   .disableMetric('grammar_score')  // Skip expensive grammar checking
///   .setThreshold('word_count', 500, 2000, 5000)
///   .enableNlp(true)
///   .build();
/// ```
#[wasm_bindgen]
pub struct WasmAnalyzerBuilder {
    profile: Option<String>,
    enabled_metrics: Vec<String>,
    disabled_metrics: Vec<String>,
    custom_thresholds: Vec<(String, f32, f32, f32, f32)>, // (metric, min, optimal_min, optimal_max, max)
    metric_weights: Vec<(String, f32)>,                   // (metric, weight) - Phase 4
    custom_penalties: Vec<crate::config::enhanced_models::GlobalPenalty>, // Phase 5
    custom_bonuses: Vec<crate::config::enhanced_models::GlobalBonus>, // Phase 5
    enable_nlp: bool,
    enable_link_check: bool, // Phase 6
    add_report: bool,
}

#[wasm_bindgen]
impl WasmAnalyzerBuilder {
    /// Create a new builder with default settings
    #[wasm_bindgen(constructor)]
    pub fn new() -> WasmAnalyzerBuilder {
        WasmAnalyzerBuilder {
            profile: None,
            enabled_metrics: Vec::new(),
            disabled_metrics: Vec::new(),
            custom_thresholds: Vec::new(),
            metric_weights: Vec::new(),   // Phase 4
            custom_penalties: Vec::new(), // Phase 5
            custom_bonuses: Vec::new(),   // Phase 5
            enable_nlp: true,
            enable_link_check: false, // Phase 6 - disabled by default (CORS issues in browser)
            add_report: true,
        }
    }

    /// Set the profile to use (chainable)
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const builder = new WasmAnalyzerBuilder()
    ///   .withProfile('news');
    /// ```
    #[wasm_bindgen(js_name = withProfile)]
    pub fn with_profile(mut self, profile: String) -> Self {
        self.profile = Some(profile);
        self
    }

    /// Enable a specific metric (chainable)
    ///
    /// By default, all metrics in the profile are enabled. Use this to
    /// explicitly enable a metric that might be disabled in the profile.
    ///
    /// # Arguments
    /// * `metric_name` - Name of metric (e.g., "word_count", "image_count")
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const builder = new WasmAnalyzerBuilder()
    ///   .enableMetric('word_count')
    ///   .enableMetric('readability_score');
    /// ```
    #[wasm_bindgen(js_name = enableMetric)]
    pub fn enable_metric(mut self, metric_name: String) -> Self {
        self.enabled_metrics.push(metric_name);
        self
    }

    /// Disable a specific metric (chainable)
    ///
    /// Disabling metrics can improve performance by skipping expensive
    /// calculations you don't need.
    ///
    /// # Arguments
    /// * `metric_name` - Name of metric to disable
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const builder = new WasmAnalyzerBuilder()
    ///   .disableMetric('grammar_score')  // Skip grammar checking
    ///   .disableMetric('link_check');     // Skip external link validation
    /// ```
    #[wasm_bindgen(js_name = disableMetric)]
    pub fn disable_metric(mut self, metric_name: String) -> Self {
        self.disabled_metrics.push(metric_name);
        self
    }

    /// Set custom threshold for a metric (chainable)
    ///
    /// Customize the thresholds used for scoring a metric with full control
    /// over the scoring curve.
    ///
    /// Thresholds define the scoring curve:
    /// - `min`: Below this value, score is 0
    /// - `optimal_min`: Start of optimal range (100% score)
    /// - `optimal_max`: End of optimal range (100% score)
    /// - `max`: Above this value, score doesn't improve
    ///
    /// # Arguments
    /// * `metric_name` - Name of the metric
    /// * `min` - Minimum acceptable value
    /// * `optimal_min` - Start of optimal range
    /// * `optimal_max` - End of optimal range
    /// * `max` - Maximum useful value
    ///
    /// # Validation
    /// Thresholds must satisfy: min < optimal_min <= optimal_max < max
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const builder = new WasmAnalyzerBuilder()
    ///   .setThreshold(
    ///     'word_count',
    ///     100,    // min - articles < 100 words score poorly
    ///     500,    // optimal_min - ideal range starts
    ///     2000,   // optimal_max - ideal range ends
    ///     5000    // max - diminishing returns after this
    ///   );
    /// ```
    #[wasm_bindgen(js_name = setThreshold)]
    pub fn set_threshold(
        mut self,
        metric_name: String,
        min: f32,
        optimal_min: f32,
        optimal_max: f32,
        max: f32,
    ) -> Self {
        self.custom_thresholds
            .push((metric_name, min, optimal_min, optimal_max, max));
        self
    }

    /// Set simple threshold for a metric (chainable)
    ///
    /// Convenience method for metrics with a single optimal value rather than a range.
    /// This creates optimal_min == optimal_max.
    ///
    /// # Arguments
    /// * `metric_name` - Name of the metric
    /// * `min` - Minimum acceptable value
    /// * `optimal` - Single optimal value (100% score)
    /// * `max` - Maximum useful value
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const builder = new WasmAnalyzerBuilder()
    ///   .setSimpleThreshold(
    ///     'title_len',
    ///     30,   // min - titles < 30 chars are poor
    ///     60,   // optimal - 60 chars is perfect
    ///     120   // max - longer titles don't help
    ///   );
    /// ```
    #[wasm_bindgen(js_name = setSimpleThreshold)]
    pub fn set_simple_threshold(
        mut self,
        metric_name: String,
        min: f32,
        optimal: f32,
        max: f32,
    ) -> Self {
        self.custom_thresholds
            .push((metric_name, min, optimal, optimal, max));
        self
    }

    /// Set custom weight for a metric (chainable)
    ///
    /// Weights control the relative importance of metrics in scoring.
    /// Default weight is 1.0. Use >1.0 to increase importance, <1.0 to decrease.
    ///
    /// # Arguments
    /// * `metric_name` - Name of the metric to adjust
    /// * `weight` - Multiplier for metric's contribution (0.0-10.0, typically 0.1-3.0)
    ///
    /// # Weight Guidelines
    /// * 0.0 - Disables the metric
    /// * 0.1-0.5 - Significantly reduce importance
    /// * 0.5-0.9 - Moderately reduce importance
    /// * 1.0 - Default (unchanged)
    /// * 1.1-2.0 - Moderately increase importance
    /// * 2.0-3.0 - Significantly increase importance
    /// * >3.0 - Extreme emphasis (use sparingly)
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const builder = new WasmAnalyzerBuilder()
    ///   .setMetricWeight('seo_title_quality', 2.0)  // Double SEO importance
    ///   .setMetricWeight('grammar_score', 0.5);     // Reduce grammar weight
    /// ```
    #[wasm_bindgen(js_name = setMetricWeight)]
    pub fn set_metric_weight(mut self, metric_name: String, weight: f32) -> Self {
        self.metric_weights.push((metric_name, weight));
        self
    }

    // ============================================================================
    // Phase 5: Custom Penalties & Bonuses APIs (WASM)
    // ============================================================================

    /// Add a penalty that reduces score when metric falls below threshold
    ///
    /// Penalties help enforce content quality standards by automatically reducing
    /// scores when important metrics don't meet expectations.
    ///
    /// # Parameters
    /// - `penalty_id`: Unique identifier for this penalty
    /// - `metric`: Metric name to monitor (e.g., "word_count", "heading_depth")
    /// - `threshold`: Trigger penalty when metric value is below this
    /// - `penalty_points`: Number of points to subtract (0-100)
    /// - `description`: Human-readable explanation
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const builder = new WasmAnalyzerBuilder()
    ///   .withProfile('content_article')
    ///   .addPenaltyBelow('short_content', 'word_count', 300, 10, 'Content too short')
    ///   .addPenaltyBelow('shallow_structure', 'heading_depth', 2, 5, 'Insufficient headings');
    /// ```
    #[wasm_bindgen(js_name = addPenaltyBelow)]
    pub fn add_penalty_below(
        mut self,
        penalty_id: String,
        metric: String,
        threshold: f32,
        penalty_points: f32,
        description: String,
    ) -> Self {
        use crate::config::enhanced_models::{GlobalPenalty, PenaltyTrigger, PenaltyType};

        let penalty = GlobalPenalty {
            trigger_condition: PenaltyTrigger::MetricBelow { metric, threshold },
            penalty_type: PenaltyType::FixedPoints {
                points: penalty_points,
            },
            description: format!("{} (ID: {})", description, penalty_id),
            enabled: true,
        };

        self.custom_penalties.push(penalty);
        self
    }

    /// Add a penalty that reduces score when metric exceeds threshold
    ///
    /// Useful for penalizing excessive values (e.g., too many links, overly long titles).
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const builder = new WasmAnalyzerBuilder()
    ///   .addPenaltyAbove('title_too_long', 'title_len', 70, 5, 'Title too long for SEO');
    /// ```
    #[wasm_bindgen(js_name = addPenaltyAbove)]
    pub fn add_penalty_above(
        mut self,
        penalty_id: String,
        metric: String,
        threshold: f32,
        penalty_points: f32,
        description: String,
    ) -> Self {
        use crate::config::enhanced_models::{GlobalPenalty, PenaltyTrigger, PenaltyType};

        let penalty = GlobalPenalty {
            trigger_condition: PenaltyTrigger::MetricAbove { metric, threshold },
            penalty_type: PenaltyType::FixedPoints {
                points: penalty_points,
            },
            description: format!("{} (ID: {})", description, penalty_id),
            enabled: true,
        };

        self.custom_penalties.push(penalty);
        self
    }

    /// Add a bonus that increases score when metric exceeds excellence threshold
    ///
    /// Bonuses reward exceptional quality, comprehensiveness, or excellence.
    ///
    /// # Parameters
    /// - `bonus_id`: Unique identifier for this bonus
    /// - `metric`: Metric name to monitor
    /// - `threshold`: Grant bonus when metric value exceeds this
    /// - `bonus_points`: Number of points to add (0-50 recommended)
    /// - `description`: Human-readable explanation
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const builder = new WasmAnalyzerBuilder()
    ///   .withProfile('content_article')
    ///   .addBonusAbove('comprehensive', 'word_count', 2000, 5, 'Comprehensive content')
    ///   .addBonusAbove('deep_structure', 'heading_depth', 4, 3, 'Excellent organization');
    /// ```
    #[wasm_bindgen(js_name = addBonusAbove)]
    pub fn add_bonus_above(
        mut self,
        bonus_id: String,
        metric: String,
        threshold: f32,
        bonus_points: f32,
        description: String,
    ) -> Self {
        use crate::config::enhanced_models::{BonusTrigger, GlobalBonus};

        let bonus = GlobalBonus {
            trigger_condition: BonusTrigger::MetricExcellence { metric, threshold },
            bonus_points,
            description: format!("{} (ID: {})", description, bonus_id),
            enabled: true,
        };

        self.custom_bonuses.push(bonus);
        self
    }

    /// Add a bonus when multiple metrics are all above thresholds
    ///
    /// Creates a synergy bonus that rewards consistent quality across metrics.
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const builder = new WasmAnalyzerBuilder()
    ///   .addBonusMultiple(
    ///     'seo_excellence',
    ///     ['title_len', 'meta_desc_len', 'heading_depth'],
    ///     50,
    ///     5,
    ///     'Excellent SEO across the board'
    ///   );
    /// ```
    #[wasm_bindgen(js_name = addBonusMultiple)]
    pub fn add_bonus_multiple(
        mut self,
        bonus_id: String,
        metrics: Vec<String>,
        threshold: f32,
        bonus_points: f32,
        description: String,
    ) -> Self {
        use crate::config::enhanced_models::{BonusTrigger, GlobalBonus};

        let bonus = GlobalBonus {
            trigger_condition: BonusTrigger::MultipleMetricsGood { metrics, threshold },
            bonus_points,
            description: format!("{} (ID: {})", description, bonus_id),
            enabled: true,
        };

        self.custom_bonuses.push(bonus);
        self
    }

    // End Phase 5 APIs

    /// Enable or disable NLP features (chainable)
    ///
    /// NLP features include language detection and keyword extraction.
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const builder = new WasmAnalyzerBuilder()
    ///   .enableNlp(false);  // Disable for faster processing
    /// ```
    #[wasm_bindgen(js_name = enableNlp)]
    pub fn enable_nlp(mut self, enable: bool) -> Self {
        self.enable_nlp = enable;
        self
    }

    /// Enable or disable link checking (chainable)
    ///
    /// Note: Link checking in WASM uses browser fetch API and may be subject
    /// to CORS restrictions. Only works when 'linkcheck' feature is enabled.
    ///
    /// # Example
    /// ```js
    /// const builder = new WasmAnalyzerBuilder()
    ///   .enableLinkCheck(true);  // Enable link validation
    /// ```
    #[wasm_bindgen(js_name = enableLinkCheck)]
    pub fn enable_link_check(mut self, enable: bool) -> Self {
        self.enable_link_check = enable;
        self
    }

    /// Enable or disable detailed report sections (chainable)
    #[wasm_bindgen(js_name = addReport)]
    pub fn add_report(mut self, add: bool) -> Self {
        self.add_report = add;
        self
    }

    // ============================================================================
    // Configuration Loading Methods (WASM Alternative to from_config_file)
    // ============================================================================

    /// Load configuration from JSON string (WASM alternative to from_config_file)
    ///
    /// Since WASM doesn't have file system access, use this method to load
    /// configuration from a JSON string instead. You can fetch the config via
    /// HTTP or embed it in your JavaScript code.
    ///
    /// # Parameters
    /// - `config_json`: JSON string containing the configuration
    ///
    /// # Returns
    /// New WasmAnalyzer instance configured from the JSON
    ///
    /// # Example (JavaScript)
    /// ```js
    /// // Fetch config from server
    /// const configResponse = await fetch('/config/analyzer-config.json');
    /// const configJson = await configResponse.text();
    /// const analyzer = WasmAnalyzerBuilder.fromConfigJson(configJson);
    ///
    /// // Or use embedded config
    /// const config = JSON.stringify({
    ///   active_profile: "news",
    ///   presets: {
    ///     news: {
    ///       category_weights: { content: 2.0, seo: 1.5 }
    ///     }
    ///   }
    /// });
    /// const analyzer = WasmAnalyzerBuilder.fromConfigJson(config);
    /// ```
    #[wasm_bindgen(js_name = fromConfigJson)]
    pub fn from_config_json(config_json: &str) -> Result<WasmAnalyzer, JsValue> {
        use crate::config::config_manager::{ConfigFormat, ConfigManager};

        #[cfg(feature = "console_error_panic_hook")]
        console_error_panic_hook::set_once();

        // Parse JSON config
        let config_manager = ConfigManager::from_str(config_json, ConfigFormat::Json)
            .map_err(|e| JsValue::from_str(&format!("Failed to parse JSON config: {}", e)))?;

        // Build analyzer with config
        let analyzer = Analyzer::<WasmRuntime>::builder()
            .with_config_manager(config_manager)
            .build()
            .map_err(|e| {
                JsValue::from_str(&format!("Failed to build analyzer from config: {}", e))
            })?;

        Ok(WasmAnalyzer { analyzer })
    }

    /// Load configuration from YAML string (WASM alternative to from_config_file)
    ///
    /// Since WASM doesn't have file system access, use this method to load
    /// configuration from a YAML string instead.
    ///
    /// # Parameters
    /// - `config_yaml`: YAML string containing the configuration
    ///
    /// # Returns
    /// New WasmAnalyzer instance configured from the YAML
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const configYaml = `
    /// active_profile: content_article
    /// presets:
    ///   content_article:
    ///     category_weights:
    ///       content: 2.0
    ///       seo: 1.5
    /// `;
    /// const analyzer = WasmAnalyzerBuilder.fromConfigYaml(configYaml);
    /// ```
    #[wasm_bindgen(js_name = fromConfigYaml)]
    pub fn from_config_yaml(config_yaml: &str) -> Result<WasmAnalyzer, JsValue> {
        use crate::config::config_manager::{ConfigFormat, ConfigManager};

        #[cfg(feature = "console_error_panic_hook")]
        console_error_panic_hook::set_once();

        // Parse YAML config
        let config_manager = ConfigManager::from_str(config_yaml, ConfigFormat::Yaml)
            .map_err(|e| JsValue::from_str(&format!("Failed to parse YAML config: {}", e)))?;

        // Build analyzer with config
        let analyzer = Analyzer::<WasmRuntime>::builder()
            .with_config_manager(config_manager)
            .build()
            .map_err(|e| {
                JsValue::from_str(&format!("Failed to build analyzer from config: {}", e))
            })?;

        Ok(WasmAnalyzer { analyzer })
    }

    /// Load configuration from TOML string (WASM alternative to from_config_file)
    ///
    /// Since WASM doesn't have file system access, use this method to load
    /// configuration from a TOML string instead.
    ///
    /// # Parameters
    /// - `config_toml`: TOML string containing the configuration
    ///
    /// # Returns
    /// New WasmAnalyzer instance configured from the TOML
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const configToml = `
    /// active_profile = "blog"
    ///
    /// [presets.blog]
    /// [presets.blog.category_weights]
    /// content = 2.0
    /// seo = 1.5
    /// `;
    /// const analyzer = WasmAnalyzerBuilder.fromConfigToml(configToml);
    /// ```
    #[wasm_bindgen(js_name = fromConfigToml)]
    pub fn from_config_toml(config_toml: &str) -> Result<WasmAnalyzer, JsValue> {
        use crate::config::config_manager::{ConfigFormat, ConfigManager};

        #[cfg(feature = "console_error_panic_hook")]
        console_error_panic_hook::set_once();

        // Parse TOML config
        let config_manager = ConfigManager::from_str(config_toml, ConfigFormat::Toml)
            .map_err(|e| JsValue::from_str(&format!("Failed to parse TOML config: {}", e)))?;

        // Build analyzer with config
        let analyzer = Analyzer::<WasmRuntime>::builder()
            .with_config_manager(config_manager)
            .build()
            .map_err(|e| {
                JsValue::from_str(&format!("Failed to build analyzer from config: {}", e))
            })?;

        Ok(WasmAnalyzer { analyzer })
    }

    // End Configuration Loading Methods

    /// Build the analyzer with configured settings
    ///
    /// # Returns
    /// WasmAnalyzer instance with custom configuration
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const analyzer = new WasmAnalyzerBuilder()
    ///   .withProfile('news')
    ///   .disableMetric('grammar_score')
    ///   .setThreshold('word_count', 500, 2000, 5000)
    ///   .build();
    ///
    /// const report = await analyzer.analyze(html);
    /// ```
    #[wasm_bindgen]
    pub fn build(self) -> Result<WasmAnalyzer, JsValue> {
        #[cfg(feature = "console_error_panic_hook")]
        console_error_panic_hook::set_once();

        let mut builder = Analyzer::<WasmRuntime>::builder();

        // Set profile if specified
        if let Some(profile_name) = self.profile {
            builder = builder.with_profile_name(&profile_name).map_err(|e| {
                JsValue::from_str(&format!("Invalid profile '{}': {}", profile_name, e))
            })?;
        }

        // Phase 2: Apply enabled/disabled metrics
        for metric_name in &self.enabled_metrics {
            builder = builder.enable_metric(metric_name).map_err(|e| {
                JsValue::from_str(&format!("Failed to enable metric '{}': {}", metric_name, e))
            })?;
        }

        for metric_name in &self.disabled_metrics {
            builder = builder.disable_metric(metric_name).map_err(|e| {
                JsValue::from_str(&format!(
                    "Failed to disable metric '{}': {}",
                    metric_name, e
                ))
            })?;
        }

        // Phase 3: Apply custom thresholds
        for (metric_name, min, optimal_min, optimal_max, max) in self.custom_thresholds {
            builder = builder
                .set_metric_threshold(&metric_name, min, optimal_min, optimal_max, max)
                .map_err(|e| {
                    JsValue::from_str(&format!(
                        "Failed to set threshold for '{}': {}",
                        metric_name, e
                    ))
                })?;
        }

        // Phase 4: Apply custom metric weights
        for (metric_name, weight) in self.metric_weights {
            builder = builder
                .set_metric_weight(&metric_name, weight)
                .map_err(|e| {
                    JsValue::from_str(&format!(
                        "Failed to set weight for '{}': {}",
                        metric_name, e
                    ))
                })?;
        }

        // Phase 5: Apply custom penalties and bonuses
        for penalty in self.custom_penalties {
            builder = builder
                .add_penalty(penalty)
                .map_err(|e| JsValue::from_str(&format!("Failed to add penalty: {}", e)))?;
        }

        for bonus in self.custom_bonuses {
            builder = builder
                .add_bonus(bonus)
                .map_err(|e| JsValue::from_str(&format!("Failed to add bonus: {}", e)))?;
        }

        #[cfg(feature = "nlp")]
        {
            builder = builder.enable_nlp(self.enable_nlp);
        }

        // Phase 6: Apply link check setting (if feature enabled)
        #[cfg(feature = "linkcheck")]
        {
            builder = builder.enable_linkcheck(self.enable_link_check);
        }

        builder = builder.add_report(self.add_report);

        let analyzer = builder
            .build()
            .map_err(|e| JsValue::from_str(&format!("Failed to build analyzer: {}", e)))?;

        Ok(WasmAnalyzer { analyzer })
    }
}

#[wasm_bindgen]
impl WasmAnalyzer {
    /// Create a builder for advanced analyzer configuration
    ///
    /// # Returns
    /// WasmAnalyzerBuilder for fluent configuration
    ///
    /// # Example (JavaScript)
    /// ```js
    /// const analyzer = WasmAnalyzer.builder()
    ///   .withProfile('news')
    ///   .disableMetric('grammar_score')
    ///   .build();
    /// ```
    #[wasm_bindgen]
    pub fn builder() -> WasmAnalyzerBuilder {
        WasmAnalyzerBuilder::new()
    }
}

/// Helper function to convert AnalyzeError to JsValue with better error messages
fn convert_error(error: AnalyzeError) -> JsValue {
    let error_msg = match error {
        AnalyzeError::InvalidUrl(msg) => format!("Invalid URL: {}", msg),
        AnalyzeError::NetworkError(msg) => format!("Network error: {}", msg),
        AnalyzeError::ParseError(msg) => format!("Parse error: {}", msg),
        AnalyzeError::ConfigError(msg) => format!("Configuration error: {}", msg),
        AnalyzeError::AnalysisError(msg) => format!("Analysis error: {}", msg),
        _ => format!("Error: {}", error),
    };

    JsValue::from_str(&error_msg)
}

/// Initialize the WASM module (call this once when loading)
///
/// Sets up panic hooks and other initialization
#[wasm_bindgen(start)]
pub fn init() {
    #[cfg(feature = "console_error_panic_hook")]
    console_error_panic_hook::set_once();

    // Optional: Set up custom logger for web console
    #[cfg(feature = "wasm-logger")]
    wasm_logger::init(wasm_logger::Config::default());
}

/// Get the library version
#[wasm_bindgen(js_name = getVersion)]
pub fn get_version() -> String {
    env!("CARGO_PKG_VERSION").to_string()
}

/// Get version changelog for current version
#[wasm_bindgen(js_name = getVersionChangelog)]
pub fn get_version_changelog() -> String {
    format!(
        "v{} - Profile scoring improvements:\n\
         - Product profile: Reverted to e-commerce focus (breaking change)\n\
         - Login page: Stricter validation (Forms: 40% weight)\n\
         - Homepage/General: More balanced scoring with new bonuses\n\
         - Fixed: MetricEquals penalty trigger implementation\n\
         See CHANGELOG.md for full details.",
        env!("CARGO_PKG_VERSION")
    )
}

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

    #[test]
    fn test_config_creation() {
        let config = WasmAnalyzerConfig::new();
        assert_eq!(config.profile, None);
        assert!(config.enable_nlp);
        assert!(config.add_report);
    }

    #[test]
    fn test_version() {
        let version = get_version();
        assert!(version.starts_with("1.0"));
    }

    #[test]
    fn test_profile_list() {
        let profiles = WasmAnalyzer::get_available_profiles();
        assert!(profiles.contains(&"default".to_string()));
        assert!(profiles.contains(&"news".to_string()));
        assert!(profiles.len() >= 6);
    }
}