ym 0.3.58

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
use anyhow::{bail, Result};
use console::style;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::config;
use crate::hotreload;
use crate::resources;
use crate::scripts;
use crate::watcher::FileWatcher;
use crate::workspace::graph::WorkspaceGraph;

pub fn execute(
    target: Option<String>,
    no_reload: bool,
    debug: bool,
    debug_port: Option<u16>,
    suspend: bool,
    jvm_extra_args: Vec<String>,
) -> 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)?;

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

    if cfg.workspaces.is_some() {
        let target = target.as_deref().unwrap_or_else(|| {
            eprintln!("  In workspace mode, specify a target: ymc dev <module>");
            std::process::exit(1);
        });
        let result = dev_workspace(&project, target);
        // Run postdev script
        scripts::run_script(&cfg, "postdev", &project)?;
        return result;
    }

    // Resolve dependencies (auto-download all, then scope-filter)
    let start = Instant::now();
    let _all_jars = super::build::resolve_deps(&project, &cfg)?;
    // Compilation: compile + provided
    let compile_jars = super::build::resolve_deps_with_scopes(&project, &cfg, &["compile", "provided"])?;
    // Runtime: compile + runtime
    let runtime_jars = super::build::resolve_deps_with_scopes(&project, &cfg, &["compile", "runtime"])?;
    let dep_count = runtime_jars.len();
    let resolve_time = start.elapsed();

    let ws_count = cfg.workspace_module_deps().len();

    println!(
        "{} dependencies ({} workspace + {} maven) {:>4}ms",
        style(format!("{:>12}", "Resolving")).green().bold(),
        ws_count,
        dep_count,
        resolve_time.as_millis()
    );

    // Initial compile (compile + provided scope)
    let compile_start = Instant::now();
    let result = super::build::compile_project(&project, &cfg, &compile_jars)?;
    let compile_time = compile_start.elapsed();

    if !result.success {
        eprint!("{}", crate::compiler::colorize_errors(&result.errors));
        bail!("Compilation failed");
    }

    // Copy resources (same as build command)
    let src = config::source_dir(&project);
    let out = config::output_classes_dir(&project);
    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());
    resources::copy_resources_with_extensions(&src, &out, custom_res_ext.map(|v| v.as_slice()), res_exclude.map(|v| v.as_slice()))?;

    let resources_dir = project.join("src").join("main").join("resources");
    if resources_dir.exists() {
        resources::copy_resources_with_extensions(&resources_dir, &out, custom_res_ext.map(|v| v.as_slice()), res_exclude.map(|v| v.as_slice()))?;
    }

    println!(
        "{} {} ({} files) {:>27}ms",
        style(format!("{:>12}", "Compiling")).green().bold(),
        &cfg.name,
        result.outcome.files_compiled(),
        compile_time.as_millis()
    );

    // Find main class
    let main_class = resolve_main_class(&cfg, &project, target.as_deref())?;

    // Build runtime classpath (compile + runtime scope)
    let out_dir = config::output_classes_dir(&project);
    let mut classpath = vec![out_dir.clone()];
    classpath.extend(runtime_jars.clone());

    let mut jvm_args: Vec<String> = cfg.jvm_args.clone().unwrap_or_default();

    // Add user-provided JVM args (from -- args)
    jvm_args.extend(jvm_extra_args.clone());

    // JDWP debug support
    if debug || suspend {
        let port = debug_port.unwrap_or(5005);
        // Check if debug port is already in use
        if is_port_in_use(port) {
            eprintln!(
                "  {} Debug port {} is already in use. Use --debug-port to specify another port.",
                style("!").yellow(),
                style(port).bold()
            );
        }
        let suspend_flag = if suspend { "y" } else { "n" };
        jvm_args.push(format!(
            "-agentlib:jdwp=transport=dt_socket,server=y,suspend={},address=*:{}",
            suspend_flag, port
        ));
        if suspend {
            println!(
                "  {} Waiting for debugger on port {}...",
                style("!").yellow(),
                style(port).bold()
            );
        } else {
            println!(
                "  {} Debug mode: listening on port {}",
                style("✓").green(),
                port
            );
        }
    }

    // Enable enhanced class redefinition on JBR (DCEVM built-in)
    // DCEVM enhances Instrumentation.redefineClasses() to support structural changes,
    // which directly powers ym-agent L1 hot reload (add/remove methods and fields).
    if !jvm_args.iter().any(|a| a.contains("AllowEnhancedClassRedefinition")) && detect_dcevm() {
        jvm_args.push("-XX:+AllowEnhancedClassRedefinition".to_string());
        println!(
            "  {} DCEVM enabled (enhanced hot reload)",
            style("✓").green(),
        );
    }

    // Spring Boot DevTools: auto-configure if devtools JAR is on classpath
    if runtime_jars.iter().any(|p| p.to_string_lossy().contains("spring-boot-devtools")) {
        // Enable restart classloader and livereload
        if !jvm_args.iter().any(|a| a.contains("spring.devtools")) {
            jvm_args.push("-Dspring.devtools.restart.enabled=true".to_string());
            jvm_args.push("-Dspring.devtools.livereload.enabled=true".to_string());
            println!(
                "  {} Spring Boot DevTools detected (restart + livereload)",
                style("✓").green(),
            );
        }
    }

    // Try to attach hot reload agent
    let hot_reload_enabled = !no_reload
        && cfg
            .hot_reload
            .as_ref()
            .and_then(|h| h.enabled)
            .unwrap_or(true);

    let agent_port = if hot_reload_enabled {
        if let Some(agent_jar) = hotreload::find_agent_jar() {
            let port = hotreload::find_free_port()?;
            let agent_args = hotreload::agent_jvm_args(&agent_jar, port);
            jvm_args.extend(agent_args);
            println!(
                "  {} Hot reload agent on port {}",
                style("✓").green(),
                port
            );
            Some(port)
        } else {
            None
        }
    } else {
        None
    };

    // Load .env files
    let dotenv = load_dotenv(&project);

    // Start the Java process
    let run_start = Instant::now();
    let mut child = start_java_process(&main_class, &classpath, &jvm_args, &dotenv)?;
    let run_time = run_start.elapsed();

    println!(
        "  {} Started {}                  {:>4.1}s",
        style("✓").green(),
        style(&main_class).bold(),
        run_time.as_secs_f64()
    );
    println!();

    // Set up file watcher
    let src_dir = config::source_dir(&project);
    let watch_extensions = cfg
        .hot_reload
        .as_ref()
        .and_then(|h| h.watch_extensions.clone())
        .unwrap_or_else(|| vec![".java".to_string()]);

    let file_count = count_source_files(&src_dir, &watch_extensions);

    println!(
        "  {} watching {} source files...",
        style("➜").green(),
        style(file_count).cyan()
    );
    println!();

    let watcher = FileWatcher::new(&[src_dir], watch_extensions)?;

    let result = dev_watch_loop(watcher, &mut child, &main_class, &classpath, &jvm_args, &dotenv, &project, &cfg, &compile_jars, agent_port);

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

    result
}

