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

import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;

import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.RiskscapeIOException;
import nz.org.riskscape.engine.resource.Resource;

/**
 * Represents a bit of source code - something that we will parse using RiskScape's DSL API.
 *
 * For now, this is effectively a wrapper around a string that remembers the location, but having a minimal matching
 * API would allow:
 *
 * - to parse the file without having to read the whole thing up front first.
 * - to not keep the whole thing in RAM once it's parsed.
 *
 * But debatable whether it's worth the effort - but might improve start up times for larger projects?
 */
@RequiredArgsConstructor
public class Source {

  /**
   * Create a Source object from a string and a URI
   */
  public static Source create(String string, URI location) {
    return new Source(string, location);
  }

  /**
   * Create a Source object from a {@link Resource}
   */
  public static Source from(Resource source) {
    return new Source(source.getContentAsString(), source.getLocation());
  }

  /**
   * Create a Source object from a file path
   */
  public static Source fromPath(String filepath) throws RiskscapeIOException {
    Path path = Paths.get(filepath);
    try {
      return new Source(Files.readAllLines(path).stream().collect(Collectors.joining("\n")), path.toUri());
    } catch (IOException e) {
      throw new RiskscapeIOException(e.getMessage(), e);
    }
  }

  /**
   * Create a Source object that doesn't retain its location - avoid using this where possible.
   */
  public static Source anon(String string) {
    return new Source(string, Resource.UNKNOWN_URI);
  }

  // NB: For now this is a string, but the source could be abstracted to avoid having to hold all the project files
  // in RAM, or to require having the whole file in RAM before we can start parsing it
  @NonNull
  private final String wrapping;

  @Getter @NonNull
  private final URI location;

  @Override
  public String toString() {
    String sourceFragment = wrapping.substring(0, Math.min(10, wrapping.length())).trim();

    if (isAnonymous()) {
      return String.format("Source[%s (anonymous)]", sourceFragment, location);
    } else {
      return String.format("Source[%s from %s]", sourceFragment, location);
    }
  }

  public boolean isAnonymous() {
    return location.equals(Resource.UNKNOWN_URI);
  }

  public String readFully() {
    return wrapping;
  }


  /*
   * String-like methods for supporting matchers
   */

  public int length() {
    // NB having this method forces us to know the full size of the source in chars, which means streaming is
    // impossible.
    return wrapping.length();
  }

  public char charAt(int index) {
    return wrapping.charAt(index);
  }

  public CharSequence subSequence(int start, int end) {
    return wrapping.subSequence(start, end);
  }

  public String substring(int begin, int end) {
    return wrapping.substring(begin, end);
  }

  public String substring(int begin) {
    return wrapping.substring(begin).toString();
  }

  public boolean isSingleLine() {
    return wrapping.trim().indexOf("\n") == -1;
  }
  /**
   * @see {@link String#regionMatches(int, String, int, int)}
   */
  public boolean regionMatches(int position, String string, int i, int length) {
    return wrapping.regionMatches(position, string, i, length);
  }

  /**
   * @see {@link String#regionMatches(boolean, int, String, int, int)}
   */
  public boolean regionMatches(boolean b, int position, String string, int i, int length) {
    return wrapping.regionMatches(b, position, string, i, length);
  }
}
