vastlint-cli 0.4.19

VAST XML validator and inspector — validate, inspect wrapper chains, and auto-fix IAB VAST 2.0–4.3 ad tags
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
use std::collections::HashMap;
use std::io::Read;
use std::process::ExitCode;

use mimalloc::MiMalloc;
#[global_allocator]
static GLOBAL: MiMalloc = MiMalloc;

use anstream::eprintln;
use anstyle::{AnsiColor, Color, Style};
use clap::{Parser, Subcommand, ValueEnum};
use vastlint_core::{
    fix_with_context, validate_with_context, FixResult, Issue, RuleLevel, Severity,
    ValidationContext, ValidationResult, VastVersion,
};

mod telemetry;

// ── CLI definition ────────────────────────────────────────────────────────────

#[derive(Parser)]
#[command(
    name = "vastlint",
    about = "VAST XML validator — checks tags against the IAB spec",
    version
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Validate one or more VAST XML files or URLs (use - for stdin).
    /// Pass http(s):// URLs to fetch and validate live tags; wrapper chains are
    /// followed automatically up to --max-depth hops.
    Check {
        /// Files to validate, stdin (-), or http(s):// URLs.
        #[arg(required = true, num_args = 1..)]
        files: Vec<String>,

        /// Output format
        #[arg(long, default_value = "plain")]
        format: Format,

        /// Disable colour output
        #[arg(long)]
        no_color: bool,

        /// Exit 0 even when errors are found (useful in some CI setups)
        #[arg(long)]
        no_fail: bool,

        /// Exit 1 when any warning (or error) is found, not just errors.
        /// Useful in CI monitoring jobs that should fail on revenue-impact warnings.
        #[arg(long)]
        fail_on_warning: bool,

        /// Maximum wrapper chain depth to follow when validating URLs (default: 5).
        #[arg(long, default_value = "5", value_name = "N")]
        max_depth: u8,

        /// Print an aggregate summary after all inputs are processed.
        /// In plain mode: totals + top rule hit-counts. In JSON mode: machine-readable object.
        #[arg(long)]
        summary: bool,

        /// Path to a vastlint.toml config file. Defaults to searching up from CWD.
        #[arg(long, value_name = "PATH")]
        config: Option<String>,

        /// Skip config file loading entirely
        #[arg(long)]
        no_config: bool,

        /// Send an anonymous usage ping (version, OS, install ID, file count).
        /// Off by default. See README for what is sent.
        #[arg(long)]
        telemetry: bool,

        /// Treat the input as this VAST spec version regardless of the version
        /// attribute declared in the XML. Useful for templates or tags where the
        /// version attribute is absent, wrong, or not yet set.
        /// Accepted values: 2.0, 3.0, 4.0, 4.1, 4.2, 4.3
        #[arg(long, value_name = "VERSION")]
        vast_version: Option<String>,

        /// Replace substrings matching this regex with a safe placeholder before
        /// validating. Use to suppress false positives from template variables
        /// such as ${CLICK_URL}, %%TRACKING_URL%%, or \[CACHEBUSTER\].
        /// Applied once to the full XML string before any parsing.
        #[arg(long, value_name = "PATTERN")]
        ignore_pattern: Option<String>,
    },
    /// List all known rule IDs with their default severity
    Rules,
    /// \[EXPERIMENTAL\] Automatically fix common VAST issues and write repaired XML.
    /// Applies opinionated, deterministic repairs (HTTPS upgrades, conditionalAd removal).
    /// Always review the diff — use --dry-run first. Future releases may make fixes configurable.
    Fix {
        /// File to fix. Pass - to read from stdin and write repaired XML to stdout.
        #[arg(required = true)]
        file: String,

        /// Write repaired XML to this path instead of overwriting the input file.
        /// When reading from stdin, output always goes to stdout regardless of this flag.
        #[arg(long, value_name = "PATH")]
        out: Option<String>,

        /// Show what would be changed without writing any files.
        #[arg(long)]
        dry_run: bool,

        /// Output format for the fix report
        #[arg(long, default_value = "plain")]
        format: Format,

        /// Disable colour output
        #[arg(long)]
        no_color: bool,

        /// Path to a vastlint.toml config file. Defaults to searching up from CWD.
        #[arg(long, value_name = "PATH")]
        config: Option<String>,

        /// Skip config file loading entirely
        #[arg(long)]
        no_config: bool,

        /// Treat the input as this VAST spec version regardless of the version
        /// attribute declared in the XML.
        /// Accepted values: 2.0, 3.0, 4.0, 4.1, 4.2, 4.3
        #[arg(long, value_name = "VERSION")]
        vast_version: Option<String>,

        /// Replace substrings matching this regex with a safe placeholder before
        /// fixing. Use to suppress noise from template variables.
        #[arg(long, value_name = "PATTERN")]
        ignore_pattern: Option<String>,
    },
    /// Run as a long-lived port daemon for Erlang/Elixir OTP integration.
    /// Reads length-prefixed VAST XML from stdin, writes length-prefixed JSON
    /// validation results to stdout. Compatible with Erlang port option
    /// `{:packet, 4}`. Runs until stdin is closed by the BEAM supervisor.
    Daemon,
}

