ym 0.3.57

Yummy - A modern Java build tool
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
use anyhow::{bail, Result};
use console::style;
use std::process::Command;
use std::time::Duration;

use crate::config;
use crate::scripts;
use crate::watcher::FileWatcher;

extern crate walkdir;

#[derive(Clone, Copy)]
enum TestMode {
    Unit,
    Integration,
    All,
}

pub fn execute(
    target: Option<String>,
    watch: bool,
    filter: Option<String>,
    integration: bool,
    all: bool,
    tag: Option<String>,
    exclude_tag: Option<String>,
    verbose: bool,
    fail_fast: bool,
    timeout: Option<u64>,
    coverage: bool,
    list: bool,
    keep_going: bool,
    report: Option<String>,
    parallel: bool,
) -> Result<()> {
    let (config_path, cfg) = config::load_or_find_config()?;
    let project = config::project_dir(&config_path);

    // Ensure JDK is available
    super::build::ensure_jdk_for_config(&cfg)?;

    let test_mode = if all {
        TestMode::All
    } else if integration {
        TestMode::Integration
    } else {
        TestMode::Unit
    };

    // Workspace mode
    if cfg.workspaces.is_some() {
        if let Some(ref target) = target {
            if list {
                return list_test_classes_workspace(&project, target, filter.as_deref());
            }
            scripts::run_script(&cfg, "pretest", &project)?;
            let result = test_workspace(&project, target, watch, filter, verbose, fail_fast, &test_mode, parallel);
            scripts::run_script(&cfg, "posttest", &project)?;
            return result;
        }
        // No target: test all modules
        scripts::run_script(&cfg, "pretest", &project)?;
        let result = test_all_workspace_modules(&project, &cfg, filter, verbose, fail_fast, keep_going, &test_mode, parallel);
        scripts::run_script(&cfg, "posttest", &project)?;
        return result;
    }

    // List test classes only
    if list {
        let test_dir = config::test_dir_for(&project, &cfg);
        return list_test_classes(&test_dir, filter.as_deref());
    }

    // Run pretest script
    scripts::run_script(&cfg, "pretest", &project)?;

    run_tests(&project, &cfg, filter.as_deref(), verbose, fail_fast, timeout, coverage,
              &test_mode, tag.as_deref(), exclude_tag.as_deref(), report.as_deref(), parallel)?;

    if watch {
        let src_dir = config::source_dir(&project);
        let test_dir = config::test_dir(&project);

        let mut watch_dirs = vec![];
        if src_dir.exists() {
            watch_dirs.push(src_dir);
        }
        if test_dir.exists() {
            watch_dirs.push(test_dir);
        }

        if watch_dirs.is_empty() {
            println!("  {} No source directories to watch", style("!").yellow());
            return Ok(());
        }

        let extensions = vec![".java".to_string()];
        let watcher = FileWatcher::new(&watch_dirs, extensions)?;

        // Track failed tests for 'f' key
        let mut failed_tests: Vec<String> = Vec::new();
        let mut current_filter = filter.clone();

        // Spawn a thread to read keyboard input
        let (key_tx, key_rx) = std::sync::mpsc::channel::<char>();
        let is_tty = console::Term::stdout().is_term();
        if is_tty {
            std::thread::spawn(move || {
                let term = console::Term::stdout();
                loop {
                    if let Ok(ch) = term.read_char() {
                        if key_tx.send(ch).is_err() {
                            break;
                        }
                    }
                }
            });
        }

        print_watch_prompt();

        loop {
            // Check for keyboard input (non-blocking)
            if let Ok(ch) = key_rx.try_recv() {
                match ch {
                    'q' | 'Q' => break,
                    'a' | 'A' => {
                        println!("  {} running all tests...", style("").green());
                        current_filter = None;
                        match run_tests(&project, &cfg, None, verbose, fail_fast, timeout, coverage, &test_mode, tag.as_deref(), exclude_tag.as_deref(), None, parallel) {
                            Ok(()) => { failed_tests.clear(); }
                            Err(e) => {
                                collect_failed_from_error(&e, &mut failed_tests);
                                eprintln!("  {} {}", style("").red(), e);
                            }
                        }
                        print_watch_prompt();
                    }
                    'f' | 'F' => {
                        if failed_tests.is_empty() {
                            println!("  {} No failed tests to re-run", style("!").yellow());
                        } else {
                            println!("  {} re-running {} failed test(s)...", style("").green(), failed_tests.len());
                            // Run with each failed test as filter
                            for class in &failed_tests {
                                let _ = run_tests(&project, &cfg, Some(class), verbose, fail_fast, timeout, coverage, &test_mode, tag.as_deref(), exclude_tag.as_deref(), None, parallel);
                            }
                        }
                        print_watch_prompt();
                    }
                    'p' | 'P' => {
                        if is_tty {
                            let input: String = dialoguer::Input::new()
                                .with_prompt("  Filter pattern")
                                .allow_empty(true)
                                .interact_text()
                                .unwrap_or_default();
                            current_filter = if input.is_empty() { None } else { Some(input) };
                            println!("  {} running with filter: {}", style("").green(),
                                current_filter.as_deref().unwrap_or("(none)"));
                            match run_tests(&project, &cfg, current_filter.as_deref(), verbose, fail_fast, timeout, coverage, &test_mode, tag.as_deref(), exclude_tag.as_deref(), None, parallel) {
                                Ok(()) => {}
                                Err(e) => {
                                    collect_failed_from_error(&e, &mut failed_tests);
                                    eprintln!("  {} {}", style("").red(), e);
                                }
                            }
                        }
                        print_watch_prompt();
                    }
                    _ => {}
                }
                continue;
            }

            // Check for file changes
            let changed = watcher.wait_for_changes(Duration::from_millis(100));
            if changed.is_empty() {
                continue;
            }

            for path in &changed {
                if let Some(name) = path.file_name() {
                    println!(
                        "  {} Changed: {}",
                        style("").green(),
                        style(name.to_string_lossy()).yellow()
                    );
                }
            }

            // Smart affected test detection (spec 06-testing P2)
            let src_dir = config::source_dir(&project);
            let test_dir = config::test_dir(&project);
            let src_root = src_dir.clone();
            let test_root = test_dir.clone();

            let effective_filter = if current_filter.is_some() {
                // User set explicit filter — respect it
                current_filter.clone()
            } else {
                // Try smart detection
                match find_affected_tests(&changed, &src_root, &test_root, &test_dir) {
                    Some(affected) => {
                        println!(
                            "  {} {} affected test(s): {}",
                            style("·").dim(),
                            affected.len(),
                            affected.iter().map(|c| c.rsplit('.').next().unwrap_or(c)).collect::<Vec<_>>().join(", ")
                        );
                        // Join as filter — JUnit accepts class name patterns
                        Some(affected.join("|"))
                    }
                    None => {
                        // Can't determine — run all
                        None
                    }
                }
            };

            match run_tests(&project, &cfg, effective_filter.as_deref(), verbose, fail_fast, timeout, coverage, &test_mode, tag.as_deref(), exclude_tag.as_deref(), None, parallel) {
                Ok(()) => { failed_tests.clear(); }
                Err(e) => {
                    collect_failed_from_error(&e, &mut failed_tests);
                    eprintln!("  {} {}", style("").red(), e);
                }
            }
            print_watch_prompt();
        }
    }

    // Run posttest script
    scripts::run_script(&cfg, "posttest", &project)?;

    Ok(())
}

