"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.detectMavenVersion = detectMavenVersion;
exports.isMaven4 = isMaven4;
exports.detectMavenExecutable = detectMavenExecutable;
const fs_1 = require("fs");
const child_process_1 = require("child_process");
const path_1 = require("path");
const devkit_1 = require("@nx/devkit");
// Cache Maven version to avoid repeated execSync calls
let cachedMavenVersion = null;
/**
 * Detect Maven version (e.g., "4.0.0-rc-4" or "3.9.9")
 */
function detectMavenVersion(workspaceRoot) {
    if (cachedMavenVersion !== null) {
        return cachedMavenVersion;
    }
    const executable = detectMavenExecutable(workspaceRoot);
    try {
        const output = (0, child_process_1.execSync)(`${executable} --version`, {
            cwd: workspaceRoot,
            stdio: 'pipe',
            encoding: 'utf-8',
            windowsHide: true,
        });
        // Parse version from output like "Apache Maven 4.0.0-rc-4" or "Apache Maven 3.9.9"
        const match = output.match(/Apache Maven (\d+\.\d+\.\d+[^\s]*)/);
        if (match) {
            cachedMavenVersion = match[1];
            devkit_1.logger.verbose(`[Maven] Detected version: ${cachedMavenVersion}`);
            return cachedMavenVersion;
        }
    }
    catch {
        // Failed to detect version
    }
    return null;
}
/**
 * Check if Maven 4.x is being used
 */
function isMaven4(workspaceRoot) {
    const version = detectMavenVersion(workspaceRoot);
    return version?.startsWith('4') ?? false;
}
/**
 * Detect Maven executable: mvnd > mvnw > mvn
 */
function detectMavenExecutable(workspaceRoot) {
    // First priority: Check for Maven Daemon
    try {
        (0, child_process_1.execSync)('mvnd --version', { stdio: 'pipe', windowsHide: true });
        devkit_1.logger.verbose(`[Maven] Found Maven Daemon, using: mvnd`);
        return 'mvnd';
    }
    catch {
        // Maven Daemon not available
    }
    // Second priority: Check for Maven wrapper
    if (process.platform === 'win32') {
        const wrapperPath = (0, path_1.join)(workspaceRoot, 'mvnw.cmd');
        if ((0, fs_1.existsSync)(wrapperPath)) {
            devkit_1.logger.verbose(`[Maven] Found Maven wrapper, using: mvnw.cmd`);
            return 'mvnw.cmd';
        }
    }
    else {
        const wrapperPath = (0, path_1.join)(workspaceRoot, 'mvnw');
        if ((0, fs_1.existsSync)(wrapperPath)) {
            devkit_1.logger.verbose(`[Maven] Found Maven wrapper, using: ./mvnw`);
            return './mvnw';
        }
    }
    // Fallback: Use regular Maven
    devkit_1.logger.verbose(`[Maven] Using fallback: mvn`);
    return 'mvn';
}