#[derive(ValueEnum, Clone)]
enum Format {
    Plain,
    Json,
}

// ── exit codes ────────────────────────────────────────────────────────────────

/// Exit 0: all files valid (no errors).
/// Exit 1: at least one file had validation errors.
/// Exit 2: CLI usage error (unreadable file, bad config).
const EXIT_VALIDATION_ERROR: u8 = 1;
const EXIT_USAGE_ERROR: u8 = 2;

// ── entry point ───────────────────────────────────────────────────────────────

fn main() -> ExitCode {
    let cli = Cli::parse();

    match cli.command {
        Command::Check {
            files,
            format,
            no_color,
            no_fail,
            fail_on_warning,
            max_depth,
            summary,
            config,
            no_config,
            telemetry,
            vast_version,
            ignore_pattern,
        } => {
            if no_color {
                std::env::set_var("NO_COLOR", "1");
            }
            run_check(
                files,
                format,
                no_fail,
                fail_on_warning,
                max_depth,
                summary,
                config,
                no_config,
                telemetry,
                vast_version,
                ignore_pattern,
            )
        }
        Command::Rules => {
            run_rules();
            ExitCode::SUCCESS
        }
        Command::Fix {
            file,
            out,
            dry_run,
            format,
            no_color,
            config,
            no_config,
            vast_version,
            ignore_pattern,
        } => {
            if no_color {
                std::env::set_var("NO_COLOR", "1");
            }
            run_fix(
                file,
                out,
                dry_run,
                format,
                config,
                no_config,
                vast_version,
                ignore_pattern,
            )
        }
        Command::Daemon => run_daemon(),
    }
}

// ── config loading ────────────────────────────────────────────────────────────

/// Parsed configuration from a vastlint.toml file.
struct Config {
    rule_overrides: Option<HashMap<&'static str, RuleLevel>>,
    /// Whether the user has opted in to telemetry via the config file.
    telemetry: bool,
}

/// Load rule overrides from a config file.
///
/// Returns None when no config file is found or loading is disabled.
/// Returns an error string when a config file was found but could not be parsed.
fn load_config(config_path: Option<String>, no_config: bool) -> Result<Option<Config>, String> {
    if no_config {
        return Ok(None);
    }

    let path = match config_path {
        Some(p) => std::path::PathBuf::from(p),
        None => match find_config_file() {
            Some(p) => p,
            None => return Ok(None),
        },
    };

    let content =
        std::fs::read_to_string(&path).map_err(|e| format!("{}: {}", path.display(), e))?;

    parse_config(&content, &path.display().to_string())
}
/// Walk up from CWD looking for `vastlint.toml` or `.vastlint.toml`.
fn find_config_file() -> Option<std::path::PathBuf> {
    let mut dir = std::env::current_dir().ok()?;
    loop {
        for name in &["vastlint.toml", ".vastlint.toml"] {
            let candidate = dir.join(name);
            if candidate.exists() {
                return Some(candidate);
            }
        }
        if !dir.pop() {
            break;
        }
    }
    None
}

/// Parse a TOML config string into a Config.
///
/// Expected format:
/// ```toml
/// telemetry = true   # opt-in to anonymous usage ping
///
/// [rules]
/// "VAST-2.0-mediafile-https" = "off"
/// "VAST-2.0-root-version" = "error"
/// ```
fn parse_config(content: &str, source: &str) -> Result<Option<Config>, String> {
    let table: toml::Table = content.parse().map_err(|e| format!("{source}: {e}"))?;

    let telemetry_cfg = match table.get("telemetry") {
        Some(toml::Value::Boolean(b)) => *b,
        Some(_) => return Err(format!("{source}: telemetry must be a boolean")),
        None => false,
    };

    let rules_table = match table.get("rules") {
        Some(toml::Value::Table(t)) => t,
        Some(_) => return Err(format!("{source}: [rules] must be a table")),
        None => {
            return Ok(Some(Config {
                rule_overrides: None,
                telemetry: telemetry_cfg,
            }));
        }
    };

    let catalog = vastlint_core::all_rules();
    let mut map: HashMap<&'static str, RuleLevel> = HashMap::new();

    for (key, val) in rules_table {
        let level_str = match val {
            toml::Value::String(s) => s.as_str(),
            _ => {
                return Err(format!(
                    "{source}: rule value for \"{key}\" must be a string"
                ))
            }
        };

        let level = match level_str {
            "error" => RuleLevel::Error,
            "warning" => RuleLevel::Warning,
            "info" => RuleLevel::Info,
            "off" => RuleLevel::Off,
            other => {
                return Err(format!(
                    "{source}: unknown level \"{other}\" for rule \"{key}\" — must be error, warning, info, or off"
                ))
            }
        };

        // Validate the rule ID against the catalog. Warn but continue.
        let known = catalog.iter().find(|r| r.id == key.as_str());
        if known.is_none() {
            eprintln!("{source}: warning: unknown rule ID \"{key}\" — ignored");
            continue;
        }

        // Safe: we just confirmed the ID exists in the static catalog, so the
        // static str lifetime is satisfied by the catalog entry.
        let static_id: &'static str = known.unwrap().id;
        map.insert(static_id, level);
    }

    Ok(Some(Config {
        rule_overrides: if map.is_empty() { None } else { Some(map) },
        telemetry: telemetry_cfg,
    }))
}