fn print_watch_prompt() {
    println!();
    println!(
        "  Press: {} run all  {} run failed  {} filter  {} quit",
        style("a").cyan().bold(),
        style("f").cyan().bold(),
        style("p").cyan().bold(),
        style("q").cyan().bold(),
    );
    println!();
}

fn collect_failed_from_error(e: &anyhow::Error, failed: &mut Vec<String>) {
    // Parse error message for failed test class names
    // Format: "Test failed: com.example.FooTest. Stopping (--fail-fast)"
    // or: "N test class(es) failed"
    let msg = e.to_string();
    if let Some(rest) = msg.strip_prefix("Test failed: ") {
        if let Some(dot_pos) = rest.find(". ") {
            let name = &rest[..dot_pos];
            if !failed.contains(&name.to_string()) {
                failed.push(name.to_string());
            }
        }
    }
}

fn run_tests(
    project: &std::path::Path,
    cfg: &config::schema::YmConfig,
    filter: Option<&str>,
    verbose: bool,
    fail_fast: bool,
    timeout: Option<u64>,
    coverage: bool,
    test_mode: &TestMode,
    tag: Option<&str>,
    exclude_tag: Option<&str>,
    report: Option<&str>,
    parallel: bool,
) -> Result<()> {
    // Resolve all deps first to populate cache, then use scope-filtered subsets
    let _all_jars = super::build::resolve_deps(project, cfg)?;

    // Main compilation classpath: compile + provided
    let compile_jars = super::build::resolve_deps_with_scopes(project, cfg, &["compile", "provided"])?;
    // Test compilation classpath: compile + provided + test
    let test_compile_jars = super::build::resolve_deps_with_scopes(project, cfg, &["compile", "provided", "test"])?;
    // Test runtime classpath: compile + runtime + provided + test
    let test_run_jars = super::build::resolve_deps_with_scopes(project, cfg, &["compile", "runtime", "provided", "test"])?;

    // Compile main sources → out/classes
    let src_dir = config::source_dir_for(project, cfg);
    let test_dir = config::test_dir_for(project, cfg);
    let out_dir = config::output_classes_dir(project);
    let test_out_dir = config::output_test_classes_dir(project);

    // Step 1: compile main source (compile + provided scope)
    let main_compile_cfg = crate::compiler::CompileConfig {
        source_dirs: vec![src_dir],
        output_dir: out_dir.clone(),
        classpath: compile_jars,
        java_version: cfg.target.clone(),
        encoding: cfg.compiler.as_ref().and_then(|c| c.encoding.clone()),
        annotation_processors: vec![],
        lint: vec![],
        extra_args: vec![],
    };

    let cache = config::cache_dir(project);
    let result = crate::compiler::incremental::incremental_compile(&main_compile_cfg, &cache, None)?;
    if !result.success {
        eprint!("{}", crate::compiler::colorize_errors(&result.errors));
        bail!("Main compilation failed");
    }

    // Step 2: compile test source → out/test-classes (compile + provided + test scope)
    if test_dir.exists() {
        let mut test_classpath = vec![out_dir.clone()];
        test_classpath.extend(test_compile_jars);

        let test_compile_cfg = crate::compiler::CompileConfig {
            source_dirs: vec![test_dir.clone()],
            output_dir: test_out_dir.clone(),
            classpath: test_classpath,
            java_version: cfg.target.clone(),
            encoding: cfg.compiler.as_ref().and_then(|c| c.encoding.clone()),
            annotation_processors: vec![],
            lint: vec![],
            extra_args: vec![],
        };

        let result = crate::compiler::incremental::incremental_compile(&test_compile_cfg, &cache, None)?;
        if !result.success {
            eprint!("{}", crate::compiler::colorize_errors(&result.errors));
            bail!("Test compilation failed");
        }
    }

    // Copy main resources (src/main/resources → out/classes)
    let custom_res_ext = cfg.compiler.as_ref().and_then(|c| c.resource_extensions.as_ref());
    let res_exclude = cfg.compiler.as_ref().and_then(|c| c.resource_exclude.as_ref());
    let main_resources = project.join("src").join("main").join("resources");
    if main_resources.exists() {
        crate::resources::copy_resources_with_extensions(&main_resources, &out_dir, custom_res_ext.map(|v| v.as_slice()), res_exclude.map(|v| v.as_slice()))?;
    }

    // Copy test resources (src/test/resources → out/test-classes)
    let test_resources = project.join("src").join("test").join("resources");
    if test_resources.exists() {
        crate::resources::copy_resources_with_extensions(&test_resources, &test_out_dir, custom_res_ext.map(|v| v.as_slice()), res_exclude.map(|v| v.as_slice()))?;
    }

    // Find test classes based on mode
    let mut test_classes = find_test_classes_filtered(&test_dir, test_mode)?;

    if test_classes.is_empty() {
        println!("  {} No test classes found", style("!").yellow());
        return Ok(());
    }

    // Apply filter
    if let Some(pattern) = filter {
        test_classes.retain(|c| c.contains(pattern));
        if test_classes.is_empty() {
            println!(
                "  {} No test classes match filter '{}'",
                style("!").yellow(),
                pattern
            );
            return Ok(());
        }
    }

    println!(
        "  {} running {} test class(es)...",
        style("").green(),
        test_classes.len()
    );

    let sep = if cfg!(windows) { ";" } else { ":" };
    let mut classpath = vec![
        out_dir.to_string_lossy().to_string(),
        test_out_dir.to_string_lossy().to_string(),
    ];
    classpath.extend(test_run_jars.iter().map(|p| p.to_string_lossy().to_string()));
    let cp = classpath.join(sep);

    // Ensure JUnit Platform Console standalone launcher is available
    let junit_launcher = ensure_junit_launcher(&test_run_jars, project);

    // Set up JaCoCo coverage if requested
    let jacoco_version = cfg.compiler.as_ref()
        .and_then(|c| c.jacoco_version.as_deref())
        .unwrap_or("0.8.12");
    let jacoco_agent = if coverage {
        find_jacoco_agent(&test_run_jars, project, jacoco_version)
    } else {
        None
    };

    if let Some(launcher) = junit_launcher {
        // Use JVM @argfile to avoid OS command-line length limits (E2BIG).
        // All arguments are written to a temp file, then passed as `java @file`.
        // This is the same approach used by IntelliJ IDEA and Gradle.
        let mut args: Vec<String> = Vec::new();

        if let Some(ref agent_jar) = jacoco_agent {
            let report_dir = project.join("out").join("coverage");
            std::fs::create_dir_all(&report_dir).ok();
            let exec_file = report_dir.join("jacoco.exec");
            args.push(format!(
                "-javaagent:{}=destfile={}",
                agent_jar.display(),
                exec_file.display()
            ));
        }

        args.push("-jar".into());
        args.push(launcher.to_string_lossy().into());
        args.push("--class-path".into());
        args.push(cp.clone());

        if verbose {
            args.push("--details".into());
            args.push("verbose".into());
        }

        if fail_fast {
            args.push("--fail-if-no-tests".into());
            args.push("-c".into());
            args.push("junit.jupiter.execution.order.random.seed=0".into());
        }

        if let Some(secs) = timeout {
            args.push("-c".into());
            args.push(format!("junit.jupiter.execution.timeout.default={}s", secs));
        }

        if parallel {
            args.push("-c".into());
            args.push("junit.jupiter.execution.parallel.enabled=true".into());
            args.push("-c".into());
            args.push("junit.jupiter.execution.parallel.mode.default=concurrent".into());
            match test_mode {
                TestMode::Integration => {}
                _ => {
                    args.push("-c".into());
                    args.push("junit.jupiter.execution.parallel.mode.classes.default=concurrent".into());
                }
            }
        }

        if let Some(pattern) = filter {
            if pattern.contains('#') {
                args.push("--select-method".into());
                args.push(pattern.to_string());
            } else {
                args.push("--include-classname".into());
                args.push(format!(".*{}.*", pattern));
            }
        }

        match test_mode {
            TestMode::Unit => {
                args.push("--exclude-classname".into());
                args.push(".*IT$".into());
                args.push("--exclude-classname".into());
                args.push(".*IntegrationTest$".into());
            }
            TestMode::Integration => {
                args.push("--include-classname".into());
                args.push(".*IT$|.*IntegrationTest$".into());
            }
            TestMode::All => {}
        }

        if let Some(t) = tag {
            args.push("--include-tag".into());
            args.push(t.to_string());
        }
        if let Some(t) = exclude_tag {
            args.push("--exclude-tag".into());
            args.push(t.to_string());
        }

        if let Some(report_type) = report {
            let reports_dir = project.join("out").join("test-reports");
            std::fs::create_dir_all(&reports_dir).ok();
            match report_type {
                "junit-xml" | "xml" | "html" => {
                    args.push("--reports-dir".into());
                    args.push(reports_dir.to_string_lossy().into());
                }
                _ => {
                    eprintln!(
                        "  {} Unknown report type '{}', supported: junit-xml, html",
                        console::style("!").yellow(),
                        report_type
                    );
                }
            }
        }

        args.push("--scan-class-path".into());
        args.push(test_out_dir.to_string_lossy().into());

        // Write @argfile
        let argfile = project.join("out").join(".ym-test-args.txt");
        std::fs::create_dir_all(argfile.parent().unwrap()).ok();
        std::fs::write(&argfile, args.join("\n"))?;

        let status = Command::new("java")
            .arg(format!("@{}", argfile.display()))
            .status()?;

        // Print report location if generated
        if let Some(report_type) = report {
            let reports_dir = project.join("out").join("test-reports");
            if reports_dir.exists() {
                match report_type {
                    "html" => {
                        let html_file = reports_dir.join("index.html");
                        generate_test_html_report(&reports_dir, &html_file);
                        if html_file.exists() {
                            println!(
                                "  {} Test report: {}",
                                console::style("").green(),
                                html_file.display()
                            );
                        }
                    }
                    "junit-xml" | "xml" => {
                        println!(
                            "  {} Test reports: {}",
                            console::style("").green(),
                            reports_dir.display()
                        );
                    }
                    _ => {}
                }
            }
        }

        if !status.success() {
            bail!("Tests failed");
        }
    } else {
        // Fallback: run test classes directly via @argfile
        let mut failures = 0;
        for class in &test_classes {
            println!("  running {}...", style(class).cyan());
            let fb_argfile = project.join("out").join(".ym-test-fb-args.txt");
            let fb_args = vec![
                "-cp".to_string(),
                cp.clone(),
                "org.junit.platform.console.ConsoleLauncher".to_string(),
                "--select-class".to_string(),
                class.clone(),
            ];
            std::fs::write(&fb_argfile, fb_args.join("\n")).ok();
            let status = Command::new("java")
                .arg(format!("@{}", fb_argfile.display()))
                .status();

            match status {
                Ok(s) if s.success() => {
                    println!("  {} {}", style("").green(), class);
                }
                _ => {
                    failures += 1;
                    println!(
                        "  {} {} (JUnit Platform not on classpath?)",
                        style("").red(),
                        class
                    );
                    if fail_fast {
                        bail!("Test failed: {}. Stopping (--fail-fast)", class);
                    }
                }
            }
        }
        if failures > 0 {
            bail!("{} test class(es) failed", failures);
        }
    }

    if jacoco_agent.is_some() {
        let exec_file = project.join("out").join("coverage").join("jacoco.exec");
        if exec_file.exists() {
            let size = std::fs::metadata(&exec_file).map(|m| m.len()).unwrap_or(0);
            println!(
                "  {} Coverage data: {} ({:.1} KB)",
                style("").green(),
                exec_file.display(),
                size as f64 / 1024.0
            );

            // Generate HTML report via JaCoCo CLI
            generate_jacoco_html_report(project, cfg, &exec_file, &out_dir);
        }
    }

    Ok(())
}

