/*
 * RiskScape™ Copyright New Zealand Institute for Earth Science Limited
 * (Earth Sciences New Zealand) is distributed for research purposes only
 * under the terms of AGPLv3.
 *
 * RiskScape™ Copyright 2026 New Zealand Institute for Earth Science
 * Limited (Earth Sciences New Zealand). All rights reserved. Source code
 * available under the AGPLv3.
 * 
 * This program is free software: you can redistribute it and/or modify it under
 *  the terms of the GNU Affero General Public License as published by the Free
 *  Software Foundation, either version 3 of the License, or (at your option) any
 *  later version.
 * 
 * This program is distributed for RESEARCH PURPOSES ONLY, in the hope that it will
 * be useful for research and education initiatives.
 * 
 * If you are not a researcher, or you are a researcher who wishes to use this
 * program on terms other than AGPLv3 (including those who wish to restrict the
 * distribution of any source code created using this program), please contact:
 * https://riskscape.org.nz
 * 
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.  You should have received a copy
 * of the GNU Affero General Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 * 
 * By way of summary only, under the AGPLv3:
 *     • Permissions of this strongest copyleft license are conditioned
 *       on making available complete source code of licensed works and
 *       modifications, which include larger works using a licensed work,
 *       under the same license.
 *     • Copyright and license notices must be preserved.
 *     • Contributors provide an express grant of patent rights.
 *     • When a modified version is used to provide a service over a
 *       network, the complete source code of the modified version must be made
 *       available.
 */
package nz.org.riskscape.engine;

import java.util.HashMap;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;

import com.codahale.metrics.MetricRegistry;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.UncheckedExecutionException;

import lombok.Getter;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.function.FunctionResolver;
import nz.org.riskscape.engine.rl.DefaultExpressionRealizer;
import nz.org.riskscape.engine.rl.ExpressionRealizer;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.problem.ProblemSink;
import nz.org.riskscape.problem.Problems;

public class DefaultRealizationContext implements RealizationContext {

  @Getter
  private final Project project;

  @Getter
  private final FunctionResolver functionResolver;

  @Getter
  private final ExpressionRealizer expressionRealizer;

  private final Cache<Object, Object> cache;

  @Getter
  private final MetricRegistry metricRegistry;

  @Getter
  private final BindingContext bindingContext;

  @Getter
  private final ProblemSink problemSink;

  public DefaultRealizationContext(Project project, MetricRegistry metricRegistry, BindingContext bindingContext,
      ProblemSink problemSink) {
    this.project = project;
    this.functionResolver = new DefaultFunctionResolver();
    this.expressionRealizer = new DefaultExpressionRealizer(this);
    this.cache = CacheBuilder.newBuilder()
        .softValues()
        // we use Math.max to ensure the concurrency level is set to something valid
        // this is mainly to keep tests passing because maybe they don't have a real pipeline executor
        .concurrencyLevel(Math.max(1, project.getEngine().getPipelineExecutor().getNumThreads()))
        .build();

    this.metricRegistry = metricRegistry;
    this.bindingContext = bindingContext;
    this.problemSink = problemSink;
  }


  /**
   * Maintains a mapping of normalized structs, to avoid object proliferation.
   * When two different structs are equal (i.e. Object#equals), then when
   * normalized they end up as the exact same object (i.e. Object ==). The first
   * struct normalized populates the map, then subsequent key lookups of
   * equivalent structs (Object#equals) will return the first canonical struct.
   */
  HashMap<RekeyedStruct, Struct> structs = new HashMap<>();
  // add this one in - reduces the need for tests etc to normalize it themselves
  Struct empty = normalizeStruct(Struct.EMPTY_STRUCT);

  @Override
  public Struct normalizeStruct(Struct struct) {
    // normalizing should typically only be done during realization, which is single-threaded.
    // However, dynamically loading a relation bookmark can do projection/struct realizing
    // on the fly, and this can occur during multi-threaded pipeline execution
    synchronized (this) {
      return structs.computeIfAbsent(new RekeyedStruct(struct), key -> key.source);
    }
  }

  @Override
  public <T> T getOrComputeFromCache(Object cacheKey, Class<T> expectedType, Function<Object, T> compute) {
    try {
      Object computed = cache.get(cacheKey, () -> compute.apply(cacheKey));
      return expectedType.cast(computed);
    } catch (ExecutionException | UncheckedExecutionException | ExecutionError e) {
      // These exceptions are thrown by the Cache if it catches an exception whilst loading a cache value.
      // All of these exceptions wrap the exception that trigged it.
      Throwable cause = e.getCause();
      if (cause instanceof RiskscapeException) {
        throw (RiskscapeException)cause;
      }
      throw new RiskscapeException(Problems.caught(e.getCause()));
    }
  }
}