fn dev_workspace(root: &std::path::Path, target: &str) -> Result<()> {
    let ws = WorkspaceGraph::build(root)?;
    let packages = ws.transitive_closure(target)?;

    let start = Instant::now();
    super::build::compile_only(Some(target.to_string()))?;
    let _build_time = start.elapsed();

    let mut classpath = Vec::new();
    let mut watch_dirs = Vec::new();
    let mut all_jars = Vec::new();
    let mut src_to_module: Vec<(std::path::PathBuf, String)> = Vec::new();

    for pkg_name in &packages {
        let pkg = ws.get_package(pkg_name).unwrap();
        classpath.push(config::output_classes_dir(&pkg.path));
        let jars = super::build::resolve_deps(&pkg.path, &pkg.config)?;
        all_jars.extend(jars);

        let src = config::source_dir(&pkg.path);
        if src.exists() {
            watch_dirs.push(src.clone());
            src_to_module.push((src, pkg_name.clone()));
        }
    }
    classpath.extend(all_jars);

    let target_pkg = ws.get_package(target).unwrap();
    let main_class = resolve_main_class(&target_pkg.config, &target_pkg.path, None)?;
    let jvm_args = target_pkg.config.jvm_args.clone().unwrap_or_default();

    // Load .env files from target package directory
    let dotenv = load_dotenv(&target_pkg.path);

    let run_start = Instant::now();
    let mut child = start_java_process(&main_class, &classpath, &jvm_args, &dotenv)?;
    let run_time = run_start.elapsed();

    println!(
        "  {} Started {}                  {:>4.1}s",
        style("✓").green(),
        style(&main_class).bold(),
        run_time.as_secs_f64()
    );
    println!();

    let watch_extensions = vec![".java".to_string()];
    let file_count: usize = watch_dirs
        .iter()
        .map(|d| count_source_files(d, &watch_extensions))
        .sum();

    println!(
        "  {} watching {} source files...",
        style("➜").green(),
        style(file_count).cyan()
    );
    println!();

    let watcher = FileWatcher::new(&watch_dirs, watch_extensions)?;

    let running = Arc::new(AtomicBool::new(true));
    let r = running.clone();
    ctrlc::set_handler(move || {
        r.store(false, Ordering::SeqCst);
    })?;

    while running.load(Ordering::SeqCst) {
        let changed = watcher.wait_for_changes(Duration::from_millis(100));

        if !running.load(Ordering::SeqCst) {
            break;
        }

        if changed.is_empty() {
            continue;
        }

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

        let changed_modules = identify_changed_modules(&changed, &src_to_module);

        let compile_start = Instant::now();
        let build_ok = if changed_modules.is_empty() {
            super::build::compile_only(Some(target.to_string())).is_ok()
        } else {
            recompile_affected_modules(&changed_modules, &packages, &ws, &classpath)
        };
        let compile_time = compile_start.elapsed();

        if build_ok {
            graceful_stop(&mut child);
            child = start_java_process(&main_class, &classpath, &jvm_args, &dotenv)?;

            let module_info = if changed_modules.is_empty() {
                "all".to_string()
            } else {
                changed_modules.join(", ")
            };
            println!(
                "  {} recompiled [{}] ({}ms) -> restarted {}",
                style(&now).dim(),
                module_info,
                compile_time.as_millis(),
                style("✓").green()
            );
        } else {
            eprintln!(
                "  {} Compilation failed ({}ms)",
                style(&now).dim(),
                compile_time.as_millis()
            );
        }
    }

    println!();
    println!("  Stopping...");
    graceful_stop(&mut child);

    Ok(())
}