/// Ensure junit-platform-console-standalone is available.
/// Detects the platform version from existing JARs and auto-downloads if needed.
fn ensure_junit_launcher(
    jars: &[std::path::PathBuf],
    project: &std::path::Path,
) -> Option<std::path::PathBuf> {
    // Already in classpath?
    for jar in jars {
        let name = jar.to_string_lossy();
        if name.contains("junit-platform-console-standalone") {
            return Some(jar.clone());
        }
    }

    // Detect JUnit Platform version from existing deps (e.g. junit-platform-engine-1.13.0-M3.jar)
    let platform_version = jars.iter().find_map(|jar| {
        let stem = jar.file_stem()?.to_string_lossy();
        stem.strip_prefix("junit-platform-engine-")
            .or_else(|| stem.strip_prefix("junit-platform-commons-"))
            .map(|v| v.to_string())
    });

    let version = platform_version?;

    // Check cache
    let cache = config::cache_dir(project);
    let tools_dir = cache.join("tools");
    let launcher_jar = tools_dir.join(format!(
        "junit-platform-console-standalone-{}.jar",
        version
    ));
    if launcher_jar.exists() {
        return Some(launcher_jar);
    }

    // Download
    println!(
        "  {} downloading junit-platform-console-standalone {}...",
        style("").green(),
        version
    );

    std::fs::create_dir_all(&tools_dir).ok()?;
    let url = format!(
        "https://repo1.maven.org/maven2/org/junit/platform/junit-platform-console-standalone/{}/junit-platform-console-standalone-{}.jar",
        version, version
    );

    let client = reqwest::blocking::Client::builder()
        .user_agent(concat!("ym/", env!("CARGO_PKG_VERSION")))
        .timeout(std::time::Duration::from_secs(60))
        .build()
        .ok()?;

    let response = client.get(&url).send().ok()?;
    if !response.status().is_success() {
        println!(
            "  {} Failed to download JUnit launcher (HTTP {})",
            style("!").yellow(),
            response.status()
        );
        return None;
    }

    let bytes = response.bytes().ok()?;
    std::fs::write(&launcher_jar, &bytes).ok()?;

    println!(
        "  {} Downloaded junit-platform-console-standalone {}",
        style("").green(),
        version
    );
    Some(launcher_jar)
}

