/*
 * 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.sched;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.output.PipelineJobContext;
import nz.org.riskscape.engine.pipeline.ExecutionResult;
import nz.org.riskscape.problem.Problem;

/**
 * Used as a {@link Future} for jobs queued up on the Scheduler.  Also has some job management code for use by the
 * {@link Scheduler} (hence the package scope on some methods)
 */
@RequiredArgsConstructor
public class ExecutionFuture implements Future<ExecutionResult> {

  // use the schedulers log, it's a more meaningful topic
  private static final Logger LOG = LoggerFactory.getLogger(Scheduler.class);

  @Getter(AccessLevel.PACKAGE)
  private final PipelineJobContext jobContext;

  /**
   * Used for storing either success or failure exception, plus used as a mutex for threads waiting on get()
   */
  private final AtomicReference<Object> result = new AtomicReference<>();

  @Override
  public boolean cancel(boolean mayInterruptIfRunning) {
    return false;
  }

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

  @Override
  public boolean isDone() {
    return result.get() != null;
  }

  @Override
  public ExecutionResult get() throws InterruptedException, java.util.concurrent.ExecutionException {
    try {
      return get(0, TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
      throw new AssertionError("we should never timeout with wait of 0");
    }
  }

  @Override
  public ExecutionResult get(long timeout, TimeUnit unit)
      throws InterruptedException, java.util.concurrent.ExecutionException, TimeoutException {
    if (!isDone()) {
      synchronized (result) {
        result.wait(unit.toMillis(timeout));
      }
    }

    ExecutionResult executionResult = result();
    if (executionResult == null) {
      // can only assume we've timed out here
      throw new TimeoutException();
    }
    return executionResult;
  }

  void markFailed(Problem problem) {
    markFailed(new RiskscapeException(problem));
  }

  void markFailed(Throwable throwable) {
    if (result.compareAndSet(null, throwable)) {
      // wake up future people
      synchronized (result) {
        result.notifyAll();
      }
    } else {
      if (result.get() instanceof ExecutionResult) {
        // failure after complete? this shouldn't happen...
        throw new AssertionError("Job has completed, failure afterwards shouldn't happen", throwable);
      } else {
        // often we'll get a bunch of failures after the initial one (because parallelism) - don't worry the user
        // with those, we will just put a message in to the logs
        LOG.info("Job {} is already marked failed, ignoring exception {}", jobContext, throwable);
      }

      return;
    }
  }

  // should only called by the scheduler thread from run()
  void markComplete() {
    if (result.compareAndSet(null, new ExecutionResult(jobContext))) {
      // wake up future people
      synchronized (result) {
        result.notifyAll();
      }
    } else {
      // hmm, we've already been marked as complete, perhaps we've already failed?
      // throw an error? log an error?
      Exception marker = new Exception();
      marker.fillInStackTrace();
      LOG.warn("Job already complete, has been marked complete again from ", marker);
    }
  }

  private ExecutionResult result() throws java.util.concurrent.ExecutionException {
    Object value = result.get();
    if (value instanceof Throwable) {
      throw new java.util.concurrent.ExecutionException((Throwable) value);
    } else {
      return (ExecutionResult) value;
    }
  }

}