// ── check subcommand ──────────────────────────────────────────────────────────

#[allow(clippy::too_many_arguments)]
fn run_check(
    files: Vec<String>,
    format: Format,
    no_fail: bool,
    fail_on_warning: bool,
    max_depth: u8,
    summary: bool,
    config_path: Option<String>,
    no_config: bool,
    telemetry_flag: bool,
    vast_version: Option<String>,
    ignore_pattern: Option<String>,
) -> ExitCode {
    let forced_version = match parse_vast_version_arg(vast_version) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("error: {}", e);
            return ExitCode::from(EXIT_USAGE_ERROR);
        }
    };
    let ignore_re = match build_ignore_regex(ignore_pattern) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("error: {}", e);
            return ExitCode::from(EXIT_USAGE_ERROR);
        }
    };
    let cfg = match load_config(config_path, no_config) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("error: {}", e);
            return ExitCode::from(EXIT_USAGE_ERROR);
        }
    };

    let (rule_overrides, telemetry_enabled) = match cfg {
        Some(c) => (c.rule_overrides, c.telemetry || telemetry_flag),
        None => (None, telemetry_flag),
    };

    let mut any_errors = false;
    let mut any_warnings = false;
    // For --summary: accumulate (label, issue) pairs across all inputs.
    let mut all_issues: Vec<(String, vastlint_core::Issue)> = Vec::new();
    let mut total_inputs = 0usize;
    let mut total_valid = 0usize;

    for file in &files {
        total_inputs += 1;
        if file.starts_with("http://") || file.starts_with("https://") {
            // ── URL mode: fetch + follow wrapper chain ────────────────────────
            let chain_results = fetch_and_validate_chain(file, max_depth, rule_overrides.clone());
            for (label, result) in &chain_results {
                let has_errors = !result.summary.is_valid();
                let has_warnings = result.summary.warnings > 0;
                if has_errors {
                    any_errors = true;
                }
                if has_warnings {
                    any_warnings = true;
                }
                if !has_errors {
                    total_valid += 1;
                }
                if summary {
                    for issue in &result.issues {
                        all_issues.push((label.clone(), issue.clone()));
                    }
                }
                match format {
                    Format::Plain => print_plain(label, result),
                    Format::Json => print_json(label, result),
                }
            }
        } else {
            // ── File / stdin mode ─────────────────────────────────────────────
            let raw = match read_input(file) {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("{}: {}", file, e);
                    return ExitCode::from(EXIT_USAGE_ERROR);
                }
            };
            let input = apply_ignore(&raw, &ignore_re);

            let ctx = ValidationContext {
                rule_overrides: rule_overrides.clone(),
                forced_version,
                ..Default::default()
            };
            let result = validate_with_context(&input, ctx);
            let has_errors = !result.summary.is_valid();
            let has_warnings = result.summary.warnings > 0;
            if has_errors {
                any_errors = true;
            }
            if has_warnings {
                any_warnings = true;
            }
            if !has_errors {
                total_valid += 1;
            }
            if summary {
                for issue in &result.issues {
                    all_issues.push((file.clone(), issue.clone()));
                }
            }
            match format {
                Format::Plain => print_plain(file, &result),
                Format::Json => print_json(file, &result),
            }
        }
    }

    if summary {
        print_summary(&all_issues, total_inputs, total_valid, &format);
    }

    if telemetry_enabled {
        telemetry::ping(files.len());
    } else {
        telemetry::maybe_show_notice();
    }

    if no_fail {
        return ExitCode::SUCCESS;
    }
    if any_errors || (fail_on_warning && any_warnings) {
        ExitCode::from(EXIT_VALIDATION_ERROR)
    } else {
        ExitCode::SUCCESS
    }
}

// ── URL fetch + wrapper chain ─────────────────────────────────────────────────