/// Find JaCoCo agent JAR from deps or download it.
fn find_jacoco_agent(
    jars: &[std::path::PathBuf],
    project: &std::path::Path,
    version: &str,
) -> Option<std::path::PathBuf> {
    // Check if jacocoagent is already in deps
    for jar in jars {
        let name = jar.to_string_lossy();
        if name.contains("jacoco") && name.contains("agent") {
            return Some(jar.clone());
        }
    }

    // Check cache (versioned filename to handle version changes)
    let cache = config::cache_dir(project);
    let tools_dir = cache.join("tools");
    let agent_jar = tools_dir.join(format!("jacocoagent-{}.jar", version));
    if agent_jar.exists() {
        return Some(agent_jar);
    }

    // Download JaCoCo
    println!(
        "  {} downloading JaCoCo agent {}...",
        style("").green(),
        version
    );

    std::fs::create_dir_all(&tools_dir).ok()?;
    let url = format!(
        "https://repo1.maven.org/maven2/org/jacoco/org.jacoco.agent/{}/org.jacoco.agent-{}-runtime.jar",
        version, version
    );

    let client = reqwest::blocking::Client::builder()
        .user_agent(concat!("ym/", env!("CARGO_PKG_VERSION")))
        .timeout(std::time::Duration::from_secs(60))
        .build()
        .ok()?;

    let response = client.get(&url).send().ok()?;
    if !response.status().is_success() {
        println!(
            "  {} Failed to download JaCoCo (HTTP {})",
            style("!").yellow(),
            response.status()
        );
        return None;
    }

    let bytes = response.bytes().ok()?;
    std::fs::write(&agent_jar, &bytes).ok()?;

    println!(
        "  {} Downloaded JaCoCo {}",
        style("").green(),
        version
    );
    Some(agent_jar)
}

