/*
 * 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.Optional;
import java.util.function.Predicate;

import lombok.Getter;

/**
 * Handles all the complicated logic of how many tuples should fit into a Page. These
 * characteristics can vary from task to task, so this class allows different parts of the pipeline
 * to fine-tune that behaviour, e.g. slower tasks should use smaller pages and more of them.
 */
public class PageAllocator {

  private static final int NO_MAX_SIZE = Integer.MAX_VALUE;

  private final int initialPageSize;

  /**
   * The maximum number of tuples that can potentially fit into a single Page.
   */
  @Getter
  private final int maxPageSize;

  private final Optional<Integer> doubleEveryNPages;

  private final Optional<Predicate<PageAllocator>> applyBackoff;

  private volatile long pagesAllocated = 0;
  private int currentPageSize;

  public PageAllocator(int startAt, int maxSize, Optional<Integer> incrementPeriod,
      Optional<Predicate<PageAllocator>> backoff) {
    this.initialPageSize = startAt;
    this.maxPageSize = maxSize;
    this.doubleEveryNPages = incrementPeriod;
    this.applyBackoff = backoff;
    this.currentPageSize = startAt;
  }

  /**
   * Returns a basic page allocator that will always allocate the same size page.
   */
  public PageAllocator(int fixedSize) {
    // the page-size is fixed at this point, so maxPageSize is kind of irrelevant
    this(fixedSize, NO_MAX_SIZE, Optional.empty(), Optional.empty());
  }

  /**
   * Returns a new PageAllocator with a fixed maximum size, but with all other characteristics the same.
   */
  public PageAllocator withMaxPageSize(int maxSize) {
    return new PageAllocator(Math.min(initialPageSize, maxSize), maxSize, doubleEveryNPages, applyBackoff);
  }

  /**
   * Returns a new PageAllocator that can backoff and reduce the size of the pages it allocates under
   * certain conditions, i.e. memory pressure. The allocator will go back to the initial page size, so
   * this only will work in combination with {@link #doubleEvery(int)}.
   */
  public PageAllocator withBackoff(Predicate<PageAllocator> backoffWhen) {
    if (!doubleEveryNPages.isPresent()) {
      throw new IllegalStateException("Can only use backoff in combination with doubleEvery()");
    }
    return new PageAllocator(initialPageSize, maxPageSize, doubleEveryNPages, Optional.of(backoffWhen));
  }

  /**
   * Returns a new PageAllocator that gradually increases the size of the page, every nTimes. This
   * allows pages to start off small (which works better for a small number of total tuples that
   * require intensive processing), and then grow up to their maximum size (which works better for
   * large datasets).
   */
  public PageAllocator doubleEvery(int nTimes) {
    return new PageAllocator(initialPageSize, maxPageSize, Optional.of(nTimes), applyBackoff);
  }

  /**
   * @return true if we should increase/double the size of the pages we're allocating
   */
  private boolean shouldDoublePageSize() {
    return doubleEveryNPages.isPresent()
        && pagesAllocated != 0
        && (pagesAllocated % doubleEveryNPages.get()) == 0;
  }

  /**
   * @return true if we should reduce the size of the pages we're allocating (or the number of tuples
   *         queued in the buffer itself)
   */
  public boolean isBackoffNeeded() {
    return applyBackoff.map(backoff -> backoff.test(this)).orElse(false);
  }

  /**
   * @return the size (number of tuples) that the next page should use
   */
  protected int getPageSize() {
    if (isBackoffNeeded()) {
      currentPageSize = initialPageSize;

    } else if (shouldDoublePageSize()) {
      currentPageSize = Math.min(currentPageSize * 2, maxPageSize);
    }
    return currentPageSize;
  }

  /**
   * @return a new Page that can then be filled with Tuples
   */
  public Page newPage() {
    synchronized (this) {
      Page page = new Page(getPageSize());
      pagesAllocated++;
      return page;
    }
  }
}
