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

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.util.List;
import java.util.Optional;

import org.geotools.api.data.DataStore;
import org.geotools.data.DefaultTransaction;
import org.geotools.api.data.FeatureWriter;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.api.feature.simple.SimpleFeature;
import org.geotools.api.feature.simple.SimpleFeatureType;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;

import org.locationtech.jts.geom.Geometry;

import lombok.Getter;

import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.output.StructFlattener.StructMapping;
import nz.org.riskscape.engine.types.Geom;
import nz.org.riskscape.engine.types.GeomType;
import nz.org.riskscape.engine.types.MultiGeom;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Referenced;
import nz.org.riskscape.engine.types.SimpleType;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Value;

import lombok.NonNull;

/**
 * Writes typed riskscape {@link Value}s out to a new file.
 * <p>
 * Due to restrictions in the shapefile format and geotools' own hacks to work with them, the {@link ShapefileWriter}
 * writes out the geometry to the <code>the_geom</code> magic feature attribute.  If geometry also appears in the
 * value, the writer either ignores it (if it was also passed as the special geometry parameter) or writes it out as
 * text in WKT
 */
public abstract class AbstractDataStoreWriter extends RiskscapeWriter implements Closeable {

  /**
   * When writing out a {@link SimpleType} value, the feature's only attribute is named this
   */
  public static final String VALUE_ATTRIBUTE = "value";

  /**
   * The name of the geometry output in the written feature - by convention with shapefiles this must be
   * the_geom
   */
  public static final String GEOMETRY_ATTRIBUTE = "the_geom";

  private final DataStore dataStore;

  /**
   * The {@link Type} we are writing out to file.  All calls to {@link #write(Tuple)} must match this
   * type.
   */
  @Getter
  private Struct riskscapeType;

  @Getter
  private final URI storedAt;

  private DefaultTransaction transaction;
  private FeatureWriter<SimpleFeatureType, SimpleFeature> featureWriter;

  //Map to contain mappings from feature attributes to access expressions
  protected List<StructMapping> mappings;
  private StructMapping geometryMapping;

  private SRIDSet sridSet;

  protected boolean setup = false;

  /**
   * SRID to write geometries as.
   */
  protected int targetSrid;

  /**
   * some formats require mandate x-y ordering, regardless of what the prj says - this is here to apply that.
   * Implementations should set the axisSwapper if required by overriding the `outputCrs` method
   */
  protected AxisSwapper axisSwapper;

  public AbstractDataStoreWriter(File outfile, SRIDSet sridSet, DataStore dataStore) throws IOException {
    this.storedAt = outfile.toURI();
    this.sridSet = sridSet;
    this.dataStore = dataStore;
    this.transaction = new DefaultTransaction("riskscape-writer-" + outfile.getAbsolutePath());
  }

  private SimpleFeatureTypeBuilder setupBuilder(String name, CoordinateReferenceSystem crs, Class<?> geometryType) {
    SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
    builder.setName("riskscape");
    if (crs != null) {
      builder.setCRS(outputCrs(crs));
    }
    builder.add(GEOMETRY_ATTRIBUTE, geometryType);
    return builder;
  }

  /**
   * Get a crs that will be "correct" for the produced file. This is to allow implementions to modify output where this
   * may be expected by other software. Such as EPSG:4326 in shapefiles other software ignores axis defintion
   * in projection file and instead uses Long/Lat.
   *
   * Implementations that override this method should set the targetSrid to match the returned CRS.
   *
   * @param crs
   * @return crs   correct crs for the produced file
   */
  protected CoordinateReferenceSystem outputCrs(@NonNull CoordinateReferenceSystem crs) {
    targetSrid = sridSet.get(crs);
    return crs;
  }

  @Override
  public void close() throws IOException {
    if (this.featureWriter != null) {
      this.featureWriter.close();
    }
    this.transaction.commit();
    this.transaction.close();
  }

  @Override
  public void write(Tuple value) throws WriteException {

    try {
      setupCrsAndGeoType(value);
    } catch (IOException e) {
      throw new WriteException("Failed to setup crs and geometry", e);
    }

    if (!value.getStruct().equals(this.riskscapeType)) {
      throw new IllegalArgumentException(String.format(
          "given value with type does not match required type: %s !=  %s", value.getStruct(), this.riskscapeType));
    }

    SimpleFeature toWrite;
    try {
      toWrite = featureWriter.next();
    } catch (IOException e) {
      throw new WriteException("failed to add new feature to data store", e);
    }

    for (StructFlattener.StructMapping member : mappings) {
      Object subValue = member.getAccessExpression().evaluate(value);
      if (member == geometryMapping) {
        @SuppressWarnings("unchecked")
        Geometry geom = (Geometry)subValue;
        if (geom != null && axisSwapper != null) {
          geom = axisSwapper.swapAxis(geom);
        }
        // geometry member is written directly, no null value mapping here
        toWrite.setAttribute(GEOMETRY_ATTRIBUTE, geom);
      } else {
        setAttr(toWrite, member.getKey(), subValue, member.getType());
      }
    }

    try {
      featureWriter.write();
    } catch (IOException e) {
      throw new WriteException("Failed to write new feature to data store", e);
    }
  }