/// Generate HTML coverage report via JaCoCo CLI.
fn generate_jacoco_html_report(
    project: &std::path::Path,
    cfg: &config::schema::YmConfig,
    exec_file: &std::path::Path,
    classes_dir: &std::path::Path,
) {
    let version = cfg.compiler.as_ref()
        .and_then(|c| c.jacoco_version.as_deref())
        .unwrap_or("0.8.12");

    let cache = config::cache_dir(project);
    let tools_dir = cache.join("tools");
    let cli_jar = tools_dir.join(format!("jacococli-{}.jar", version));

    // Download JaCoCo CLI if not cached
    if !cli_jar.exists() {
        let url = format!(
            "https://repo1.maven.org/maven2/org/jacoco/org.jacoco.cli/{}/org.jacoco.cli-{}-nodeps.jar",
            version, version
        );
        let _ = std::fs::create_dir_all(&tools_dir);
        if let Ok(client) = reqwest::blocking::Client::builder()
            .user_agent(concat!("ym/", env!("CARGO_PKG_VERSION")))
            .timeout(std::time::Duration::from_secs(60))
            .build()
        {
            if let Ok(resp) = client.get(&url).send() {
                if resp.status().is_success() {
                    if let Ok(bytes) = resp.bytes() {
                        let _ = std::fs::write(&cli_jar, &bytes);
                    }
                }
            }
        }
    }

    if !cli_jar.exists() {
        println!(
            "  {} Use JaCoCo CLI or IDE to generate HTML report",
            style("").dim()
        );
        return;
    }

    let html_dir = project.join("out").join("coverage").join("html");
    let _ = std::fs::create_dir_all(&html_dir);

    let src_dir = config::source_dir_for(project, cfg);
    let status = Command::new("java")
        .arg("-jar").arg(&cli_jar)
        .arg("report").arg(exec_file)
        .arg("--classfiles").arg(classes_dir)
        .arg("--sourcefiles").arg(&src_dir)
        .arg("--html").arg(&html_dir)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();

    match status {
        Ok(s) if s.success() => {
            println!(
                "  {} Coverage report: {}",
                style("").green(),
                html_dir.join("index.html").display()
            );
        }
        _ => {
            println!(
                "  {} Failed to generate HTML report, use JaCoCo CLI manually",
                style("!").yellow()
            );
        }
    }
}

fn test_workspace(
    root: &std::path::Path,
    target: &str,
    watch: bool,
    filter: Option<String>,
    verbose: bool,
    fail_fast: bool,
    test_mode: &TestMode,
    parallel: bool,
) -> Result<()> {
    use crate::workspace::graph::WorkspaceGraph;

    // Build the target and its dependencies first
    super::build::compile_only(Some(target.to_string()))?;

    let ws = WorkspaceGraph::build(root)?;
    let packages = ws.transitive_closure(target)?;
    let target_pkg = ws.get_package(target).unwrap();

    // Build classpath from all packages in the closure
    let mut classpath_jars: Vec<std::path::PathBuf> = Vec::new();
    for pkg_name in &packages {
        let pkg = ws.get_package(pkg_name).unwrap();
        classpath_jars.push(config::output_classes_dir(&pkg.path));
        let jars = super::build::resolve_deps(&pkg.path, &pkg.config)?;
        classpath_jars.extend(jars);
    }

    // Also resolve all Maven dependencies (including test-scoped) for the target
    {
        let all_deps = target_pkg.config.maven_dependencies();
        let cache = config::maven_cache_dir(&target_pkg.path);
        let mut resolved = config::load_resolved_cache(&target_pkg.path)?;
        let extra_jars = crate::workspace::resolver::resolve_and_download(&all_deps, &cache, &mut resolved)?;
        config::save_resolved_cache(&target_pkg.path, &resolved)?;
        classpath_jars.extend(extra_jars);
    }

    // Compile test sources for the target module → out/test-classes
    let test_dir = config::test_dir(&target_pkg.path);
    let out_dir = config::output_classes_dir(&target_pkg.path);
    let test_out_dir = config::output_test_classes_dir(&target_pkg.path);

    if test_dir.exists() {
        let mut test_cp = vec![out_dir.clone()];
        test_cp.extend(classpath_jars.clone());

        let compile_cfg = crate::compiler::CompileConfig {
            source_dirs: vec![test_dir.clone()],
            output_dir: test_out_dir.clone(),
            classpath: test_cp,
            java_version: target_pkg.config.target.clone(),
            encoding: target_pkg
                .config
                .compiler
                .as_ref()
                .and_then(|c| c.encoding.clone()),
            annotation_processors: vec![],
            lint: vec![],
            extra_args: vec![],
        };

        let ws_cache = config::cache_dir(&target_pkg.path);
        let result = crate::compiler::incremental::incremental_compile(&compile_cfg, &ws_cache, None)?;
        if !result.success {
            eprint!("{}", crate::compiler::colorize_errors(&result.errors));
            bail!("Test compilation failed");
        }
    }

    // Find and run test classes
    let mut test_classes = find_test_classes_filtered(&test_dir, test_mode)?;
    if test_classes.is_empty() {
        println!("  {} No test classes found in {}", style("!").yellow(), target);
        return Ok(());
    }

    if let Some(ref pattern) = filter {
        test_classes.retain(|c| c.contains(pattern));
    }

    println!(
        "  {} running {} test class(es) in {}...",
        style("").green(),
        test_classes.len(),
        style(target).bold()
    );

    // Add test-classes to classpath
    classpath_jars.insert(0, test_out_dir);

    let sep = if cfg!(windows) { ";" } else { ":" };
    let cp = classpath_jars
        .iter()
        .map(|p| p.to_string_lossy().to_string())
        .collect::<Vec<_>>()
        .join(sep);

    // Ensure JUnit Platform Console standalone launcher is available
    // Ensure JUnit Platform Console standalone launcher is available
    let junit_launcher = ensure_junit_launcher(&classpath_jars, &target_pkg.path);
    if let Some(launcher) = junit_launcher {
        let mut args: Vec<String> = Vec::new();
        args.push("-jar".into());
        args.push(launcher.to_string_lossy().into());
        // JUnit 6+ requires 'execute' subcommand
        let launcher_name = launcher.file_name().unwrap_or_default().to_string_lossy();
        if launcher_name.contains("-6.") || launcher_name.contains("-7.") || launcher_name.contains("-8.") || launcher_name.contains("-9.") {
            args.push("execute".into());
        }
        args.push("--class-path".into());
        args.push(cp.clone());
        if verbose {
            args.push("--details".into());
            args.push("verbose".into());
        }
        if fail_fast {
            args.push("--fail-if-no-tests".into());
        }
        if parallel {
            args.push("-c".into());
            args.push("junit.jupiter.execution.parallel.enabled=true".into());
            args.push("-c".into());
            args.push("junit.jupiter.execution.parallel.mode.default=concurrent".into());
            args.push("-c".into());
            args.push("junit.jupiter.execution.parallel.mode.classes.default=concurrent".into());
        }
        if let Some(ref pattern) = filter {
            args.push("--include-classname".into());
            args.push(format!(".*{}.*", pattern));
        }
        let ws_test_out = config::output_test_classes_dir(&target_pkg.path);
        args.push("--scan-class-path".into());
        args.push(ws_test_out.to_string_lossy().into());

        let argfile = target_pkg.path.join("out").join(".ym-test-args.txt");
        std::fs::create_dir_all(argfile.parent().unwrap()).ok();
        std::fs::write(&argfile, args.join("\n"))?;

        let status = std::process::Command::new("java")
            .arg(format!("@{}", argfile.display()))
            .status()?;
        if !status.success() {
            bail!("Tests failed");
        }
    } else {
        for class in &test_classes {
            println!("  running {}...", style(class).cyan());
            let fb_argfile = target_pkg.path.join("out").join(".ym-test-fb-args.txt");
            let fb_args = vec![
                "-cp".to_string(),
                cp.clone(),
                class.clone(),
            ];
            std::fs::write(&fb_argfile, fb_args.join("\n")).ok();
            let status = std::process::Command::new("java")
                .arg(format!("@{}", fb_argfile.display()))
                .status();
            match status {
                Ok(s) if s.success() => println!("  {} {}", style("").green(), class),
                _ => {
                    println!("  {} {}", style("").red(), class);
                    if fail_fast {
                        bail!("Test failed: {}. Stopping (--fail-fast)", class);
                    }
                }
            }
        }
    }

    if watch {
        let mut watch_dirs = vec![];
        let src_dir = config::source_dir(&target_pkg.path);
        if src_dir.exists() {
            watch_dirs.push(src_dir);
        }
        if test_dir.exists() {
            watch_dirs.push(test_dir);
        }
        let watcher = FileWatcher::new(&watch_dirs, vec![".java".to_string()])?;
        println!();
        println!("  Watching for changes...");
        loop {
            let changed = watcher.wait_for_changes(Duration::from_millis(100));
            if changed.is_empty() {
                continue;
            }
            for path in &changed {
                if let Some(name) = path.file_name() {
                    println!("  {} Changed: {}", style("").green(), style(name.to_string_lossy()).yellow());
                }
            }
            if let Err(e) = test_workspace(root, target, false, filter.clone(), verbose, fail_fast, &TestMode::Unit, parallel) {
                eprintln!("  {} {}", style("").red(), e);
            }
        }
    }

    Ok(())
}