/// Fetch a VAST URL, validate it, then follow any `<VASTAdTagURI>` wrapper
/// redirect up to `max_depth` hops. Returns one (label, ValidationResult)
/// per hop so each is displayed individually.
fn fetch_and_validate_chain(
    url: &str,
    max_depth: u8,
    rule_overrides: Option<std::collections::HashMap<&'static str, vastlint_core::RuleLevel>>,
) -> Vec<(String, ValidationResult)> {
    let mut results = Vec::new();
    let mut current_url = url.to_owned();
    let mut depth: u8 = 0;

    loop {
        let xml = match fetch_url(&current_url) {
            Ok(s) => s,
            Err(e) => {
                let label = if depth == 0 {
                    current_url.clone()
                } else {
                    format!("{} [wrapper depth {}]", current_url, depth)
                };
                eprintln!("error fetching {}: {}", current_url, e);
                let ctx = ValidationContext {
                    wrapper_depth: depth,
                    max_wrapper_depth: max_depth,
                    rule_overrides: rule_overrides.clone(),
                    forced_version: None,
                };
                results.push((label, validate_with_context("", ctx)));
                break;
            }
        };

        let label = if depth == 0 {
            current_url.clone()
        } else {
            format!("{} [wrapper depth {}]", current_url, depth)
        };

        let ctx = ValidationContext {
            wrapper_depth: depth,
            max_wrapper_depth: max_depth,
            rule_overrides: rule_overrides.clone(),
            forced_version: None,
        };
        let result = validate_with_context(&xml, ctx);
        let next_url = extract_vast_ad_tag_uri(&xml);
        results.push((label, result));

        depth += 1;
        match next_url {
            Some(next) if depth <= max_depth => {
                current_url = next;
            }
            _ => break,
        }
    }

    results
}

/// Fetch a URL and return the response body as a String.
fn fetch_url(url: &str) -> Result<String, String> {
    ureq::get(url)
        .timeout(std::time::Duration::from_secs(10))
        .set(
            "User-Agent",
            concat!("vastlint-cli/", env!("CARGO_PKG_VERSION")),
        )
        .call()
        .map_err(|e| e.to_string())?
        .into_string()
        .map_err(|e| e.to_string())
}

/// Extract the text content of the first `<VASTAdTagURI>` element.
/// Used to follow wrapper chains without a full re-parse.
fn extract_vast_ad_tag_uri(xml: &str) -> Option<String> {
    let start_tag = "<VASTAdTagURI>";
    let end_tag = "</VASTAdTagURI>";
    let start = xml.find(start_tag)? + start_tag.len();
    let end = xml[start..].find(end_tag)? + start;
    let raw = xml[start..end].trim();
    // Strip CDATA wrapper if present.
    let value = if raw.starts_with("<![CDATA[") && raw.ends_with("]]>") {
        raw[9..raw.len() - 3].trim()
    } else {
        raw
    };
    if value.is_empty() {
        None
    } else {
        Some(value.to_owned())
    }
}

// ── aggregate summary ─────────────────────────────────────────────────────────

