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

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import nz.org.riskscape.engine.task.ReturnState;
import nz.org.riskscape.engine.task.WorkerTask;

/**
 * The Worker represents a thread that can run tasks. It gets assigned a
 * WorkerTask by the Scheduler and runs the task until it is either complete,
 * there's no more input available, or its output buffer is full. The result of
 * the task is then passed back to the Scheduler.
 */
@RequiredArgsConstructor
@Slf4j
public class Worker implements Runnable {

  @RequiredArgsConstructor
  public class Result {
    public final WorkerTask task;
    public final ReturnState state;
    public final Throwable errorThrown;

    public Result(WorkerTask task, ReturnState state) {
      this(task, state, null);
    }
  }

  public final AtomicReference<Result> lastResult = new AtomicReference<>();

  private final int id;

  public final Scheduler owner;

  private WorkerTask currentTask;

  private final Object sleepMutex = new Object();

  private boolean threadActive = true;

  public static final int MAX_WAIT_MILLISECS = 1000;

  /**
   * @return true if the Worker is currently busy running a task
   */
  public boolean isRunning() {
    return hasCurrentTask();
  }

  private boolean hasCurrentTask() {
    synchronized (sleepMutex) {
      return currentTask != null;
    }
  }

  public Result clearLastTask() {
    return lastResult.getAndSet(null);
  }

  private void wakeThread() {
    // wake up our main run() thread when there is something to do
    synchronized (sleepMutex) {
      sleepMutex.notify();
    }
  }

  public void setCurrentTask(WorkerTask task) {
    synchronized (sleepMutex) {
      currentTask = task;
    }
  }

  public void runTask(WorkerTask toRun) {
    setCurrentTask(toRun);
    wakeThread();
  }

  private void waitForMoreWork() {
    synchronized (sleepMutex) {
      // we should only ever sleep if there's no current task to run
      // (note we check this inside the mutex to avoid race conditions)
      if (currentTask == null) {
        try {
          // don't sleep indefinitely, just in case of race conditions
          sleepMutex.wait(MAX_WAIT_MILLISECS);
        } catch (InterruptedException e) {
          throw new RuntimeException("Worker interupted", e);
        }
      }
    }
  }

  @Override
  public void run() {
    while (threadActive) {
      // wait until the scheduler gives us something to do
      waitForMoreWork();

      if (hasCurrentTask()) {
        // run the task and store the result to pass back to the scheduler
        try {
          ReturnState result = currentTask.runPublic();
          storeResult(result);
        } catch (Throwable t) {
          storeException(t);
        }

        // let the scheduler know we've finished running
        setCurrentTask(null);
        owner.workerFinished();
      }
    }
  }

  private void storeResult(ReturnState result) {
    lastResult.set(new Result(currentTask, result));
  }

  private void storeException(Throwable t) {
    log.info("Exception processing {}: {}", currentTask, t);
    lastResult.set(new Result(currentTask, ReturnState.ERROR_THROWN, t));
  }

  /**
   * Stop the Worker (once it completes any task currently in progress).
   */
  public void stop() {
    threadActive = false;
    wakeThread();
  }

  @Override
  public String toString() {
    return String.format("Worker thread #%d", id);
  }
}