/// List test classes without running them
fn list_test_classes(test_dir: &std::path::Path, filter: Option<&str>) -> Result<()> {
    let mut classes = find_test_classes(test_dir)?;

    if let Some(pattern) = filter {
        classes.retain(|c| c.contains(pattern));
    }

    println!();
    if classes.is_empty() {
        println!("  {} No test classes found", style("!").yellow());
    } else {
        println!("  {} test class(es):", classes.len());
        println!();
        for class in &classes {
            println!("  {} {}", style("·").dim(), style(class).cyan());
        }
    }
    println!();

    Ok(())
}

/// Test all modules in the workspace (no target specified).
fn test_all_workspace_modules(
    root: &std::path::Path,
    _cfg: &config::schema::YmConfig,
    filter: Option<String>,
    verbose: bool,
    fail_fast: bool,
    keep_going: bool,
    test_mode: &TestMode,
    parallel: bool,
) -> Result<()> {
    use crate::workspace::graph::WorkspaceGraph;

    let ws = WorkspaceGraph::build(root)?;
    let mut packages = ws.all_packages();
    packages.sort();

    // Build all modules first
    super::build::compile_only(None)?;

    let mut failures = Vec::new();

    for pkg_name in &packages {
        let pkg = ws.get_package(pkg_name).unwrap();
        let test_dir = config::test_dir(&pkg.path);
        if !test_dir.exists() {
            continue;
        }
        let classes = find_test_classes_filtered(&test_dir, test_mode)?;
        if classes.is_empty() {
            continue;
        }

        println!(
            "\n  {} Testing {}...",
            style("").green(),
            style(pkg_name).cyan()
        );

        match test_workspace(root, pkg_name, false, filter.clone(), verbose, fail_fast, test_mode, parallel) {
            Ok(()) => {
                println!(
                    "  {} {} tests passed",
                    style("").green(),
                    pkg_name
                );
            }
            Err(e) => {
                eprintln!(
                    "  {} {} tests failed: {}",
                    style("").red(),
                    pkg_name,
                    e
                );
                if !keep_going {
                    return Err(e);
                }
                failures.push(pkg_name.clone());
            }
        }
    }

    if !failures.is_empty() {
        bail!(
            "{} module(s) had test failures: {}",
            failures.len(),
            failures.join(", ")
        );
    }

    Ok(())
}

/// List test classes in a workspace module
fn list_test_classes_workspace(root: &std::path::Path, target: &str, filter: Option<&str>) -> Result<()> {
    let ws = crate::workspace::graph::WorkspaceGraph::build(root)?;
    let pkg = ws.get_package(target)
        .ok_or_else(|| anyhow::anyhow!("Package '{}' not found", target))?;
    let test_dir = config::test_dir(&pkg.path);
    list_test_classes(&test_dir, filter)
}