fn print_summary(
    all_issues: &[(String, vastlint_core::Issue)],
    total_inputs: usize,
    total_valid: usize,
    format: &Format,
) {
    let mut rule_counts: std::collections::HashMap<&str, (usize, Severity)> =
        std::collections::HashMap::new();
    let mut total_errors = 0usize;
    let mut total_warnings = 0usize;
    let mut total_infos = 0usize;

    for (_, issue) in all_issues {
        match issue.severity {
            Severity::Error => total_errors += 1,
            Severity::Warning => total_warnings += 1,
            Severity::Info => total_infos += 1,
        }
        rule_counts
            .entry(issue.id)
            .and_modify(|(c, _)| *c += 1)
            .or_insert((1, issue.severity));
    }

    let mut sorted: Vec<(&str, usize, Severity)> = rule_counts
        .iter()
        .map(|(id, (count, sev))| (*id, *count, *sev))
        .collect();
    sorted.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));

    let revenue_id = |id: &str| -> bool {
        vastlint_core::all_rules()
            .iter()
            .find(|r| r.id == id)
            .map(|r| r.revenue_impact())
            .unwrap_or(false)
    };

    match format {
        Format::Plain => {
            println!(
                "\n{}── Summary ─────────────────────────────────────────────────{}",
                BOLD_STYLE.render(),
                BOLD_STYLE.render_reset()
            );
            println!("  Inputs checked : {}", total_inputs);
            println!(
                "  Valid          : {}{}/{}{}",
                if total_valid == total_inputs {
                    OK_STYLE.render()
                } else {
                    ERROR_STYLE.render()
                },
                total_valid,
                total_inputs,
                OK_STYLE.render_reset(),
            );
            println!(
                "  Errors         : {}{}{}",
                if total_errors > 0 {
                    ERROR_STYLE.render()
                } else {
                    OK_STYLE.render()
                },
                total_errors,
                ERROR_STYLE.render_reset(),
            );
            println!(
                "  Warnings       : {}{}{}",
                if total_warnings > 0 {
                    WARN_STYLE.render()
                } else {
                    OK_STYLE.render()
                },
                total_warnings,
                WARN_STYLE.render_reset(),
            );
            println!("  Infos          : {}", total_infos);

            if !sorted.is_empty() {
                println!(
                    "\n  {}Top issues by frequency:{}  ($ = revenue impact)",
                    BOLD_STYLE.render(),
                    BOLD_STYLE.render_reset()
                );
                for (id, count, sev) in sorted.iter().take(10) {
                    let style = match sev {
                        Severity::Error => ERROR_STYLE,
                        Severity::Warning => WARN_STYLE,
                        Severity::Info => INFO_STYLE,
                    };
                    let ri_marker = if revenue_id(id) {
                        format!(
                            "  {}$revenue{}",
                            WARN_STYLE.render(),
                            WARN_STYLE.render_reset()
                        )
                    } else {
                        String::new()
                    };
                    println!(
                        "  {}  {:>4}×  {}{}{}",
                        style.render(),
                        count,
                        id,
                        style.render_reset(),
                        ri_marker
                    );
                }
            }
            println!();
        }
        Format::Json => {
            let top_rules: Vec<String> =
                sorted
                    .iter()
                    .take(20)
                    .map(|(id, count, sev)| {
                        format!(
                        "{{\"id\":\"{}\",\"count\":{},\"severity\":\"{}\",\"revenue_impact\":{}}}",
                        id, count, sev.as_str(), revenue_id(id)
                    )
                    })
                    .collect();
            println!(
                "{{\"summary\":{{\"total_inputs\":{},\"total_valid\":{},\"errors\":{},\"warnings\":{},\"infos\":{},\"top_rules\":[{}]}}}}",
                total_inputs, total_valid, total_errors, total_warnings, total_infos,
                top_rules.join(",")
            );
        }
    }
}

fn read_input(file: &str) -> Result<String, String> {
    if file == "-" {
        let mut buf = String::new();
        std::io::stdin()
            .read_to_string(&mut buf)
            .map_err(|e| format!("failed to read stdin: {e}"))?;
        Ok(buf)
    } else {
        std::fs::read_to_string(file).map_err(|e| format!("{e}"))
    }
}

// ── plain output ──────────────────────────────────────────────────────────────

const ERROR_STYLE: Style = Style::new()
    .fg_color(Some(Color::Ansi(AnsiColor::Red)))
    .bold();
const WARN_STYLE: Style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)));
const INFO_STYLE: Style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan)));
const DIM_STYLE: Style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::BrightBlack)));
const BOLD_STYLE: Style = Style::new().bold();
const OK_STYLE: Style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Green)));

const UNDERLINE_STYLE: Style = Style::new().underline();

fn print_plain(file: &str, result: &ValidationResult) {
    let version_str = result
        .version
        .best()
        .map(|v| v.as_str())
        .unwrap_or("unknown");

    println!(
        "\n{}{}{}  {}VAST {}{}",
        UNDERLINE_STYLE.render(),
        file,
        UNDERLINE_STYLE.render_reset(),
        DIM_STYLE.render(),
        version_str,
        DIM_STYLE.render_reset(),
    );

    if result.issues.is_empty() {
        println!(
            "  {}✓ no issues{}\n",
            OK_STYLE.render(),
            OK_STYLE.render_reset()
        );
        return;
    }

    for issue in &result.issues {
        print_issue(issue);
    }

    let s = &result.summary;
    let marker = if result.summary.is_valid() {
        format!("{}{}", OK_STYLE.render(), OK_STYLE.render_reset())
    } else {
        format!("{}{}", ERROR_STYLE.render(), ERROR_STYLE.render_reset())
    };

    println!(
        "\n{} {} error{}, {} warning{}, {} info\n",
        marker,
        s.errors,
        if s.errors == 1 { "" } else { "s" },
        s.warnings,
        if s.warnings == 1 { "" } else { "s" },
        s.infos,
    );
}

