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

import java.util.List;

import org.geotools.referencing.CRS;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.geotools.api.referencing.FactoryException;
import org.geotools.api.referencing.NoSuchAuthorityCodeException;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.GeometryProblems;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.BaseRealizableFunction;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.FunctionCall;

public class GeomFromWKT extends BaseRealizableFunction {

  public GeomFromWKT() {
    super(
      ArgumentList.create("wkt_text", Types.TEXT),
      Types.GEOMETRY
     );
  }

  // this is useful for testing, but currently hidden from users because it can make the
  // Relation behave unintuitively, i.e. it's not a replacement for bookmark crs-name even
  // though it appears to do the same job. See GL-#338 for more details
  // new FunctionArgument("crs_name", Nullable.TEXT)
  // need this for constant initialization
  private final ArgumentList argumentsHidden = ArgumentList.create("wkt_text", Types.TEXT, "crs_name", Nullable.TEXT);

  @Override
  public ResultOrProblems<RiskscapeFunction> realize(RealizationContext context, FunctionCall functionCall,
      List<Type> givenTypes) {

    return ProblemException.catching(() -> {

      WKTReader wktReader;
      if (givenTypes.size() == 1) {
        wktReader = new WKTReader();
      } else if (givenTypes.size() == 2) {
        CoordinateReferenceSystem crs = parseCrs(context, functionCall);
        wktReader = new WKTReader(context.getProject().getSridSet().getGeometryFactory(crs));
      } else {
        throw new ProblemException(ArgsProblems.get().wrongNumber(2, givenTypes.size()));
      }

      return new Instance(givenTypes, wktReader);
    });

  }

  @RequiredArgsConstructor
  private static class Instance implements RiskscapeFunction {
    @Getter
    private final List<Type> argumentTypes;

    @Getter
    private final Type returnType = Types.GEOMETRY;

    private final WKTReader reader;

    @Override
    public Object call(List<Object> args) {
      String wktText = (String) args.get(0);
      try {
        return reader.read(wktText);
      } catch (ParseException e) {
        throw new RiskscapeException(GeometryProblems.get().badWkt(wktText)
                .withChildren(Problems.caught(e)));
      }
    }
  }

  private CoordinateReferenceSystem parseCrs(RealizationContext context, FunctionCall functionCall)
      throws ProblemException {

    String crsCode =
        argumentsHidden.evaluateConstant(context, functionCall, "crs_name", String.class, Types.TEXT).getOrThrow();

    try {
      return CRS.decode(crsCode);
    } catch (NoSuchAuthorityCodeException e) {
      // this one is a bad code
      throw new ProblemException(GeometryProblems.get().unknownCrsCode(crsCode));
    } catch (FactoryException e) {
      // this one isn't the user's fault, but maybe they can do something about it?
      throw new ProblemException(Problems.caught(e));
    }
  }

}