fn find_test_classes(test_dir: &std::path::Path) -> Result<Vec<String>> {
    find_test_classes_filtered(test_dir, &TestMode::Unit)
}

fn find_test_classes_filtered(test_dir: &std::path::Path, mode: &TestMode) -> Result<Vec<String>> {
    let mut classes = Vec::new();

    if !test_dir.exists() {
        return Ok(classes);
    }

    for entry in walkdir::WalkDir::new(test_dir) {
        let entry = entry?;
        if entry.path().extension().and_then(|e| e.to_str()) != Some("java") {
            continue;
        }

        let file_stem = entry
            .path()
            .file_stem()
            .unwrap_or_default()
            .to_string_lossy()
            .to_string();

        // Filename-based test discovery
        let is_unit = file_stem.ends_with("Test")
            || file_stem.starts_with("Test")
            || file_stem.ends_with("Tests");
        let is_integration =
            file_stem.ends_with("IT") || file_stem.ends_with("IntegrationTest");

        let matches_mode = match mode {
            TestMode::Unit => is_unit && !is_integration,
            TestMode::Integration => is_integration,
            TestMode::All => is_unit || is_integration,
        };

        if !matches_mode {
            continue;
        }

        // Verify file contains test annotations
        let content = std::fs::read_to_string(entry.path())?;
        if !content.contains("@Test") && !content.contains("@org.junit") {
            continue;
        }

        // Exclude abstract classes
        if content.contains("abstract class") {
            continue;
        }

        let rel = entry.path().strip_prefix(test_dir)?;
        let class = rel
            .to_string_lossy()
            .replace(['/', '\\'], ".")
            .trim_end_matches(".java")
            .to_string();
        classes.push(class);
    }

    Ok(classes)
}

