"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDependencies = void 0;
const devkit_1 = require("@nx/devkit");
const node_path_1 = require("node:path");
const get_project_graph_from_gradle_plugin_1 = require("./utils/get-project-graph-from-gradle-plugin");
const split_config_files_1 = require("../utils/split-config-files");
const workspace_context_1 = require("nx/src/utils/workspace-context");
const node_fs_1 = require("node:fs");
const createDependencies = async (options, context) => {
    const files = await (0, workspace_context_1.globWithWorkspaceContext)(devkit_1.workspaceRoot, Array.from(split_config_files_1.GRADLEW_FILES));
    const { gradlewFiles } = (0, split_config_files_1.splitConfigFiles)(files);
    await (0, get_project_graph_from_gradle_plugin_1.populateProjectGraph)(context.workspaceRoot, gradlewFiles.map((file) => (0, node_path_1.join)(devkit_1.workspaceRoot, file)), options);
    const { dependencies: dependenciesFromReport } = (0, get_project_graph_from_gradle_plugin_1.getCurrentProjectGraphReport)();
    const dependencies = [];
    dependenciesFromReport.forEach((dependencyFromPlugin) => {
        try {
            const source = (0, node_path_1.relative)(devkit_1.workspaceRoot, dependencyFromPlugin.source) || '.';
            const sourceProjectName = Object.values(context.projects).find((project) => source === project.root)?.name ?? dependencyFromPlugin.source;
            const target = (0, node_path_1.relative)(devkit_1.workspaceRoot, dependencyFromPlugin.target) || '.';
            const targetProjectName = Object.values(context.projects).find((project) => target === project.root)?.name ?? dependencyFromPlugin.target;
            if (!sourceProjectName ||
                !targetProjectName ||
                !(0, node_fs_1.existsSync)(dependencyFromPlugin.sourceFile)) {
                return;
            }
            const dependency = {
                source: sourceProjectName,
                target: targetProjectName,
                type: devkit_1.DependencyType.static,
                sourceFile: (0, devkit_1.normalizePath)((0, node_path_1.relative)(devkit_1.workspaceRoot, dependencyFromPlugin.sourceFile)),
            };
            (0, devkit_1.validateDependency)(dependency, context);
            dependencies.push(dependency);
        }
        catch {
            devkit_1.logger.warn(`Unable to parse dependency from gradle plugin: ${dependencyFromPlugin.source} -> ${dependencyFromPlugin.target}`);
        }
    });
    return dependencies;
};
exports.createDependencies = createDependencies;