fn print_issue(issue: &Issue) {
    let (label, style) = match issue.severity {
        Severity::Error => ("error  ", ERROR_STYLE),
        Severity::Warning => ("warning", WARN_STYLE),
        Severity::Info => ("info   ", INFO_STYLE),
    };

    let path = issue.path.as_deref().unwrap_or("(document)");

    // Line 1: severity + message + rule ID
    println!(
        "  {}{}{}  {}  {}{}{}",
        style.render(),
        label,
        style.render_reset(),
        issue.message,
        DIM_STYLE.render(),
        issue.id,
        DIM_STYLE.render_reset(),
    );
    // Line 2: XPath location + line:col (dimmed, indented under severity)
    let location = match (issue.line, issue.col) {
        (Some(l), Some(c)) => format!("{}:{}:{}", path, l, c),
        (Some(l), None) => format!("{}:{}", path, l),
        _ => path.to_owned(),
    };
    println!(
        "  {}         {}{}",
        DIM_STYLE.render(),
        location,
        DIM_STYLE.render_reset(),
    );
}

// ── JSON output ───────────────────────────────────────────────────────────────

fn print_json(file: &str, result: &ValidationResult) {
    let version_str = result
        .version
        .best()
        .map(|v| v.as_str())
        .unwrap_or("unknown");

    let issues_json: Vec<String> = result
        .issues
        .iter()
        .map(|i| {
            let path = match &i.path {
                Some(p) => format!("\"{}\"", json_escape(p)),
                None => "null".to_owned(),
            };
            let line = match i.line {
                Some(l) => l.to_string(),
                None => "null".to_owned(),
            };
            let col = match i.col {
                Some(c) => c.to_string(),
                None => "null".to_owned(),
            };
            format!(
                "{{\"id\":\"{}\",\"severity\":\"{}\",\"message\":\"{}\",\"path\":{},\"spec_ref\":\"{}\",\"line\":{},\"col\":{}}}",
                i.id,
                i.severity.as_str(),
                json_escape(i.message),
                path,
                i.spec_ref,
                line,
                col,
            )
        })
        .collect();

    println!(
        "{{\"file\":\"{}\",\"version\":\"{}\",\"valid\":{},\"summary\":{{\"errors\":{},\"warnings\":{},\"infos\":{}}},\"issues\":[{}]}}",
        json_escape(file),
        version_str,
        result.summary.is_valid(),
        result.summary.errors,
        result.summary.warnings,
        result.summary.infos,
        issues_json.join(","),
    );
}

fn json_escape(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
        .replace('\r', "\\r")
        .replace('\t', "\\t")
}

// ── fix subcommand ────────────────────────────────────────────────────────────

#[allow(clippy::too_many_arguments)]
fn run_fix(
    file: String,
    out: Option<String>,
    dry_run: bool,
    format: Format,
    config_path: Option<String>,
    no_config: bool,
    vast_version: Option<String>,
    ignore_pattern: Option<String>,
) -> ExitCode {
    let forced_version = match parse_vast_version_arg(vast_version) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("error: {}", e);
            return ExitCode::from(EXIT_USAGE_ERROR);
        }
    };
    let ignore_re = match build_ignore_regex(ignore_pattern) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("error: {}", e);
            return ExitCode::from(EXIT_USAGE_ERROR);
        }
    };
    let cfg = match load_config(config_path, no_config) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("error: {}", e);
            return ExitCode::from(EXIT_USAGE_ERROR);
        }
    };

    let rule_overrides = cfg.and_then(|c| c.rule_overrides);
    let ctx = ValidationContext {
        rule_overrides,
        forced_version,
        ..Default::default()
    };

    let raw = match read_input(&file) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("{}: {}", file, e);
            return ExitCode::from(EXIT_USAGE_ERROR);
        }
    };
    let input = apply_ignore(&raw, &ignore_re);

    let result = fix_with_context(&input, ctx);
    let is_stdin = file == "-";

    match format {
        Format::Plain => print_fix_plain(&file, &result, dry_run),
        Format::Json => print_fix_json(&file, &result),
    }

    if !dry_run {
        if is_stdin {
            // stdin → stdout: write repaired XML directly.
            print!("{}", result.xml);
        } else {
            let dest = out.as_deref().unwrap_or(file.as_str());

            // Write a .bak backup only when writing in-place (no --out flag).
            if out.is_none() {
                let bak = format!("{}.bak", file);
                if let Err(e) = std::fs::copy(&file, &bak) {
                    eprintln!("error: failed to write backup {}: {}", bak, e);
                    return ExitCode::from(EXIT_USAGE_ERROR);
                }
            }

            if let Err(e) = std::fs::write(dest, &result.xml) {
                eprintln!("error: failed to write {}: {}", dest, e);
                return ExitCode::from(EXIT_USAGE_ERROR);
            }
        }
    }

    // Exit 0 when no remaining errors; exit 1 when issues remain.
    if result
        .remaining
        .iter()
        .any(|i| i.severity == Severity::Error)
    {
        ExitCode::from(EXIT_VALIDATION_ERROR)
    } else {
        ExitCode::SUCCESS
    }
}