/// Identify which workspace module(s) contain the changed files.
fn identify_changed_modules(
    changed_files: &[std::path::PathBuf],
    src_to_module: &[(std::path::PathBuf, String)],
) -> Vec<String> {
    let mut modules = Vec::new();
    for file in changed_files {
        for (src_dir, module_name) in src_to_module {
            if file.starts_with(src_dir) && !modules.contains(module_name) {
                modules.push(module_name.clone());
                break;
            }
        }
    }
    modules
}

/// Recompile only affected modules (changed + downstream dependents).
fn recompile_affected_modules(
    changed_modules: &[String],
    all_packages: &[String],
    ws: &WorkspaceGraph,
    full_classpath: &[std::path::PathBuf],
) -> bool {
    let mut affected: std::collections::HashSet<String> = changed_modules.iter().cloned().collect();

    for pkg_name in all_packages {
        if affected.contains(pkg_name) {
            continue;
        }
        if let Some(pkg) = ws.get_package(pkg_name) {
            let ws_deps = pkg.config.workspace_module_deps();
            if ws_deps.iter().any(|dep| affected.contains(dep)) {
                affected.insert(pkg_name.clone());
            }
        }
    }

    for pkg_name in all_packages {
        if !affected.contains(pkg_name) {
            continue;
        }
        if let Some(pkg) = ws.get_package(pkg_name) {
            let result = super::build::compile_project(&pkg.path, &pkg.config, full_classpath);
            match result {
                Ok(r) if r.success => {}
                Ok(r) => {
                    eprint!("{}", crate::compiler::colorize_errors(&r.errors));
                    return false;
                }
                Err(e) => {
                    eprintln!("  {} Error compiling {}: {}", style("✗").red(), pkg_name, e);
                    return false;
                }
            }
        }
    }

    true
}

