/*
 * Copyright 2011 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gradle.testfixtures.internal;

import org.gradle.api.JavaVersion;
import org.gradle.api.Project;
import org.gradle.api.artifacts.ModuleVersionIdentifier;
import org.gradle.api.artifacts.component.ProjectComponentIdentifier;
import org.gradle.api.internal.BuildDefinition;
import org.gradle.api.internal.DocumentationRegistry;
import org.gradle.api.internal.GradleInternal;
import org.gradle.api.internal.StartParameterInternal;
import org.gradle.api.internal.file.temp.DefaultTemporaryFileProvider;
import org.gradle.api.internal.file.temp.TemporaryFileProvider;
import org.gradle.api.internal.initialization.ClassLoaderScope;
import org.gradle.api.internal.project.ProjectIdentity;
import org.gradle.api.internal.project.ProjectInternal;
import org.gradle.api.internal.project.ProjectState;
import org.gradle.api.internal.project.ProjectStateRegistry;
import org.gradle.api.internal.properties.GradlePropertiesController;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.logging.configuration.WarningMode;
import org.gradle.api.problems.Problems;
import org.gradle.initialization.BuildRequestMetaData;
import org.gradle.initialization.DefaultBuildCancellationToken;
import org.gradle.initialization.DefaultBuildRequestMetaData;
import org.gradle.initialization.LegacyTypesSupport;
import org.gradle.initialization.NoOpBuildEventConsumer;
import org.gradle.initialization.layout.BuildLayoutFactory;
import org.gradle.internal.FileUtils;
import org.gradle.internal.Pair;
import org.gradle.internal.SystemProperties;
import org.gradle.internal.build.AbstractBuildState;
import org.gradle.internal.build.BuildState;
import org.gradle.internal.build.BuildStateRegistry;
import org.gradle.internal.build.RootBuildState;
import org.gradle.internal.buildoption.InternalOptions;
import org.gradle.internal.buildprocess.BuildProcessScopeServices;
import org.gradle.internal.buildtree.BuildModelParameters;
import org.gradle.internal.buildtree.BuildModelParametersFactory;
import org.gradle.internal.buildtree.BuildTreeLifecycleController;
import org.gradle.internal.buildtree.BuildTreeServices;
import org.gradle.internal.buildtree.BuildTreeState;
import org.gradle.internal.buildtree.RunTasksRequirements;
import org.gradle.internal.classpath.ClassPath;
import org.gradle.internal.composite.IncludedBuildInternal;
import org.gradle.internal.concurrent.Stoppable;
import org.gradle.internal.deprecation.DeprecationLogger;
import org.gradle.internal.id.UniqueId;
import org.gradle.internal.jvm.SupportedJavaVersions;
import org.gradle.internal.jvm.UnsupportedJavaRuntimeException;
import org.gradle.internal.logging.services.LoggingServiceRegistry;
import org.gradle.internal.nativeintegration.services.NativeServices;
import org.gradle.internal.nativeintegration.services.NativeServices.NativeServicesMode;
import org.gradle.internal.problems.NoOpProblemDiagnosticsFactory;
import org.gradle.internal.project.ImmutableProjectDescriptor;
import org.gradle.internal.resources.DefaultResourceLockCoordinationService;
import org.gradle.internal.resources.ResourceLockCoordinationService;
import org.gradle.internal.scopeids.id.BuildInvocationScopeId;
import org.gradle.internal.scripts.ScriptFileResolver;
import org.gradle.internal.scripts.ScriptFileUtil;
import org.gradle.internal.scripts.ScriptResolutionResultReporter;
import org.gradle.internal.service.CloseableServiceRegistry;
import org.gradle.internal.service.ServiceRegistry;
import org.gradle.internal.service.ServiceRegistryBuilder;
import org.gradle.internal.service.scopes.GradleUserHomeScopeServiceRegistry;
import org.gradle.internal.session.BuildSessionState;
import org.gradle.internal.session.CrossBuildSessionState;
import org.gradle.internal.time.Time;
import org.gradle.internal.work.ProjectParallelExecutionController;
import org.gradle.internal.work.WorkerLeaseRegistry;
import org.gradle.internal.work.WorkerLeaseService;
import org.gradle.util.GradleVersion;
import org.gradle.util.Path;
import org.jspecify.annotations.Nullable;

import java.io.File;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;

import static org.gradle.internal.concurrent.CompositeStoppable.stoppable;

public class ProjectBuilderImpl {
    private static @Nullable ServiceRegistry globalServices;

    private static final Logger LOGGER = Logging.getLogger(ProjectBuilderImpl.class);

    public Project createChildProject(String name, Project parent, @Nullable File inputProjectDir) {
        ProjectInternal parentProject = (ProjectInternal) parent;
        File projectDir = (inputProjectDir != null) ? inputProjectDir.getAbsoluteFile() : new File(parentProject.getProjectDir(), name);

        ProjectBuilderProjectDescriptor descriptor = descriptorForSubproject(parentProject, projectDir, name);
        ProjectBuilderProjectDescriptor parentDescriptor = (ProjectBuilderProjectDescriptor) parentProject.getOwner().getDescriptor();
        // Side effect, required due to projects being created one by one, instead of all together
        parentDescriptor.addChild(descriptor.getIdentity());

        ProjectState projectState = parentProject.getServices().get(ProjectStateRegistry.class).registerProject(parentProject.getServices().get(BuildState.class), descriptor);
        projectState.createMutableModel(parentProject.getClassLoaderScope().createChild("project-" + name, null), parentProject.getBaseClassLoaderScope());
        ProjectInternal project = projectState.getMutableModel();

        // Lock the project, these won't ever be released as ProjectBuilder has no lifecycle
        ResourceLockCoordinationService coordinationService = project.getServices().get(ResourceLockCoordinationService.class);
        coordinationService.withStateLock(DefaultResourceLockCoordinationService.lock(project.getOwner().getAccessLock()));

        return project;
    }

    public ProjectInternal createProject(String name, @Nullable File inputProjectDir, @Nullable File gradleUserHomeDir) {
        // ProjectBuilder uses daemon classes, so it has the same JVM compatibility.
        UnsupportedJavaRuntimeException.assertCurrentProcessSupportsDaemonJavaVersion();

        int currentMajor = Integer.parseInt(JavaVersion.current().getMajorVersion());
        if (currentMajor < SupportedJavaVersions.FUTURE_MINIMUM_DAEMON_JAVA_VERSION) {
            int currentMajorGradleVersion = GradleVersion.current().getMajorVersion();

            // We do not use a DeprecationLogger here since the logger is not initialized when using the ProjectBuilder.
            LOGGER.warn("Executing Gradle on JVM versions {} and lower has been deprecated. " +
                    "This will fail with an error in Gradle {}. " +
                    "Use JVM {} or greater to execute Gradle. " +
                    "Projects can continue to use older JVM versions via toolchains. " +
                    "Consult the upgrading guide for further information: {}",
                SupportedJavaVersions.FUTURE_MINIMUM_DAEMON_JAVA_VERSION - 1,
                currentMajorGradleVersion + 1,
                SupportedJavaVersions.FUTURE_MINIMUM_DAEMON_JAVA_VERSION,
                new DocumentationRegistry().getDocumentationFor("upgrading_version_" + currentMajorGradleVersion, "minimum_daemon_jvm_version")
            );
        }

        final File projectDir = prepareProjectDir(inputProjectDir);
        File userHomeDir = gradleUserHomeDir == null ? new File(projectDir, "userHome") : FileUtils.canonicalize(gradleUserHomeDir);
        StartParameterInternal startParameter = new StartParameterInternal();
        startParameter.setGradleUserHomeDir(userHomeDir);
        startParameter.setCurrentDir(projectDir);
        startParameter.doNotSearchUpwards();

        // ProjectBuilder tests are more lightweight and native services shouldn't be required, so we disable them by default.
        // Additionally, when they are enabled they are put in the projectDir by default and that can cause issues with test cleanup on Windows.
        // If needed, a test can still enable them by setting the org.gradle.native=true system property.
        // This was also the default behavior before Gradle 8.8 by accident since org.gradle.native=false was always passed to the test executor.
        NativeServicesMode nativeServicesMode = System.getProperty(NativeServices.NATIVE_SERVICES_OPTION) != null
            ? NativeServicesMode.fromSystemProperties()
            : NativeServicesMode.DISABLED;
        NativeServices.initializeOnDaemon(userHomeDir, nativeServicesMode);

        final ServiceRegistry globalServices = getGlobalServices();

        BuildRequestMetaData buildRequestMetaData = new DefaultBuildRequestMetaData(Time.currentTimeMillis());
        File userActionRootDir = globalServices.get(BuildLayoutFactory.class).getLayoutFor(startParameter.toBuildLayoutConfiguration()).getRootDirectory();
        CrossBuildSessionState crossBuildSessionState = new CrossBuildSessionState(globalServices, startParameter, userActionRootDir);
        GradleUserHomeScopeServiceRegistry userHomeServices = userHomeServicesOf(globalServices);
        BuildSessionState buildSessionState = new BuildSessionState(userHomeServices, crossBuildSessionState, startParameter, buildRequestMetaData, ClassPath.EMPTY, new DefaultBuildCancellationToken(), buildRequestMetaData.getClient(), new NoOpBuildEventConsumer());
        RunTasksRequirements buildActionRequirements = new RunTasksRequirements(startParameter);
        InternalOptions internalOptions = crossBuildSessionState.getServices().get(InternalOptions.class);
        ServiceRegistry buildSessionServices = buildSessionState.getServices();
        BuildModelParameters buildModelParameters = buildSessionServices.get(BuildModelParametersFactory.class).parametersForRootBuildTree(buildActionRequirements, internalOptions);
        BuildInvocationScopeId buildInvocationScopeId = new BuildInvocationScopeId(UniqueId.generate());
        BuildTreeState buildTreeState = new BuildTreeState(buildSessionServices, buildActionRequirements, buildModelParameters, buildInvocationScopeId);
        BuildTreeServices buildTreeServices = buildTreeState.getServices().get(BuildTreeServices.class);
        TestRootBuild build = new TestRootBuild(projectDir, startParameter, buildTreeServices);

        CloseableServiceRegistry buildServices = build.getBuildServices();
        buildServices.get(BuildStateRegistry.class).attachRootBuild(build);

        // Project or applied plugins can emit deprecation warnings, so we need to initialize the deprecation logger
        //noinspection DataFlowIssue
        DeprecationLogger.init(WarningMode.None, null, null, NoOpProblemDiagnosticsFactory.EMPTY_STREAM);

        // Take a root worker lease; this won't ever be released as ProjectBuilder has no lifecycle
        ResourceLockCoordinationService coordinationService = buildServices.get(ResourceLockCoordinationService.class);
        WorkerLeaseService workerLeaseService = buildServices.get(WorkerLeaseService.class);
        WorkerLeaseRegistry.WorkerLeaseCompletion workerLease = workerLeaseService.maybeStartWorker();
        buildServices.get(ProjectParallelExecutionController.class).startProjectExecution(false);

        GradleInternal gradle = build.getMutableModel();
        gradle.setIncludedBuilds(Collections.emptyList());

        GradlePropertiesController gradlePropertiesController = buildServices.get(GradlePropertiesController.class);
        gradlePropertiesController.loadGradleProperties(build.getBuildIdentifier(), build.getBuildRootDir(), false);

        ClassLoaderScope baseScope = gradle.getClassLoaderScope();
        ClassLoaderScope rootProjectScope = baseScope.createChild("root-project", null);

        ProjectStateRegistry projectStateRegistry = buildServices.get(ProjectStateRegistry.class);
        ImmutableProjectDescriptor rootProjectDescriptor = descriptorForRootProject(build.getIdentityPath(), projectDir, name, buildServices);
        ProjectState projectState = projectStateRegistry.registerProject(build, rootProjectDescriptor);
        projectState.createMutableModel(rootProjectScope, baseScope);
        ProjectInternal project = projectState.getMutableModel();

        gradle.setDefaultProjectState(projectState);

        // Lock root project; this won't ever be released as ProjectBuilder has no lifecycle
        coordinationService.withStateLock(DefaultResourceLockCoordinationService.lock(project.getOwner().getAccessLock()));

        Stoppable tearDown = stoppable(
            (Stoppable) workerLeaseService::runAsIsolatedTask,
            (Stoppable) workerLease::leaseFinish,
            buildServices,
            buildTreeState,
            buildSessionState,
            crossBuildSessionState
        );

        RootProjectContext.attach(project, new RootProjectContext(tearDown));

        return project;
    }

    private static ImmutableProjectDescriptor descriptorForRootProject(
        Path buildPath,
        File projectDir,
        String projectName,
        ServiceRegistry buildServices
    ) {
        ProjectIdentity identity = ProjectIdentity.forRootProject(buildPath, projectName);
        ScriptFileResolver scriptFileResolver = buildServices.get(ScriptFileResolver.class);
        ScriptResolutionResultReporter reporter = new ScriptResolutionResultReporter(buildServices.get(Problems.class).getReporter());
        File buildFile = ScriptFileUtil.resolveBuildFile(projectDir, scriptFileResolver, reporter::reportResolutionProblemsOf);
        return new ProjectBuilderProjectDescriptor(identity, projectDir, buildFile, null);
    }

    private static ProjectBuilderProjectDescriptor descriptorForSubproject(
        ProjectInternal parent,
        File projectDir,
        String projectName
    ) {
        ProjectIdentity parentIdentity = parent.getProjectIdentity();
        Path projectPath = parentIdentity.getProjectPath().child(projectName);
        ProjectIdentity identity = ProjectIdentity.forSubproject(parentIdentity.getBuildPath(), projectPath);
        ScriptFileResolver scriptFileResolver = parent.getServices().get(ScriptFileResolver.class);
        ScriptResolutionResultReporter reporter = new ScriptResolutionResultReporter(parent.getServices().get(Problems.class).getReporter());
        File buildFile = ScriptFileUtil.resolveBuildFile(projectDir, scriptFileResolver, reporter::reportResolutionProblemsOf);
        return new ProjectBuilderProjectDescriptor(identity, projectDir, buildFile, parentIdentity);
    }

    public static void stop(Project rootProject) {
        RootProjectContext.obtain(rootProject).tearDown.stop();
    }

    private GradleUserHomeScopeServiceRegistry userHomeServicesOf(ServiceRegistry globalServices) {
        return globalServices.get(GradleUserHomeScopeServiceRegistry.class);
    }

    public synchronized static ServiceRegistry getGlobalServices() {
        if (globalServices == null) {
            globalServices = createGlobalServices();
            // Inject missing interfaces to support the usage of plugins compiled with older Gradle versions.
            // A normal gradle build does this by adding the MixInLegacyTypesClassLoader to the class loader hierarchy.
            // In a test run, which is essentially a plain Java application, the classpath is flattened and injected
            // into the system class loader and there exists no Gradle class loader hierarchy in the running test. (See Implementation
            // in ApplicationClassesInSystemClassLoaderWorkerImplementationFactory, BootstrapSecurityManager and GradleWorkerMain.)
            // Thus, we inject the missing interfaces directly into the system class loader used to load all classes in the test.
            globalServices.get(LegacyTypesSupport.class).injectEmptyInterfacesIntoClassLoader(ProjectBuilderImpl.class.getClassLoader());
        }
        return globalServices;
    }

    private static ServiceRegistry createGlobalServices() {
        return ServiceRegistryBuilder
            .builder()
            .displayName("global services")
            .parent(LoggingServiceRegistry.newNestedLogging())
            .parent(NativeServices.getInstance())
            .provider(new TestGlobalScopeServices())
            .provider(new BuildProcessScopeServices())
            .build();
    }

    public File prepareProjectDir(@Nullable final File projectDir) {
        if (projectDir != null) {
            return FileUtils.canonicalize(projectDir);
        }

        TemporaryFileProvider temporaryFileProvider = new DefaultTemporaryFileProvider(() -> {
            String rootTmpDir = SystemProperties.getInstance().getWorkerTmpDir();
            if (rootTmpDir == null) {
                @SuppressWarnings("deprecation")
                String javaIoTmpDir = SystemProperties.getInstance().getJavaIoTmpDir();
                rootTmpDir = javaIoTmpDir;
            }
            return FileUtils.canonicalize(new File(rootTmpDir));
        });
        File tempDirectory = temporaryFileProvider.createTemporaryDirectory("gradle", "projectDir");
        // TODO deleteOnExit won't clean up non-empty directories (and it leaks memory for long-running processes).
        tempDirectory.deleteOnExit();
        return tempDirectory;
    }

    private static class TestRootBuild extends AbstractBuildState implements RootBuildState {

        public TestRootBuild(File rootProjectDir, StartParameterInternal startParameter, BuildTreeServices buildTreeServices) {
            super(buildTreeServices, BuildDefinition.fromStartParameter(startParameter, rootProjectDir, null), null);
        }

        @Override
        public CloseableServiceRegistry getBuildServices() {
            return super.getBuildServices();
        }

        @Override
        public void ensureProjectsLoaded() {
        }

        @Override
        public void ensureProjectsConfigured() {
        }

        @Override
        public Path getIdentityPath() {
            return Path.ROOT;
        }

        @Override
        public boolean isImplicitBuild() {
            return false;
        }

        @Override
        public StartParameterInternal getStartParameter() {
            throw new UnsupportedOperationException();
        }

        @Override
        public <T> T run(Function<? super BuildTreeLifecycleController, T> action) {
            throw new UnsupportedOperationException();
        }

        @Override
        public IncludedBuildInternal getModel() {
            throw new UnsupportedOperationException();
        }

        @Override
        public Set<Pair<ModuleVersionIdentifier, ProjectComponentIdentifier>> getAvailableModules() {
            throw new UnsupportedOperationException();
        }
    }

    /**
     * ProjectBuilder has its own simplified lifecycle that compresses all operational service scopes
     * into a single operation. It also skips the Settings phase entirely, so settings-specific
     * services must be created and managed manually.
     */
    private record RootProjectContext(
        Stoppable tearDown
    ) {

        // The context is stored in the ProjectBuilder-created root project's extra properties.
        // We have to store it in the root project state because the API gives out the full instances of the `Project` to the user.
        // That becomes the only state used for further interactions, such as creating new subprojects and the teardown at the end.
        private static final String EXT = "ProjectBuilder.context";

        static void attach(Project rootProject, RootProjectContext context) {
            assert rootProject.getParent() == null;
            rootProject.getExtensions().getExtraProperties().set(EXT, context);
        }

        static RootProjectContext obtain(Project rootProject) {
            assert rootProject.getParent() == null;
            return (RootProjectContext) Objects.requireNonNull(rootProject.getExtensions().getExtraProperties().get(EXT));
        }
    }
}
