"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = mavenExecutor;
const tslib_1 = require("tslib");
const devkit_1 = require("@nx/devkit");
const run_commands_impl_1 = tslib_1.__importDefault(require("nx/src/executors/run-commands/run-commands.impl"));
const detect_maven_executable_1 = require("../../utils/detect-maven-executable");
const nxMavenApplyGoal = 'dev.nx.maven:nx-maven-plugin:apply';
const nxMavenRecordGoal = 'dev.nx.maven:nx-maven-plugin:record';
/**
 * Get the Maven project coordinates (groupId:artifactId) from project metadata.
 * Falls back to the Nx project name if metadata is not available.
 */
function getMavenProjectName(context) {
    const projectConfig = context.projectGraph?.nodes?.[context.projectName]?.data;
    return (projectConfig?.metadata?.mavenProject ||
        context.projectName);
}
/**
 * Build Maven command arguments
 */
function buildMavenArgs(options, projectName, useMaven4) {
    const args = [];
    // Verbose flags
    if (process.env.NX_VERBOSE_LOGGING === 'true') {
        args.push('-X', '-e');
    }
    // Never update snapshots (faster builds)
    args.push('-nsu');
    // Non-recursive - only build the specified project (Maven 4.x only)
    // Maven 3.x needs to scan modules to find projects
    if (useMaven4) {
        args.push('-N');
    }
    // Project selector - always pass the project
    args.push('-pl', projectName);
    // Goals with apply/record wrappers
    if (options.goals) {
        const goals = Array.isArray(options.goals)
            ? options.goals
            : options.goals.split(' ');
        args.push(nxMavenApplyGoal);
        args.push(...goals);
        args.push(nxMavenRecordGoal);
    }
    // Additional args from options
    if (options.args) {
        const additionalArgs = Array.isArray(options.args)
            ? options.args
            : options.args.trim().split(' ');
        args.push(...additionalArgs.filter((arg) => arg.length > 0));
    }
    return args;
}
/**
 * Maven single-task executor
 */
async function mavenExecutor(options, context) {
    const mavenExecutable = (0, detect_maven_executable_1.detectMavenExecutable)(devkit_1.workspaceRoot);
    const mavenProject = getMavenProjectName(context);
    const useMaven4 = (0, detect_maven_executable_1.isMaven4)(devkit_1.workspaceRoot);
    const args = buildMavenArgs(options, mavenProject, useMaven4);
    return (0, run_commands_impl_1.default)({
        command: mavenExecutable,
        cwd: devkit_1.workspaceRoot,
        args,
        __unparsed__: options.__unparsed__ || [],
    }, context);
}