fn dev_watch_loop(
    watcher: FileWatcher,
    child: &mut std::process::Child,
    main_class: &str,
    classpath: &[std::path::PathBuf],
    jvm_args: &[String],
    dotenv: &HashMap<String, String>,
    project: &std::path::Path,
    cfg: &config::schema::YmConfig,
    jars: &[std::path::PathBuf],
    agent_port: Option<u16>,
) -> Result<()> {
    let running = Arc::new(AtomicBool::new(true));
    let r = running.clone();
    ctrlc::set_handler(move || {
        r.store(false, Ordering::SeqCst);
    })?;

    let agent_client = agent_port.map(hotreload::AgentClient::new);

    while running.load(Ordering::SeqCst) {
        let changed = watcher.wait_for_changes(Duration::from_millis(100));

        if !running.load(Ordering::SeqCst) {
            break;
        }

        if changed.is_empty() {
            continue;
        }

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

        let compile_start = Instant::now();
        let result = super::build::compile_project(project, cfg, jars)?;
        let compile_time = compile_start.elapsed();

        if !result.success {
            eprintln!(
                "  {} Compilation failed ({}ms)",
                style(&now).dim(),
                compile_time.as_millis()
            );
            eprint!("{}", crate::compiler::colorize_errors(&result.errors));
            continue;
        }

        // Try hot reload via agent (only if process is still running)
        let process_alive = child.try_wait().ok().flatten().is_none();
        if process_alive {
            if let Some(ref client) = agent_client {
                let class_names = extract_class_names(&changed, project);
                if !class_names.is_empty() {
                    let out_dir = config::output_classes_dir(project);
                    match client.reload(&out_dir, &class_names) {
                        Ok(reload_result) if reload_result.success => {
                            println!(
                                "  {} compiled {} file(s) ({}ms) -> {} {}",
                                style(&now).dim(),
                                result.outcome.files_compiled(),
                                compile_time.as_millis(),
                                reload_result.strategy,
                                style("✓").green()
                            );
                            continue;
                        }
                        Ok(reload_result) => {
                            eprintln!(
                                "  {} Hot reload failed: {} (falling back to restart)",
                                style("!").yellow(),
                                reload_result.error.as_deref().unwrap_or("unknown")
                            );
                        }
                        Err(e) => {
                            eprintln!(
                                "  {} Agent unreachable: {} (falling back to restart)",
                                style("!").yellow(),
                                e
                            );
                        }
                    }
                }
            }
        }

        // Fall back to restart
        graceful_stop(child);

        *child = start_java_process(main_class, classpath, jvm_args, dotenv)?;

        println!(
            "  {} compiled {} file(s) ({}ms) -> restarted {}",
            style(&now).dim(),
            result.outcome.files_compiled(),
            compile_time.as_millis(),
            style("✓").green()
        );
    }

    println!();
    println!("  Stopping...");
    graceful_stop(child);

    Ok(())
}