fn print_fix_plain(file: &str, result: &FixResult, dry_run: bool) {
    let dry_label = if dry_run { " (dry run)" } else { "" };
    println!(
        "\n{}{}{}{}",
        UNDERLINE_STYLE.render(),
        file,
        UNDERLINE_STYLE.render_reset(),
        dry_label,
    );

    if result.applied.is_empty() {
        println!(
            "  {}✓ nothing to fix{}",
            OK_STYLE.render(),
            OK_STYLE.render_reset()
        );
    } else {
        for fix in &result.applied {
            println!(
                "  {}fixed{}  {}  {}{}{}",
                OK_STYLE.render(),
                OK_STYLE.render_reset(),
                fix.description,
                DIM_STYLE.render(),
                fix.rule_id,
                DIM_STYLE.render_reset(),
            );
            println!(
                "  {}         {}{}",
                DIM_STYLE.render(),
                fix.path,
                DIM_STYLE.render_reset(),
            );
        }
    }

    if !result.remaining.is_empty() {
        println!(
            "\n  {}Remaining issues (not auto-fixable):{}",
            BOLD_STYLE.render(),
            BOLD_STYLE.render_reset()
        );
        for issue in &result.remaining {
            print_issue(issue);
        }
    }

    let n = result.applied.len();
    println!(
        "\n  {} fix{} applied, {} remaining\n",
        n,
        if n == 1 { "" } else { "es" },
        result.remaining.len(),
    );
}

fn print_fix_json(file: &str, result: &FixResult) {
    let applied_json: Vec<String> = result
        .applied
        .iter()
        .map(|f| {
            format!(
                "{{\"rule_id\":\"{}\",\"description\":\"{}\",\"path\":\"{}\"}}",
                f.rule_id,
                json_escape(&f.description),
                json_escape(&f.path),
            )
        })
        .collect();

    let remaining_json: Vec<String> = result
        .remaining
        .iter()
        .map(|i| {
            let path = match &i.path {
                Some(p) => format!("\"{}\"", json_escape(p)),
                None => "null".to_owned(),
            };
            format!(
                "{{\"id\":\"{}\",\"severity\":\"{}\",\"message\":\"{}\",\"path\":{}}}",
                i.id,
                i.severity.as_str(),
                json_escape(i.message),
                path,
            )
        })
        .collect();

    println!(
        "{{\"file\":\"{}\",\"applied\":[{}],\"remaining\":[{}],\"valid\":{}}}",
        json_escape(file),
        applied_json.join(","),
        remaining_json.join(","),
        result
            .remaining
            .iter()
            .all(|i| i.severity != Severity::Error),
    );
}

// ── rules subcommand ──────────────────────────────────────────────────────────

fn run_rules() {
    let rules = vastlint_core::all_rules();

    println!(
        "{}{:<45} {:<8} {:<18} {:<3} DESCRIPTION{}",
        BOLD_STYLE.render(),
        "RULE ID",
        "DEFAULT",
        "SOURCE",
        "$",
        BOLD_STYLE.render_reset()
    );
    println!(
        "{}{}{}",
        DIM_STYLE.render(),
        "".repeat(125),
        DIM_STYLE.render_reset()
    );

    for rule in rules {
        let style = match rule.default_severity {
            Severity::Error => ERROR_STYLE,
            Severity::Warning => WARN_STYLE,
            Severity::Info => INFO_STYLE,
        };
        let ri = if rule.revenue_impact() {
            format!("{}${}  ", WARN_STYLE.render(), WARN_STYLE.render_reset())
        } else {
            "   ".to_owned()
        };
        println!(
            "{:<45} {}{:<8}{}  {:<18}  {}{}",
            rule.id,
            style.render(),
            rule.default_severity.as_str(),
            style.render_reset(),
            rule.source.as_str(),
            ri,
            rule.description,
        );
    }
    println!(
        "\n{}$ = revenue impact — violation results in lost impressions, broken measurement, or zero fill{}",
        DIM_STYLE.render(), DIM_STYLE.render_reset()
    );
}

// ── --vast-version / --ignore-pattern helpers ─────────────────────────────────

/// Parse the `--vast-version` argument string into an optional `VastVersion`.
fn parse_vast_version_arg(s: Option<String>) -> Result<Option<VastVersion>, String> {
    match s.as_deref() {
        None => Ok(None),
        Some("2.0") => Ok(Some(VastVersion::V2_0)),
        Some("3.0") => Ok(Some(VastVersion::V3_0)),
        Some("4.0") => Ok(Some(VastVersion::V4_0)),
        Some("4.1") => Ok(Some(VastVersion::V4_1)),
        Some("4.2") => Ok(Some(VastVersion::V4_2)),
        Some("4.3") => Ok(Some(VastVersion::V4_3)),
        Some(other) => Err(format!(
            "--vast-version \"{other}\" is not a recognised VAST version — accepted: 2.0, 3.0, 4.0, 4.1, 4.2, 4.3"
        )),
    }
}

