// Copyright 2018 The Bazel Authors. All rights reserved.
//
// 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 com.google.devtools.build.lib.skyframe;

import static java.util.Objects.requireNonNull;

import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.bazel.bzlmod.Version;
import com.google.devtools.build.lib.cmdline.RepositoryMapping;
import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.skyframe.serialization.VisibleForSerialization;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import com.google.devtools.build.lib.util.DetailedExitCode;
import com.google.devtools.build.lib.util.ExitCode;
import com.google.devtools.build.skyframe.SkyFunctionName;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;
import java.util.Optional;
import javax.annotation.Nullable;

/**
 * A {@link SkyValue} that wraps a {@link RepositoryMapping}.
 *
 * @param repositoryMapping The actual repo mapping. Will be null if the requested repo doesn't
 *     exist.
 * @param associatedModuleName Returns the name of the Bzlmod module associated with the requested
 *     repo. For repos generated by module extensions, this is the name of the module hosting the
 *     extension.
 * @param associatedModuleVersion Returns the version of the Bzlmod module associated with the
 *     requested repo. For repos generated by module extensions, this is the version of the module
 *     hosting the extension.
 */
@AutoCodec
public record RepositoryMappingValue(
    @Nullable RepositoryMapping repositoryMapping,
    Optional<String> associatedModuleName,
    Optional<String> associatedModuleVersion)
    implements SkyValue {
  public RepositoryMappingValue {
    requireNonNull(associatedModuleName, "associatedModuleName");
    requireNonNull(associatedModuleVersion, "associatedModuleVersion");
  }

  public static final RepositoryMappingValue VALUE_FOR_EMPTY_ROOT_MODULE =
      RepositoryMappingValue.create(RepositoryMapping.EMPTY, "", Version.EMPTY);

  public static final RepositoryMappingValue NOT_FOUND_VALUE =
      RepositoryMappingValue.createSpecial(null);

  public static final RepositoryMappingValue DEFAULT_VALUE_FOR_BUILTINS_REPO =
      RepositoryMappingValue.createSpecial(
          RepositoryMapping.create(
              ImmutableMap.of(
                  RepositoryName.BUILTINS.getName(),
                  RepositoryName.BUILTINS,
                  "",
                  RepositoryName.MAIN),
              RepositoryName.BUILTINS));

  public static RepositoryMappingValue create(
      RepositoryMapping repositoryMapping,
      String associatedModuleName,
      Version associatedModuleVersion) {
    return new RepositoryMappingValue(
        repositoryMapping,
        Optional.of(associatedModuleName),
        Optional.of(associatedModuleVersion.getNormalized()));
  }

  /**
   * Returns a {@link RepositoryMappingValue} for certain special repos with no associated module
   * (for example {@code @_builtins}).
   */
  public static RepositoryMappingValue createSpecial(RepositoryMapping repositoryMapping) {
    return new RepositoryMappingValue(repositoryMapping, Optional.empty(), Optional.empty());
  }

  /**
   * Replaces the inner {@link #repositoryMapping() repository mapping} with one returned by calling
   * its {@link RepositoryMapping#withAdditionalMappings} method.
   */
  public RepositoryMappingValue withAdditionalMappings(RepositoryMapping repoMapping) {
    return new RepositoryMappingValue(
        repositoryMapping.withAdditionalMappings(repoMapping),
        associatedModuleName,
        associatedModuleVersion);
  }

  /**
   * Replaces the inner {@link #repositoryMapping() repository mapping} with one returned by calling
   * its {@link RepositoryMapping#withCachedInverseMap} method.
   */
  public RepositoryMappingValue withCachedInverseMap() {
    return new RepositoryMappingValue(
        repositoryMapping().withCachedInverseMap(),
        associatedModuleName(),
        associatedModuleVersion());
  }

  /** Returns the {@link Key} for {@link RepositoryMappingValue}s. */
  public static Key key(RepositoryName repositoryName) {
    return RepositoryMappingValue.Key.create(repositoryName);
  }

  /** {@link SkyKey} for {@link RepositoryMappingValue}. */
  // TODO: b/331765692 - migrate to a record once autocodec supports it.
  @AutoValue
  public abstract static class Key implements SkyKey {

    /** The name of the repo to grab mappings for. */
    public abstract RepositoryName repoName();

    private static final SkyKeyInterner<Key> interner = SkyKey.newInterner();

    public static Key create(RepositoryName repoName) {
      return interner.intern(new AutoValue_RepositoryMappingValue_Key(repoName));
    }

    @VisibleForSerialization
    @AutoCodec.Interner
    static Key intern(Key key) {
      return interner.intern(key);
    }

    @Override
    public SkyFunctionName functionName() {
      return SkyFunctions.REPOSITORY_MAPPING;
    }

    @Override
    public SkyKeyInterner<Key> getSkyKeyInterner() {
      return interner;
    }
  }

  /**
   * Exception thrown where the RepositoryMappingValue is requested and its computation fails for
   * any reason.
   */
  public static class RepositoryMappingResolutionException extends Exception {

    private final DetailedExitCode detailedExitCode;

    public RepositoryMappingResolutionException(DetailedExitCode detailedExitCode) {
      super(
          String.format(
              "Error computing the main repository mapping: %s",
              detailedExitCode.getFailureDetail().getMessage()));
      this.detailedExitCode = detailedExitCode;
    }

    public RepositoryMappingResolutionException(
        DetailedExitCode detailedExitCode, Throwable cause) {
      super(
          String.format(
              "Error computing the main repository mapping: %s",
              detailedExitCode.getFailureDetail().getMessage()),
          cause);
      this.detailedExitCode = detailedExitCode;
    }

    public ExitCode getExitCode() {
      return detailedExitCode.getExitCode();
    }

    public DetailedExitCode getDetailedExitCode() {
      return detailedExitCode;
    }
  }
}