  protected void setupCrsAndGeoType(Tuple value) throws IOException {
    if (this.setup) {
      return;
    }

    this.riskscapeType = value.getStruct();
    StructFlattener flattener = new StructFlattener();
    this.mappings = flattener.flatten(riskscapeType);
    if (getAttrNameMaxLength() > 0) {
      flattener.shortenIfNecessary(mappings, getAttrNameMaxLength());
    }
    this.geometryMapping = mappings.stream()
        .filter(m -> m.getType().findAllowNull(Geom.class).isPresent())
        .findFirst()
        .orElseThrow(() -> new RiskscapeException(
            "output type does not include geometry - output file requires geometry"));

    Geometry geom = (Geometry)geometryMapping.getAccessExpression().evaluate(value);

    Class geomClass;
    CoordinateReferenceSystem crs = geometryMapping.getType().findAllowNull(Referenced.class)
        .map(Referenced::getCrs)
        .orElse(null);

    if (geom == null) {
      // we need to attempt to infer the geom class from the type system
      geomClass = geomClassTypeFrom(Nullable.strip(geometryMapping.getType()));
    } else if (crs == null && geom.getSRID() > 0) {
      // If the type system doesn't have the CRS, then we use the geometry's SRID
      crs = sridSet.get(geom.getSRID());
      geomClass = geom.getClass();
    } else {
      geomClass = geom.getClass();
    }

    SimpleFeatureTypeBuilder builder = setupBuilder("anon", crs, geomClass);
    dataStore.createSchema(featureTypeFromMappings(builder));
    this.featureWriter = dataStore.getFeatureWriter(dataStore.getTypeNames()[0], transaction);

    this.setup = true;
  }

  /**
   * @return Geometry class inferred from the type system. This is not guaranteed to work all the time, so
   * should only be used with the first tuple written has a null geometry member.
   */
  private Class geomClassTypeFrom(Type type) {
    Optional<Class> multiGeom = type.find(MultiGeom.class)
        .map(MultiGeom::internalType);
    if (multiGeom.isPresent()) {
      return multiGeom.get();
    }
    Optional<Class> geometryType = type.find(GeomType.class)
        .map(GeomType::internalType);
    if (geometryType.isPresent()) {
      return geometryType.get();
    }

    // we really don't know. This is probably going to blow up later.
    return Geometry.class;
  }

  /**
   * Sub classes should override and return a positive value to force attribute names to be truncated if
   * they exceed the max length.
   *
   * @return desired max length of attribute names
   */
  protected int getAttrNameMaxLength() {
    return -1;
  }

  protected void setAttr(SimpleFeature toWrite, String key, Object value, Type type) {
    // we write bigdecimals as strings, not floats, to preserve accuracy
    Object valueToWrite;
    if (value instanceof BigDecimal) {
      valueToWrite = value.toString();
    } else {
      valueToWrite = value;
    }

    toWrite.setAttribute(key, mapValueIfNecessary(valueToWrite, type));
  }

  /**
   * Allows implementations to perform any value mapping should this be required.
   *
   * @param value to map
   * @param type Riskscape type that values is
   * @return value, or a mapped version of value.
   */
  protected Object mapValueIfNecessary(Object value, Type type) {
    return value;
  }

  protected SimpleFeatureType featureTypeFromMappings(SimpleFeatureTypeBuilder builder) {
    mappings.forEach(member -> {
      // GEOMETRY_ATTRIBUTE is special and set up elsewhere
      if (!member.equals(this.geometryMapping)) {
        builder.add(member.getKey(), mapJavaType(member.getType().internalType()));
      }
    });
    return builder.buildFeatureType();
  }

  protected Class<?> mapJavaType(Class<?> toMap) {
    if (toMap.equals(BigDecimal.class)) {
      // so we don't lose precision
      return String.class;
    } else if (Geometry.class.isAssignableFrom(toMap)) {
      // we don't support more than one geometry, so write out extra value as wkt
      return String.class;
    } else {
      return toMap;
    }
  }

}