/// Generate an HTML test report from JUnit XML files in the reports directory.
fn generate_test_html_report(xml_dir: &std::path::Path, html_file: &std::path::Path) {
    use std::fs;

    let mut suites: Vec<(String, usize, usize, usize, f64)> = Vec::new(); // name, tests, failures, errors, time
    let mut total_tests = 0usize;
    let mut total_failures = 0usize;
    let mut total_errors = 0usize;
    let mut total_time = 0.0f64;

    // Parse all TEST-*.xml files
    let entries = match fs::read_dir(xml_dir) {
        Ok(e) => e,
        Err(_) => return,
    };

    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("xml") {
            continue;
        }
        let content = match fs::read_to_string(&path) {
            Ok(c) => c,
            Err(_) => continue,
        };

        // Simple XML parsing for testsuite attributes
        if let Some(ts_start) = content.find("<testsuite") {
            let ts_end = content[ts_start..].find('>').unwrap_or(0) + ts_start;
            let tag = &content[ts_start..=ts_end];

            let name = extract_attr(tag, "name").unwrap_or_else(|| "unknown".to_string());
            let tests: usize = extract_attr(tag, "tests").and_then(|v| v.parse().ok()).unwrap_or(0);
            let failures: usize = extract_attr(tag, "failures").and_then(|v| v.parse().ok()).unwrap_or(0);
            let errors: usize = extract_attr(tag, "errors").and_then(|v| v.parse().ok()).unwrap_or(0);
            let time: f64 = extract_attr(tag, "time").and_then(|v| v.parse().ok()).unwrap_or(0.0);

            total_tests += tests;
            total_failures += failures;
            total_errors += errors;
            total_time += time;
            suites.push((name, tests, failures, errors, time));
        }
    }

    suites.sort_by(|a, b| a.0.cmp(&b.0));

    let passed = total_tests.saturating_sub(total_failures + total_errors);
    let status_color = if total_failures + total_errors > 0 { "#dc3545" } else { "#28a745" };

    let mut rows = String::new();
    for (name, tests, failures, errors, time) in &suites {
        let suite_passed = tests.saturating_sub(failures + errors);
        let row_class = if *failures + *errors > 0 { " class=\"failed\"" } else { "" };
        rows.push_str(&format!(
            "    <tr{}><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{:.3}s</td></tr>\n",
            row_class, name, tests, suite_passed, failures, errors, time
        ));
    }

    let html = format!(
        r#"<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test Report</title>
<style>
  body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; margin: 2em; background: #f8f9fa; }}
  h1 {{ color: #333; }}
  .summary {{ display: flex; gap: 1.5em; margin: 1em 0; }}
  .stat {{ padding: 1em 1.5em; border-radius: 8px; background: white; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }}
  .stat .value {{ font-size: 2em; font-weight: bold; }}
  .stat .label {{ color: #666; font-size: 0.9em; }}
  table {{ border-collapse: collapse; width: 100%; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }}
  th {{ background: #343a40; color: white; text-align: left; padding: 0.75em 1em; }}
  td {{ padding: 0.6em 1em; border-bottom: 1px solid #eee; }}
  tr:hover {{ background: #f1f3f5; }}
  tr.failed td {{ background: #fff5f5; }}
  .status {{ font-size: 1.2em; font-weight: bold; color: {status_color}; }}
</style>
</head>
<body>
<h1>Test Report</h1>
<p class="status">{} passed, {} failed, {} errors — {:.3}s</p>
<div class="summary">
  <div class="stat"><div class="value">{}</div><div class="label">Total</div></div>
  <div class="stat"><div class="value" style="color:#28a745">{}</div><div class="label">Passed</div></div>
  <div class="stat"><div class="value" style="color:#dc3545">{}</div><div class="label">Failed</div></div>
  <div class="stat"><div class="value" style="color:#fd7e14">{}</div><div class="label">Errors</div></div>
</div>
<table>
  <thead><tr><th>Test Suite</th><th>Tests</th><th>Passed</th><th>Failures</th><th>Errors</th><th>Time</th></tr></thead>
  <tbody>
{}  </tbody>
</table>
<p style="color:#999;margin-top:2em;font-size:0.85em">Generated by ym test</p>
</body>
</html>
"#,
        passed, total_failures, total_errors, total_time,
        total_tests, passed, total_failures, total_errors,
        rows
    );

    let _ = fs::write(html_file, html);
}

fn extract_attr(tag: &str, name: &str) -> Option<String> {
    let pattern = format!("{}=\"", name);
    let start = tag.find(&pattern)? + pattern.len();
    let end = tag[start..].find('"')? + start;
    Some(tag[start..end].to_string())
}

// ── Affected test detection ─────────────────────────────────────────

/// Parse import statements from a Java source file.
/// Returns fully qualified class names (e.g., "com.example.UserService").
fn parse_imports(content: &str) -> Vec<String> {
    let mut imports = Vec::new();
    for line in content.lines() {
        let trimmed = line.trim();
        if let Some(rest) = trimmed.strip_prefix("import ") {
            // Skip static imports for now — they reference methods, not classes directly
            if rest.starts_with("static ") {
                // Extract class part: "static com.example.Foo.method;" → "com.example.Foo"
                let static_rest = rest.strip_prefix("static ").unwrap();
                if let Some(semi) = static_rest.strip_suffix(';') {
                    // Remove last segment (method/field name)
                    if let Some(dot_pos) = semi.rfind('.') {
                        imports.push(semi[..dot_pos].to_string());
                    }
                }
            } else if let Some(class_name) = rest.strip_suffix(';') {
                if !class_name.ends_with(".*") {
                    imports.push(class_name.to_string());
                }
            }
        }
        // Stop scanning after class/interface/enum declaration (imports are before that)
        if trimmed.starts_with("public ") || trimmed.starts_with("class ")
            || trimmed.starts_with("interface ") || trimmed.starts_with("enum ")
            || trimmed.starts_with("abstract ") || trimmed.starts_with("final class ")
        {
            break;
        }
    }
    imports
}

/// Convert a file path under a source root to a fully qualified class name.
/// e.g., src/test/java/com/example/UserServiceTest.java → "com.example.UserServiceTest"
fn path_to_class_name(file: &std::path::Path, source_root: &std::path::Path) -> Option<String> {
    let relative = file.strip_prefix(source_root).ok()?;
    let s = relative.to_string_lossy().replace(std::path::MAIN_SEPARATOR, ".");
    s.strip_suffix(".java").map(|s| s.to_string())
}

/// Build a reverse index: source class → list of test classes that import it.
/// Scans all .java files in the test directory.
fn build_import_index(
    test_dir: &std::path::Path,
    test_root: &std::path::Path,
) -> std::collections::HashMap<String, Vec<String>> {
    let mut index: std::collections::HashMap<String, Vec<String>> = std::collections::HashMap::new();

    if !test_dir.exists() {
        return index;
    }

    let walker = walkdir::WalkDir::new(test_dir)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path().extension().and_then(|ext| ext.to_str()) == Some("java")
        });

    for entry in walker {
        let path = entry.path();
        let test_class = match path_to_class_name(path, test_root) {
            Some(c) => c,
            None => continue,
        };

        let content = match std::fs::read_to_string(path) {
            Ok(c) => c,
            Err(_) => continue,
        };

        for imported in parse_imports(&content) {
            index
                .entry(imported)
                .or_default()
                .push(test_class.clone());
        }
    }

    index
}

/// Given changed file paths, determine which test classes to run.
/// Returns None if all tests should run (can't determine affected tests).
/// Returns Some(vec) with specific test class filters.
fn find_affected_tests(
    changed_files: &[std::path::PathBuf],
    src_root: &std::path::Path,
    test_root: &std::path::Path,
    test_dir: &std::path::Path,
) -> Option<Vec<String>> {
    let import_index = build_import_index(test_dir, test_root);
    let mut affected: Vec<String> = Vec::new();

    for file in changed_files {
        // Case 1: Test file changed → run that test directly
        if file.starts_with(test_dir) {
            if let Some(class_name) = path_to_class_name(file, test_root) {
                if !affected.contains(&class_name) {
                    affected.push(class_name);
                }
            }
            continue;
        }

        // Case 2: Main source changed → find tests that import this class
        if file.starts_with(src_root) {
            if let Some(class_name) = path_to_class_name(file, src_root) {
                if let Some(test_classes) = import_index.get(&class_name) {
                    for tc in test_classes {
                        if !affected.contains(tc) {
                            affected.push(tc.clone());
                        }
                    }
                } else {
                    // Changed class not imported by any test → run all (conservative)
                    return None;
                }
            }
        }
    }

    if affected.is_empty() {
        None
    } else {
        Some(affected)
    }
}

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

    #[test]
    fn test_parse_imports_basic() {
        let content = r#"
package com.example;

import com.example.UserService;
import com.example.OrderService;
import java.util.List;

public class UserServiceTest {
}
"#;
        let imports = parse_imports(content);
        assert_eq!(imports, vec![
            "com.example.UserService",
            "com.example.OrderService",
            "java.util.List",
        ]);
    }

    #[test]
    fn test_parse_imports_static() {
        let content = r#"
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.example.Foo;

public class FooTest {}
"#;
        let imports = parse_imports(content);
        assert_eq!(imports, vec![
            "org.junit.jupiter.api.Assertions",
            "com.example.Foo",
        ]);
    }

    #[test]
    fn test_parse_imports_skips_wildcard() {
        let content = "import java.util.*;\nimport com.example.Foo;\npublic class X {}";
        let imports = parse_imports(content);
        assert_eq!(imports, vec!["com.example.Foo"]);
    }

    #[test]
    fn test_path_to_class_name() {
        let root = std::path::Path::new("src/test/java");
        let file = std::path::Path::new("src/test/java/com/example/FooTest.java");
        assert_eq!(path_to_class_name(file, root), Some("com.example.FooTest".to_string()));
    }
}