/// Resolve the main class from config or source scanning
pub fn resolve_main_class(cfg: &config::schema::YmConfig, project: &std::path::Path, _target: Option<&str>) -> Result<String> {
    if let Some(ref main) = cfg.main {
        return Ok(main.clone());
    }

    // Scan for main classes
    let src_dir = config::source_dir_for(project, cfg);
    let main_classes = find_main_classes(&src_dir);

    match main_classes.len() {
        0 => bail!("No main class found. Set 'main' in package.toml or add a class with 'public static void main(String[] args)'"),
        1 => Ok(main_classes[0].clone()),
        _ => {
            use std::io::IsTerminal;
            if !std::io::stdin().is_terminal() {
                bail!("Multiple main classes found: {}. Set 'main' in package.toml", main_classes.join(", "));
            }
            let selection = dialoguer::Select::new()
                .with_prompt("Select main class")
                .items(&main_classes)
                .default(0)
                .interact()?;
            Ok(main_classes[selection].clone())
        }
    }
}

fn find_main_classes(src_dir: &std::path::Path) -> Vec<String> {
    let mut result = Vec::new();
    if !src_dir.exists() {
        return result;
    }
    for entry in walkdir::WalkDir::new(src_dir) {
        let entry = match entry {
            Ok(e) => e,
            Err(_) => continue,
        };
        if entry.path().extension().and_then(|e| e.to_str()) != Some("java") {
            continue;
        }
        if let Ok(content) = std::fs::read_to_string(entry.path()) {
            if content.contains("public static void main(String") ||
               content.contains("public static void main( String") {
                if let Ok(rel) = entry.path().strip_prefix(src_dir) {
                    let class_name = rel
                        .to_string_lossy()
                        .replace(['/', '\\'], ".")
                        .trim_end_matches(".java")
                        .to_string();
                    result.push(class_name);
                }
            }
        }
    }
    result
}

/// Load .env files from the given directory.
/// Files loaded in order: .env, .env.development (later overrides earlier).
fn load_dotenv(dir: &std::path::Path) -> HashMap<String, String> {
    let mut env = HashMap::new();
    for name in &[".env", ".env.development"] {
        let path = dir.join(name);
        if let Ok(content) = std::fs::read_to_string(&path) {
            let mut count = 0;
            for line in content.lines() {
                let line = line.trim();
                if line.is_empty() || line.starts_with('#') {
                    continue;
                }
                if let Some((key, value)) = line.split_once('=') {
                    env.insert(key.trim().to_string(), value.trim().to_string());
                    count += 1;
                }
            }
            println!(
                "  {} Loaded {} ({} vars)",
                style("✓").green(),
                name,
                count
            );
        }
    }
    env
}

/// Start a Java process
fn start_java_process(
    main_class: &str,
    classpath: &[std::path::PathBuf],
    jvm_args: &[String],
    env: &HashMap<String, String>,
) -> Result<std::process::Child> {
    let cp = classpath
        .iter()
        .map(|p| p.display().to_string())
        .collect::<Vec<_>>()
        .join(if cfg!(windows) { ";" } else { ":" });

    let mut cmd = std::process::Command::new("java");
    cmd.envs(env);
    for arg in jvm_args {
        cmd.arg(arg);
    }

    // Use argfile to avoid "Argument list too long" (E2BIG) on large classpaths
    let argfile = std::env::temp_dir().join(format!("ym-cp-{}.txt", std::process::id()));
    std::fs::write(&argfile, format!("-cp\n{}\n{}", cp, main_class))?;
    cmd.arg(format!("@{}", argfile.display()));

    // Create a new process group so we can kill the entire tree on stop
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        unsafe {
            cmd.pre_exec(|| {
                libc::setsid();
                Ok(())
            });
        }
    }

    let child = cmd.spawn()
        .map_err(|e| anyhow::anyhow!("Failed to start Java process: {}", e))?;

    Ok(child)
}

