webshot 0.3.0

A command-line tool for automated website screenshots and web scraping
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
use assert_cmd::Command;
use predicates::prelude::*;
use std::{fs, path::Path};
use tempfile::TempDir;

const TEST_URL: &str = "https://httpbin.org/html";

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_basic_screenshot() {
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("test.png");

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg(TEST_URL)
        .arg("-o")
        .arg(&output_path)
        .arg("-w")
        .arg("800")
        .arg("-H")
        .arg("600");

    cmd.assert().success();
    assert!(output_path.exists());

    // Check that the file is not empty
    let metadata = fs::metadata(&output_path).unwrap();
    assert!(metadata.len() > 0);
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_pdf_generation() {
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("test.pdf");

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("pdf").arg(TEST_URL).arg("-o").arg(&output_path);

    cmd.assert().success();
    assert!(output_path.exists());

    // Check that the file is not empty and starts with PDF header
    let content = fs::read(&output_path).unwrap();
    assert!(!content.is_empty());
    assert!(content.starts_with(b"%PDF"));
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_element_screenshot() {
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("element.png");

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg(TEST_URL)
        .arg("-o")
        .arg(&output_path)
        .arg("-s")
        .arg("h1");

    cmd.assert().success();
    assert!(output_path.exists());
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_javascript_execution() {
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("js-test.png");

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg(TEST_URL)
        .arg("-o")
        .arg(&output_path)
        .arg("-j")
        .arg("document.body.style.backgroundColor = 'red'");

    cmd.assert().success();
    assert!(output_path.exists());
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_text_extraction() {
    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("text").arg(TEST_URL).arg("-s").arg("h1");

    cmd.assert()
        .success()
        .stdout(predicate::str::contains("Herman Melville"));
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_config_processing() {
    let temp_dir = TempDir::new().unwrap();

    // Create a simple config file
    let config_content = format!(
        r#"
screenshots:
  - url: "{}"
    output: "test1.png"
    width: 800
    height: 600
  - url: "{}"
    output: "test2.png"
    width: 1200
    height: 800
"#,
        TEST_URL, TEST_URL
    );

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

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("multi")
        .arg(&config_path)
        .arg("-o")
        .arg(temp_dir.path())
        .arg("-p")
        .arg("2");

    cmd.assert().success();

    assert!(temp_dir.path().join("test1.png").exists());
    assert!(temp_dir.path().join("test2.png").exists());
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_multi_output_dir_prepends_defaults_output_dir_and_overwrites() {
    let temp_dir = TempDir::new().unwrap();
    let config_content = format!(
        r#"
defaults:
  output_dir: "defaults/nested"
screenshots:
  - url: "{}"
    output: "page.png"
    width: 800
    height: 600
"#,
        TEST_URL
    );

    let config_path = temp_dir.path().join("config.yaml");
    let artifacts_dir = temp_dir.path().join("artifacts");
    let expected_output = artifacts_dir
        .join("defaults")
        .join("nested")
        .join("page.png");
    fs::write(&config_path, config_content).unwrap();

    run_multi_output_dir_command(&config_path, &artifacts_dir);

    assert_png_file(&expected_output);
    assert_no_alternate_outputs(temp_dir.path(), &artifacts_dir);

    fs::write(&expected_output, b"stale output").unwrap();

    run_multi_output_dir_command(&config_path, &artifacts_dir);

    let second_output = assert_png_file(&expected_output);
    assert_ne!(second_output, b"stale output");
    assert_no_alternate_outputs(temp_dir.path(), &artifacts_dir);
}

fn run_multi_output_dir_command(config_path: &Path, artifacts_dir: &Path) {
    let mut cmd = Command::cargo_bin("webshot").unwrap();
    // Keep relative paths in the YAML rooted in the test temp directory.
    cmd.current_dir(config_path.parent().unwrap())
        .arg("multi")
        .arg(config_path)
        .arg("-o")
        .arg(artifacts_dir)
        .arg("-p")
        .arg("1");

    cmd.assert().success();
}

fn assert_no_alternate_outputs(temp_dir: &Path, artifacts_dir: &Path) {
    assert!(!temp_dir
        .join("defaults")
        .join("nested")
        .join("page.png")
        .exists());
    assert!(!artifacts_dir.join("page.png").exists());
}

fn assert_png_file(path: &Path) -> Vec<u8> {
    let content = fs::read(path).unwrap();
    assert!(content.starts_with(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]));
    assert!(content.len() > 8);
    content
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_jpeg_quality() {
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("quality.jpg");

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg(TEST_URL)
        .arg("-o")
        .arg(&output_path)
        .arg("-q")
        .arg("50");

    cmd.assert().success();
    assert!(output_path.exists());

    // Check that it's a JPEG file
    let content = fs::read(&output_path).unwrap();
    assert!(content.starts_with(&[0xFF, 0xD8, 0xFF])); // JPEG header
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_retina_mode() {
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("retina.png");

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg(TEST_URL)
        .arg("-o")
        .arg(&output_path)
        .arg("--retina");

    cmd.assert().success();
    assert!(output_path.exists());
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_wait_for_element() {
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("wait.png");

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg(TEST_URL)
        .arg("-o")
        .arg(&output_path)
        .arg("--wait-for")
        .arg("h1");

    cmd.assert().success();
    assert!(output_path.exists());
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_custom_user_agent() {
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("user-agent.png");

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("https://httpbin.org/user-agent")
        .arg("-o")
        .arg(&output_path)
        .arg("--user-agent")
        .arg("WebshotBot/1.0");

    cmd.assert().success();
    assert!(output_path.exists());
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium startup before validation completes"]
async fn test_error_handling_invalid_url() {
    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("not-a-valid-url");

    cmd.assert().failure();
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_error_handling_invalid_selector() {
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("invalid.png");

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg(TEST_URL)
        .arg("-o")
        .arg(&output_path)
        .arg("-s")
        .arg("invalid-selector-that-does-not-exist");

    cmd.assert().failure();
}

#[tokio::test]
async fn test_help_output() {
    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("--help");

    cmd.assert()
        .success()
        .stdout(predicate::str::contains("webshot"))
        .stdout(predicate::str::contains("screenshot"))
        .stdout(predicate::str::contains("-H, --height"))
        .stdout(predicate::str::contains("-h, --help"));
}

#[tokio::test]
async fn test_screenshot_help_height_short_flag() {
    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.args(["screenshot", "--help"]);

    cmd.assert()
        .success()
        .stdout(predicate::str::contains("-H, --height"))
        .stdout(predicate::str::contains("-h, --help"));
}

#[tokio::test]
async fn test_cli_rejects_non_web_url_before_browser_startup() {
    for args in [
        vec!["screenshot", "file:///etc/passwd"],
        vec!["pdf", "file:///etc/passwd"],
        vec!["text", "data:text/html,<h1>Test</h1>"],
    ] {
        let mut cmd = Command::cargo_bin("webshot").unwrap();
        cmd.args(args);

        cmd.assert()
            .failure()
            .stderr(predicate::str::contains("Unsupported URL scheme"));
    }
}

#[test]
fn test_readme_uses_actual_height_short_flag() {
    let readme_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("README.md");
    let readme = fs::read_to_string(readme_path).unwrap();

    assert!(
        !readme.contains("-h, --height"),
        "README should document -H for --height because -h is clap help"
    );
    assert!(
        readme.contains("-H, --height"),
        "README should document the actual short flag for --height"
    );
    assert!(
        readme.contains("webshot https://example.com -o screenshot.png -w 1920 -H 1080"),
        "README quick-start example should use -H for viewport height"
    );
    assert!(
        readme.contains("webshot screenshot https://example.com -o test.png -w 1920 -H 1080"),
        "README screenshot subcommand example should use -H for viewport height"
    );
}

#[test]
fn test_readme_documents_batch_output_behavior() {
    let readme_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("README.md");
    let readme = fs::read_to_string(readme_path).unwrap();

    for detail in [
        "#### Output Behavior",
        "Target HTTP(S) URL (required)",
        "Supported output extensions are `.png`, `.jpg`, `.jpeg`, `.webp`, and `.pdf`.",
        "Webshot chooses the runtime output format from the `output` filename extension.",
        "Relative screenshot `output` paths are resolved under `defaults.output_dir` when it is set.",
        "The `multi` command's `-o, --output-dir` option is prepended at runtime to each loaded output path",
        "artifacts/screenshots/home.png",
        "Parent directories for screenshot, PDF, text, diff-image, and JSON comparison outputs are created automatically.",
        "Existing output files are replaced when a command writes the same path.",
    ] {
        assert!(
            readme.contains(detail),
            "README should document batch/output behavior detail: {detail}"
        );
    }
}

#[test]
fn test_readme_release_flow_matches_github_actions() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let readme = fs::read_to_string(manifest_dir.join("README.md"))
        .expect("README.md must exist for release-flow doc test");
    let workflow = fs::read_to_string(manifest_dir.join(".github/workflows/rust.yml"))
        .expect(".github/workflows/rust.yml must exist for release-flow doc test");
    let workflow_yaml: serde_yaml::Value =
        serde_yaml::from_str(&workflow).expect("rust.yml must be valid YAML");

    let workflow_name = workflow_yaml["name"]
        .as_str()
        .expect("workflow should have a name");
    let triggers = &workflow_yaml["on"];
    let jobs = &workflow_yaml["jobs"];
    let test_job = &jobs["test"];
    let release_job = &jobs["release"];

    assert_eq!(workflow_name, "Rust CI");
    assert_eq!(test_job["name"].as_str(), Some("Test"));
    assert_eq!(release_job["name"].as_str(), Some("Create Release"));
    assert_eq!(release_job["needs"].as_str(), Some("test"));
    assert_eq!(
        release_job["if"].as_str(),
        Some("startsWith(github.ref, 'refs/tags/')")
    );

    for branch in ["master", "main"] {
        assert!(
            yaml_sequence_contains(&triggers["push"]["branches"], branch),
            "push trigger should include {branch}"
        );
        assert!(
            yaml_sequence_contains(&triggers["pull_request"]["branches"], branch),
            "pull_request trigger should include {branch}"
        );
    }
    assert!(
        yaml_sequence_contains(&triggers["push"]["tags"], "v*"),
        "push trigger should include v* tags"
    );

    assert!(
        job_has_run_step(test_job, "cargo test --verbose --all-features"),
        "Test job should run the documented test command"
    );
    assert!(
        job_has_run_step(test_job, "cargo build --release --verbose"),
        "Test job should build the release binary before artifact upload"
    );
    assert!(
        job_uses_action(test_job, "actions/upload-artifact@v4"),
        "Test job should upload the release binary artifact"
    );
    assert_eq!(
        find_action_step(test_job, "actions/upload-artifact@v4")["with"]["name"].as_str(),
        Some("webshot-binary")
    );
    assert_eq!(
        find_action_step(test_job, "actions/upload-artifact@v4")["with"]["path"].as_str(),
        Some("target/release/webshot")
    );
    assert_eq!(
        find_action_step(test_job, "actions/upload-artifact@v4")["with"]["retention-days"].as_i64(),
        Some(7)
    );

    assert!(
        job_has_run_step(release_job, "cargo build --release --verbose"),
        "Create Release job should rebuild the release binary after Test succeeds"
    );
    assert!(
        job_uses_action(release_job, "softprops/action-gh-release@v1"),
        "Create Release job should publish through the documented release action"
    );
    assert_eq!(
        find_action_step(release_job, "softprops/action-gh-release@v1")["with"]["files"].as_str(),
        Some("target/release/webshot")
    );
    assert_eq!(
        find_action_step(release_job, "softprops/action-gh-release@v1")["with"]
            ["generate_release_notes"]
            .as_bool(),
        Some(true)
    );

    let documented_details = [
        ("workflow name", "`Rust CI` workflow"),
        ("push branches", "pushes to `master` or `main`"),
        (
            "pull request target branches",
            "`pull_request` events targeting `master` or `main`",
        ),
        ("tag release trigger", "pushed tags matching `v*`"),
        (
            "pull request job scope",
            "Pull requests run only the `Test` job",
        ),
        (
            "release job tag scope",
            "releases are triggered only by `v*` tags",
        ),
        ("test command", "`cargo test --verbose --all-features`"),
        ("release build command", "`cargo build --release --verbose`"),
        ("release binary path", "`target/release/webshot`"),
        ("artifact name", "`webshot-binary`"),
        ("artifact retention", "for seven days"),
        (
            "test dependency",
            "If it succeeds, the `Create Release` job",
        ),
        ("release action", "`softprops/action-gh-release@v1`"),
        ("generated release notes", "`generate_release_notes: true`"),
    ];

    for (description, detail) in documented_details {
        assert!(
            readme.contains(detail),
            "README release flow should document {description}: {detail}"
        );
    }
}

fn yaml_sequence_contains(value: &serde_yaml::Value, expected: &str) -> bool {
    value
        .as_sequence()
        .map(|items| items.iter().any(|item| item.as_str() == Some(expected)))
        .unwrap_or(false)
}

fn job_steps(job: &serde_yaml::Value) -> &[serde_yaml::Value] {
    job["steps"]
        .as_sequence()
        .expect("workflow job should define steps")
}

fn job_has_run_step(job: &serde_yaml::Value, expected: &str) -> bool {
    job_steps(job)
        .iter()
        .any(|step| step["run"].as_str() == Some(expected))
}

fn job_uses_action(job: &serde_yaml::Value, action: &str) -> bool {
    job_steps(job)
        .iter()
        .any(|step| step["uses"].as_str() == Some(action))
}

fn find_action_step<'a>(job: &'a serde_yaml::Value, action: &str) -> &'a serde_yaml::Value {
    job_steps(job)
        .iter()
        .find(|step| step["uses"].as_str() == Some(action))
        .expect("workflow job should include documented action step")
}

#[tokio::test]
async fn test_version_output() {
    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("--version");

    cmd.assert()
        .success()
        .stdout(predicate::str::contains(env!("CARGO_PKG_VERSION")));
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_verbose_logging() {
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("verbose.png");

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg(TEST_URL).arg("-o").arg(&output_path).arg("-v");

    cmd.assert().success();
    assert!(output_path.exists());
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_timeout_handling() {
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("timeout.png");

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    // Test timeout by waiting for an element that doesn't exist
    cmd.arg("https://httpbin.org/html")
        .arg("-o")
        .arg(&output_path)
        .arg("--wait-for")
        .arg(".non-existent-element-that-will-never-appear")
        .arg("-t")
        .arg("2"); // 2 second timeout

    // This should timeout and fail when waiting for non-existent element
    cmd.timeout(std::time::Duration::from_secs(8))
        .assert()
        .failure();
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium startup before validation completes"]
async fn test_config_validation() {
    let temp_dir = TempDir::new().unwrap();

    // Create an invalid config file
    let config_content = r#"
screenshots:
  - url: "not-a-valid-url"
    output: "test.png"
"#;

    let config_path = temp_dir.path().join("invalid-config.yaml");
    fs::write(&config_path, config_content).unwrap();

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("multi").arg(&config_path);

    cmd.assert().failure();
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_subcommand_screenshot() {
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("subcommand.png");

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("screenshot")
        .arg(TEST_URL)
        .arg("-o")
        .arg(&output_path);

    cmd.assert().success();
    assert!(output_path.exists());
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_subcommand_pdf() {
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("subcommand.pdf");

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("pdf")
        .arg(TEST_URL)
        .arg("-o")
        .arg(&output_path)
        .arg("--landscape");

    cmd.assert().success();
    assert!(output_path.exists());

    let content = fs::read(&output_path).unwrap();
    assert!(content.starts_with(b"%PDF"));
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_parallel_processing() {
    let temp_dir = TempDir::new().unwrap();

    // Create config with multiple screenshots
    let config_content = format!(
        r#"
screenshots:
  - url: "{}"
    output: "parallel1.png"
  - url: "{}" 
    output: "parallel2.png"
  - url: "{}"
    output: "parallel3.png"
  - url: "{}"
    output: "parallel4.png"
"#,
        TEST_URL, TEST_URL, TEST_URL, TEST_URL
    );

    let config_path = temp_dir.path().join("parallel-config.yaml");
    fs::write(&config_path, config_content).unwrap();

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("multi")
        .arg(&config_path)
        .arg("-o")
        .arg(temp_dir.path())
        .arg("-p")
        .arg("4");

    cmd.assert().success();

    // Check all files were created
    for i in 1..=4 {
        assert!(temp_dir.path().join(format!("parallel{}.png", i)).exists());
    }
}

// Helper function to create a test image
fn create_test_image(width: u32, height: u32, color: [u8; 3], path: &std::path::Path) {
    let img: image::RgbImage = image::ImageBuffer::from_fn(width, height, |_, _| image::Rgb(color));
    img.save(path).unwrap();
}

#[tokio::test]
async fn test_compare_identical_images() {
    let temp_dir = TempDir::new().unwrap();
    let img1_path = temp_dir.path().join("img1.png");
    let img2_path = temp_dir.path().join("img2.png");

    // Create two identical images
    create_test_image(100, 100, [255, 0, 0], &img1_path);
    create_test_image(100, 100, [255, 0, 0], &img2_path);

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare").arg(&img1_path).arg(&img2_path);

    // Should exit with code 0 (similar images)
    cmd.assert().code(0);
}

#[tokio::test]
async fn test_compare_different_images() {
    let temp_dir = TempDir::new().unwrap();
    let img1_path = temp_dir.path().join("img1.png");
    let img2_path = temp_dir.path().join("img2.png");

    // Create two different images
    create_test_image(100, 100, [255, 0, 0], &img1_path); // Red
    create_test_image(100, 100, [0, 255, 0], &img2_path); // Green

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare").arg(&img1_path).arg(&img2_path);

    // Should exit with code 1 (different images)
    cmd.assert().code(1);
}

#[tokio::test]
async fn test_compare_with_diff_image() {
    let temp_dir = TempDir::new().unwrap();
    let img1_path = temp_dir.path().join("img1.png");
    let img2_path = temp_dir.path().join("img2.png");
    let diff_path = temp_dir.path().join("diff.png");

    // Create two different images
    create_test_image(100, 100, [255, 0, 0], &img1_path);
    create_test_image(100, 100, [0, 255, 0], &img2_path);

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare")
        .arg(&img1_path)
        .arg(&img2_path)
        .arg("--diff-image")
        .arg("--diff-path")
        .arg(&diff_path);

    cmd.assert().code(1);

    // Check that diff image was created
    assert!(diff_path.exists());
    let metadata = fs::metadata(&diff_path).unwrap();
    assert!(metadata.len() > 0);
}

#[tokio::test]
async fn test_compare_json_output_creates_parent_dirs_and_overwrites() {
    let temp_dir = TempDir::new().unwrap();
    let img1_path = temp_dir.path().join("img1.png");
    let img2_path = temp_dir.path().join("img2.png");
    let output_path = temp_dir
        .path()
        .join("reports")
        .join("nested")
        .join("results.json");

    create_test_image(50, 50, [255, 0, 0], &img1_path);
    create_test_image(50, 50, [0, 255, 0], &img2_path);

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare")
        .arg(&img1_path)
        .arg(&img2_path)
        .arg("--format")
        .arg("json")
        .arg("-o")
        .arg(&output_path);

    cmd.assert().code(1);
    assert_json_comparison_output(&output_path);

    fs::write(&output_path, "stale output").unwrap();

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare")
        .arg(&img1_path)
        .arg(&img2_path)
        .arg("--format")
        .arg("json")
        .arg("-o")
        .arg(&output_path);

    cmd.assert().code(1);
    let content = fs::read_to_string(&output_path).unwrap();
    assert!(!content.contains("stale output"));
    assert_json_comparison_output(&output_path);
}

fn assert_json_comparison_output(output_path: &Path) {
    assert!(output_path.exists());
    let content = fs::read_to_string(output_path).unwrap();
    let json: serde_json::Value = serde_json::from_str(&content).unwrap();

    assert!(json["similar"].is_boolean());
    assert!(json["similarity"].is_number());
    assert!(json["algorithm"].is_string());
    assert!(json["threshold"].is_number());
    assert!(json["total_pixels"].is_number());
}

#[tokio::test]
async fn test_compare_text_output_creates_parent_dirs_and_overwrites() {
    let temp_dir = TempDir::new().unwrap();
    let img1_path = temp_dir.path().join("img1.png");
    let img2_path = temp_dir.path().join("img2.png");
    let output_path = temp_dir
        .path()
        .join("reports")
        .join("nested")
        .join("results.txt");

    create_test_image(50, 50, [255, 0, 0], &img1_path);
    create_test_image(50, 50, [255, 0, 0], &img2_path);

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare")
        .arg(&img1_path)
        .arg(&img2_path)
        .arg("-o")
        .arg(&output_path);

    cmd.assert().code(0);
    assert!(output_path.exists());
    assert!(fs::read_to_string(&output_path)
        .unwrap()
        .contains("Similar: YES"));

    fs::write(&output_path, "stale output").unwrap();

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare")
        .arg(&img1_path)
        .arg(&img2_path)
        .arg("-o")
        .arg(&output_path);

    cmd.assert().code(0);
    let content = fs::read_to_string(&output_path).unwrap();
    assert!(content.contains("Image Comparison Results"));
    assert!(!content.contains("stale output"));
}

#[tokio::test]
async fn test_compare_diff_image_creates_parent_dirs_and_overwrites() {
    let temp_dir = TempDir::new().unwrap();
    let img1_path = temp_dir.path().join("img1.png");
    let img2_path = temp_dir.path().join("img2.png");
    let diff_path = temp_dir
        .path()
        .join("diffs")
        .join("nested")
        .join("diff.png");

    create_test_image(50, 50, [255, 0, 0], &img1_path);
    create_test_image(50, 50, [0, 255, 0], &img2_path);

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare")
        .arg(&img1_path)
        .arg(&img2_path)
        .arg("--diff-image")
        .arg("--diff-path")
        .arg(&diff_path);

    cmd.assert().code(1);
    assert!(diff_path.exists());
    assert!(image::open(&diff_path).is_ok());

    fs::write(&diff_path, "stale output").unwrap();

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare")
        .arg(&img1_path)
        .arg(&img2_path)
        .arg("--diff-image")
        .arg("--diff-path")
        .arg(&diff_path);

    cmd.assert().code(1);
    let diff_image = image::open(&diff_path).unwrap();
    assert_eq!(diff_image.width(), 50);
    assert_eq!(diff_image.height(), 50);
    assert_ne!(fs::read(&diff_path).unwrap(), b"stale output");
}

#[tokio::test]
async fn test_compare_different_algorithms() {
    let temp_dir = TempDir::new().unwrap();
    let img1_path = temp_dir.path().join("img1.png");
    let img2_path = temp_dir.path().join("img2.png");

    // Create slightly different images
    create_test_image(50, 50, [255, 0, 0], &img1_path);
    create_test_image(50, 50, [250, 5, 5], &img2_path);

    // Test different algorithms
    let algorithms = ["pixel-diff", "ssim", "mse", "psnr"];

    for algorithm in &algorithms {
        let mut cmd = Command::cargo_bin("webshot").unwrap();
        cmd.arg("compare")
            .arg(&img1_path)
            .arg(&img2_path)
            .arg("-a")
            .arg(algorithm)
            .arg("--format")
            .arg("json");

        let assertion = cmd.assert();
        let output = assertion.get_output();
        let stdout = String::from_utf8(output.stdout.clone()).unwrap();

        if !stdout.is_empty() {
            let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
            // Algorithm names in JSON are PascalCase
            let expected_algorithm = match *algorithm {
                "pixel-diff" => "PixelDiff",
                "ssim" => "SSIM",
                "mse" => "MSE",
                "psnr" => "PSNR",
                _ => *algorithm,
            };
            assert_eq!(json["algorithm"].as_str().unwrap(), expected_algorithm);
        }
    }
}

#[tokio::test]
async fn test_compare_with_threshold() {
    let temp_dir = TempDir::new().unwrap();
    let img1_path = temp_dir.path().join("img1.png");
    let img2_path = temp_dir.path().join("img2.png");

    // Create more different images for the strict test
    create_test_image(50, 50, [255, 0, 0], &img1_path);
    create_test_image(50, 50, [200, 50, 50], &img2_path); // More different colors

    // Test with strict threshold (should be different)
    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare")
        .arg(&img1_path)
        .arg(&img2_path)
        .arg("-t")
        .arg("0.01"); // Very strict threshold, no anti-aliasing flag

    cmd.assert().code(1); // Should be different with strict threshold

    // Test with lenient threshold using more similar images
    let similar_img1_path = temp_dir.path().join("similar1.png");
    let similar_img2_path = temp_dir.path().join("similar2.png");
    create_test_image(50, 50, [255, 0, 0], &similar_img1_path);
    create_test_image(50, 50, [253, 2, 2], &similar_img2_path); // Very similar colors

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare")
        .arg(&similar_img1_path)
        .arg(&similar_img2_path)
        .arg("-t")
        .arg("0.5") // Lenient threshold
        .arg("--ignore-antialiasing");

    cmd.assert().code(0); // Should be similar with lenient threshold
}

#[tokio::test]
async fn test_compare_custom_diff_color() {
    let temp_dir = TempDir::new().unwrap();
    let img1_path = temp_dir.path().join("img1.png");
    let img2_path = temp_dir.path().join("img2.png");
    let diff_path = temp_dir.path().join("diff.png");

    // Create different images
    create_test_image(50, 50, [255, 0, 0], &img1_path);
    create_test_image(50, 50, [0, 255, 0], &img2_path);

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare")
        .arg(&img1_path)
        .arg(&img2_path)
        .arg("--diff-image")
        .arg("--diff-path")
        .arg(&diff_path)
        .arg("--diff-color")
        .arg("0,0,255"); // Blue highlighting

    cmd.assert().code(1);

    // Check that diff image was created
    assert!(diff_path.exists());
}

#[tokio::test]
async fn test_compare_dimension_mismatch() {
    let temp_dir = TempDir::new().unwrap();
    let img1_path = temp_dir.path().join("img1.png");
    let img2_path = temp_dir.path().join("img2.png");

    // Create images with different dimensions
    create_test_image(100, 100, [255, 0, 0], &img1_path);
    create_test_image(200, 100, [255, 0, 0], &img2_path);

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare").arg(&img1_path).arg(&img2_path);

    // Should fail with error due to dimension mismatch
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("dimensions don't match"));
}

#[tokio::test]
async fn test_compare_invalid_files() {
    let temp_dir = TempDir::new().unwrap();
    let nonexistent_path = temp_dir.path().join("nonexistent.png");
    let valid_path = temp_dir.path().join("valid.png");

    create_test_image(50, 50, [255, 0, 0], &valid_path);

    // Test with non-existent first image
    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare").arg(&nonexistent_path).arg(&valid_path);

    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("Failed to load first image"));

    // Test with non-existent second image
    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare").arg(&valid_path).arg(&nonexistent_path);

    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("Failed to load second image"));
}

// Scrolling screenshot tests
#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_full_page_screenshot() {
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("fullpage.png");

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg(TEST_URL)
        .arg("-o")
        .arg(&output_path)
        .arg("--full-page")
        .arg("--max-height")
        .arg("5000"); // Small limit for test

    cmd.assert().success();
    assert!(output_path.exists());

    // Check that the file is not empty
    let metadata = fs::metadata(&output_path).unwrap();
    assert!(metadata.len() > 0);
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_full_page_with_config() {
    let temp_dir = TempDir::new().unwrap();

    // Create a config with scrolling options
    let config_content = format!(
        r#"
defaults:
  scroll_mode: "FullPage"
  max_height: 3000
  scroll_delay: 50

screenshots:
  - url: "{}"
    output: "fullpage-config.png"
    width: 800
    height: 600
"#,
        TEST_URL
    );

    let config_path = temp_dir.path().join("scroll-config.yaml");
    fs::write(&config_path, config_content).unwrap();

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("multi")
        .arg(&config_path)
        .arg("-o")
        .arg(temp_dir.path());

    cmd.assert().success();
    assert!(temp_dir.path().join("fullpage-config.png").exists());
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_full_element_screenshot() {
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("element-full.png");

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg(TEST_URL)
        .arg("-o")
        .arg(&output_path)
        .arg("-s")
        .arg("body") // Select body element
        .arg("--full-page") // This should automatically use FullElement mode
        .arg("--max-height")
        .arg("3000");

    cmd.assert().success();
    assert!(output_path.exists());
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_scroll_delay_option() {
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("scroll-delay.png");

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg(TEST_URL)
        .arg("-o")
        .arg(&output_path)
        .arg("--full-page")
        .arg("--scroll-delay")
        .arg("200")
        .arg("--max-height")
        .arg("2000");

    cmd.assert().success();
    assert!(output_path.exists());
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_viewport_vs_fullpage_difference() {
    let temp_dir = TempDir::new().unwrap();
    let viewport_path = temp_dir.path().join("viewport.png");
    let fullpage_path = temp_dir.path().join("fullpage.png");

    // Take viewport screenshot
    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg(TEST_URL)
        .arg("-o")
        .arg(&viewport_path)
        .arg("-w")
        .arg("800")
        .arg("-H")
        .arg("600");
    cmd.assert().success();

    // Take full page screenshot
    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg(TEST_URL)
        .arg("-o")
        .arg(&fullpage_path)
        .arg("-w")
        .arg("800")
        .arg("-H")
        .arg("600")
        .arg("--full-page")
        .arg("--max-height")
        .arg("3000");
    cmd.assert().success();

    // Both should exist
    assert!(viewport_path.exists());
    assert!(fullpage_path.exists());

    // Full page screenshot should typically be larger (unless page is very short)
    let viewport_size = fs::metadata(&viewport_path).unwrap().len();
    let fullpage_size = fs::metadata(&fullpage_path).unwrap().len();

    // Both should be non-empty
    assert!(viewport_size > 0);
    assert!(fullpage_size > 0);
}

#[tokio::test]
#[ignore = "requires Chrome/Chromium and network access"]
async fn test_max_height_limit() {
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("height-limited.png");

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg(TEST_URL)
        .arg("-o")
        .arg(&output_path)
        .arg("--full-page")
        .arg("--max-height")
        .arg("1000"); // Very small limit

    cmd.assert().success();
    assert!(output_path.exists());
}

#[tokio::test]
async fn test_scroll_mode_config_validation() {
    let temp_dir = TempDir::new().unwrap();

    // Create config with invalid scroll mode for FullElement (no selector)
    let invalid_config = r#"
screenshots:
  - url: "https://httpbin.org/html"
    output: "invalid.png"
    scroll_mode: "FullElement"
"#;

    let config_path = temp_dir.path().join("invalid-scroll-config.yaml");
    fs::write(&config_path, invalid_config).unwrap();

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("multi").arg(&config_path);

    // Should fail validation before browser startup because FullElement
    // scroll mode requires a selector.
    cmd.assert().failure().stderr(predicate::str::contains(
        "FullElement scroll mode requires a selector",
    ));
}

#[tokio::test]
async fn test_compare_invalid_algorithm() {
    let temp_dir = TempDir::new().unwrap();
    let img1_path = temp_dir.path().join("img1.png");
    let img2_path = temp_dir.path().join("img2.png");

    create_test_image(50, 50, [255, 0, 0], &img1_path);
    create_test_image(50, 50, [0, 255, 0], &img2_path);

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare")
        .arg(&img1_path)
        .arg(&img2_path)
        .arg("-a")
        .arg("invalid-algorithm");

    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("Unknown algorithm"));
}

#[tokio::test]
async fn test_compare_text_stdout_output_format() {
    let temp_dir = TempDir::new().unwrap();
    let img1_path = temp_dir.path().join("img1.png");
    let img2_path = temp_dir.path().join("img2.png");

    create_test_image(50, 50, [255, 0, 0], &img1_path);
    create_test_image(50, 50, [0, 255, 0], &img2_path);

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare")
        .arg(&img1_path)
        .arg(&img2_path)
        .arg("--format")
        .arg("text");

    cmd.assert()
        .code(1)
        .stdout(predicate::str::contains("Image Comparison Results"))
        .stdout(predicate::str::contains("Algorithm:"))
        .stdout(predicate::str::contains("Similarity:"))
        .stdout(predicate::str::contains("Similar:"));
}

#[tokio::test]
async fn test_compare_text_output_format() {
    let temp_dir = TempDir::new().unwrap();
    let img1_path = temp_dir.path().join("img1.png");
    let img2_path = temp_dir.path().join("img2.png");
    let output_path = temp_dir.path().join("reports").join("results.txt");

    create_test_image(50, 50, [255, 0, 0], &img1_path);
    create_test_image(50, 50, [0, 255, 0], &img2_path);

    let mut cmd = Command::cargo_bin("webshot").unwrap();
    cmd.arg("compare")
        .arg(&img1_path)
        .arg(&img2_path)
        .arg("--format")
        .arg("text")
        .arg("-o")
        .arg(&output_path);

    cmd.assert().code(1);

    let text_output = fs::read_to_string(&output_path).unwrap();
    assert!(text_output.contains("Image Comparison Results"));
    assert!(text_output.contains("Algorithm:"));
    assert!(text_output.contains("Similarity:"));
    assert!(text_output.contains("Similar:"));
}