/*
 * 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.net.URI;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

import lombok.Data;

/**
 * Information about a specific character location within a string of source code
 */
@Data
public class SourceLocation implements Comparable<SourceLocation> {

  /**
   * Attempt to parse the given URI fragment and turn it in to a {@link SourceLocation}, returning empty if it doesn't
   * parse.  See {@link #toUriFragment()} for the inverse method.
   * @param fragment the anchor fragment part of a URI, can be null, see {@link URI#getFragment()}.
   */
  public static Optional<SourceLocation> parseUriFragment(String fragment) {
    // short-circuit if it doesn't start with I (for index) - it won't be a source location if it doesn't start with I
    if (fragment == null || !fragment.startsWith("I")) {
      return Optional.empty();
    }

    List<String> bits = List.of(fragment.substring(1).split("[ILC]"));
    if (bits.size() != 3) {
      return Optional.empty();
    }

    try {
      Iterator<Integer> ints = bits.stream().map(Integer::parseInt).toList().iterator();
      return Optional.of(new SourceLocation(ints.next(), ints.next(), ints.next()));
    } catch (NumberFormatException e) {
      return Optional.empty();
    }
  }

  /**
   * @return a location in source that has lost track of line numbers.
   */
  public static SourceLocation unlined(int index) {
    return new SourceLocation(index, -1, index + 1);
  }

  /**
   * @return a single lined location at the given index
   */
  public static SourceLocation index(int index) {
    return new SourceLocation(index, 1, index + 1);
  }

  /**
   * Starting position.
   */
  public static final SourceLocation START = new SourceLocation(0, 1, 1);

  /**
   * Absolute index in to the source string.
   */
  private final int index;

  /**
   * Line number (1 based)
   */
  private final int line;

  /**
   * Column number within the current line (1 based)
   */
  private final int column;

  @Override
  public String toString() {
    if (isUnlined()) {
      return String.format("index %d (unlined)", index);
    } else {
      return String.format("line %d, column %d", line, column);
    }
  }

  /**
   * @return a new SourceLocation shifted forward by moveByChars.
   */
  public SourceLocation advance(int moveByChars) {
    return new SourceLocation(index + moveByChars, line, column + moveByChars);
  }

  /**
   * @return a new SourceLocation at the same overall index, but at the start of a new line, i.e. index stays the same,
   * line is incremented and column is set to 1.
   */
  public SourceLocation newline() {
    if (isUnlined()) {
      throw new IllegalStateException("Unlined locations can't do newlines");
    }

    return new SourceLocation(index, line + 1, 1);
  }

  /**
   * @return true if this source location has lost track of lines
   */
  public boolean isUnlined() {
    return this.line == -1;
  }

  /**
   * Creates a string that can be embedded in a URI as an anchor fragment, see {@link #parseUriFragment(String)} for the
   * inverse method.
   */
  public String toUriFragment() {
    return String.format("I%dL%dC%d", index, line, column);
  }

  /**
   * Creates that extends/modifies the given URI so that it includes an anchor fragment that points to this source code
   * location
   */
  public URI addToUri(URI existing) {
    String uriString = existing.toString();
    int lastIndexOf = uriString.lastIndexOf('#');

    if (lastIndexOf >= 0) {
      uriString = uriString.substring(0, lastIndexOf + 1) + toUriFragment();
    } else {
      uriString = uriString + "#" + toUriFragment();
    }

    return URI.create(uriString);
  }

  @Override
  public int compareTo(SourceLocation rhs) {
    if (this.isUnlined() != rhs.isUnlined()) {
      throw new IllegalArgumentException("Can not compare source locations if one is lined and the other not");
    }

    if (this.isUnlined()) {
      //  sort by position in source when either is unlined
      return Integer.compare(this.index, rhs.index);
    } else {
      // otherwise, to allow a comparison between potentially different documents, we sort by line then column
      int lineCmp = Integer.compare(this.line, rhs.line);
      if (lineCmp != 0) {
        return lineCmp;
      } else {
        return Integer.compare(this.column, rhs.column);
      }
    }
  }
}