/// Compile the `--ignore-pattern` regex. Returns `None` when no pattern was given.
fn build_ignore_regex(pattern: Option<String>) -> Result<Option<regex::Regex>, String> {
    match pattern {
        None => Ok(None),
        Some(p) => regex::Regex::new(&p)
            .map(Some)
            .map_err(|e| format!("--ignore-pattern: invalid regex: {e}")),
    }
}

/// Replace every match of `re` in `input` with a benign placeholder.
/// The placeholder is chosen to be a valid HTTPS URL so URL-field validators
/// do not fire on the substituted positions.
fn apply_ignore(input: &str, re: &Option<regex::Regex>) -> String {
    match re {
        None => input.to_owned(),
        Some(r) => r
            .replace_all(input, "https://placeholder.vastlint.invalid")
            .into_owned(),
    }
}

// ── daemon subcommand ─────────────────────────────────────────────────────────

/// OTP port daemon for Erlang/Elixir integration.
///
/// Protocol: 4-byte big-endian message length (Erlang `{:packet, 4}` framing).
///   stdin  → 4-byte BE length | raw VAST XML bytes (UTF-8)
///   stdout → 4-byte BE length | JSON validation result bytes
///
/// Runs until stdin EOF (BEAM supervisor closed the port). All coloured output
/// is suppressed — stdout is reserved for the binary protocol.
fn run_daemon() -> ExitCode {
    use std::io::{BufWriter, ErrorKind, Write};

    // Suppress any colour output that could contaminate the binary protocol.
    std::env::set_var("NO_COLOR", "1");

    let stdin = std::io::stdin();
    let stdout = std::io::stdout();
    let mut stdin = stdin.lock();
    let mut out = BufWriter::new(stdout.lock());

    loop {
        // Read the 4-byte big-endian length prefix.
        let mut len_buf = [0u8; 4];
        match stdin.read_exact(&mut len_buf) {
            Ok(()) => {}
            Err(e) if e.kind() == ErrorKind::UnexpectedEof => break, // port closed — clean exit
            Err(e) => {
                let _ = writeln!(std::io::stderr(), "vastlint daemon: read error: {e}");
                return ExitCode::from(EXIT_USAGE_ERROR);
            }
        }

        let msg_len = u32::from_be_bytes(len_buf) as usize;
        let mut xml_buf = vec![0u8; msg_len];
        if let Err(e) = stdin.read_exact(&mut xml_buf) {
            let _ = writeln!(std::io::stderr(), "vastlint daemon: read error: {e}");
            return ExitCode::from(EXIT_USAGE_ERROR);
        }

        let response = match std::str::from_utf8(&xml_buf) {
            Ok(xml) => {
                let result = validate_with_context(xml, ValidationContext::default());
                daemon_result_json(&result)
            }
            Err(_) => {
                // Invalid UTF-8 — return a structured error response rather than crashing.
                r#"{"version":"unknown","valid":false,"summary":{"errors":1,"warnings":0,"infos":0},"issues":[{"id":"daemon-invalid-utf8","severity":"error","message":"Input is not valid UTF-8","path":null,"spec_ref":""}]}"#
                    .to_owned()
            }
        };

        let bytes = response.as_bytes();
        let out_len = (bytes.len() as u32).to_be_bytes();
        // Any write failure means the port owner closed stdout — exit cleanly.
        if out.write_all(&out_len).is_err() || out.write_all(bytes).is_err() || out.flush().is_err()
        {
            break;
        }
    }

    ExitCode::SUCCESS
}

/// Serialize a `ValidationResult` to the daemon JSON wire format.
/// Shape matches the documented vastlint-erlang OTP port response.
fn daemon_result_json(result: &ValidationResult) -> String {
    let version_str = result
        .version
        .best()
        .map(|v| v.as_str())
        .unwrap_or("unknown");

    let issues_json: Vec<String> = result
        .issues
        .iter()
        .map(|i| {
            let path = match &i.path {
                Some(p) => format!("\"{}\"", json_escape(p)),
                None => "null".to_owned(),
            };
            format!(
                "{{\"id\":\"{}\",\"severity\":\"{}\",\"message\":\"{}\",\"path\":{},\"spec_ref\":\"{}\"}}", 
                i.id,
                i.severity.as_str(),
                json_escape(i.message),
                path,
                i.spec_ref,
            )
        })
        .collect();

    format!(
        "{{\"version\":\"{}\",\"valid\":{},\"summary\":{{\"errors\":{},\"warnings\":{},\"infos\":{}}},\"issues\":[{}]}}",
        version_str,
        result.summary.is_valid(),
        result.summary.errors,
        result.summary.warnings,
        result.summary.infos,
        issues_json.join(","),
    )
}