/// Gracefully stop a Java process: SIGTERM entire process group → 5s timeout → SIGKILL.
fn graceful_stop(child: &mut std::process::Child) {
    // Already exited
    if child.try_wait().ok().flatten().is_some() {
        return;
    }

    #[cfg(unix)]
    {
        let pid = child.id() as i32;
        // Send SIGTERM to entire process group (negative PID)
        unsafe { libc::kill(-pid, libc::SIGTERM); }
        // Wait up to 5 seconds
        for _ in 0..50 {
            if child.try_wait().ok().flatten().is_some() {
                return;
            }
            std::thread::sleep(Duration::from_millis(100));
        }
        // Force kill entire process group
        unsafe { libc::kill(-pid, libc::SIGKILL); }
        let _ = child.wait();
    }
    #[cfg(not(unix))]
    {
        // /T kills the entire process tree
        let pid = child.id();
        let _ = std::process::Command::new("taskkill")
            .args(["/F", "/T", "/PID", &pid.to_string()])
            .status();
        let _ = child.wait();
    }
}

/// Extract Java class names from changed file paths.
fn extract_class_names(changed_files: &[std::path::PathBuf], project: &std::path::Path) -> Vec<String> {
    let src_dir = config::source_dir(project);
    changed_files
        .iter()
        .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("java"))
        .filter_map(|p| {
            p.strip_prefix(&src_dir).ok().map(|rel| {
                rel.to_string_lossy()
                    .replace(['/', '\\'], ".")
                    .trim_end_matches(".java")
                    .to_string()
            })
        })
        .collect()
}

fn chrono_time() -> String {
    use std::time::SystemTime;
    let now = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap();
    let secs = now.as_secs() % 86400;
    let hours = secs / 3600;
    let minutes = (secs % 3600) / 60;
    let seconds = secs % 60;
    format!("[{:02}:{:02}:{:02}]", hours, minutes, seconds)
}

fn count_source_files(dir: &std::path::Path, extensions: &[String]) -> usize {
    if !dir.exists() {
        return 0;
    }
    walkdir::WalkDir::new(dir)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| {
            if let Some(ext) = e.path().extension().and_then(|e| e.to_str()) {
                let dot_ext = format!(".{}", ext);
                extensions.iter().any(|x| x == &dot_ext || x == ext)
            } else {
                false
            }
        })
        .count()
}

/// Detect DCEVM/JBR support via JAVA_HOME path or `java -version` output.
fn detect_dcevm() -> bool {
    // Method 1: JAVA_HOME path contains jbr/jetbrains
    if let Ok(java_home) = std::env::var("JAVA_HOME") {
        let home_lower = java_home.to_lowercase();
        if home_lower.contains("jbr") || home_lower.contains("jetbrains") {
            return true;
        }
    }

    // Method 2: parse `java -version` output for JBR/DCEVM signature
    if let Ok(output) = std::process::Command::new("java")
        .arg("-version")
        .output()
    {
        let stderr = String::from_utf8_lossy(&output.stderr).to_lowercase();
        if stderr.contains("jetbrains") || stderr.contains("jbr") || stderr.contains("dcevm") {
            return true;
        }
    }

    false
}

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

    #[test]
    fn test_identify_changed_modules() {
        let src_to_module = vec![
            (std::path::PathBuf::from("/project/core/src"), "core".to_string()),
            (std::path::PathBuf::from("/project/web/src"), "web".to_string()),
        ];

        let changed = vec![std::path::PathBuf::from("/project/core/src/Main.java")];
        let modules = identify_changed_modules(&changed, &src_to_module);
        assert_eq!(modules, vec!["core"]);

        let changed = vec![
            std::path::PathBuf::from("/project/core/src/Foo.java"),
            std::path::PathBuf::from("/project/web/src/Bar.java"),
        ];
        let modules = identify_changed_modules(&changed, &src_to_module);
        assert_eq!(modules.len(), 2);
    }
}

/// Check if a TCP port is already in use by attempting to bind to it.
fn is_port_in_use(port: u16) -> bool {
    std::net::TcpListener::bind(("127.0.0.1", port)).is_err()
}