/*
 * 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.IOException;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.util.Formatter;

import org.json.JSONException;
import org.json.JSONObject;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.geojson.GeoJsonWriter;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;

import lombok.Getter;
import nz.org.riskscape.engine.OutputProblems;
import nz.org.riskscape.engine.Project;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.projection.FlattenProjection;
import nz.org.riskscape.engine.projection.Projector;
import nz.org.riskscape.engine.query.TupleUtils;
import nz.org.riskscape.engine.resource.CreateHandle;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.problem.StandardCodes;

/**
 * A {@link RiskscapeWriter} that writes in GeoJSON format as specified in RFC7926.
 */
public class GeoJSONWriter extends RiskscapeWriter {

  public static ResultOrProblems<GeoJSONWriter> of(Struct type, CreateHandle handle, Project project) {
    return ProblemException.catching(() -> {
      // we flatten the structure for better support with other geojson reading tools.
      // QGIS and OGR do not handle nested properties.
      FlattenProjection flattener = new FlattenProjection(".");
      Projector flattenProjector = flattener.getProjectionFunction(type).getOrThrow();

      StructMember geomMember = TupleUtils.findGeometryMember(
          flattenProjector.getProjectedType(), TupleUtils.FindOption.OPTIONAL);
      if (geomMember == null) {
        throw new ProblemException(Problem.error(StandardCodes.GEOMETRY_REQUIRED, type));
      }


      int crs84 = project.getSridSet().get(project.newBindingContext()
          .bind("CRS:84", CoordinateReferenceSystem.class)
          .getOrThrow());

      return new GeoJSONWriter(flattenProjector, geomMember, crs84, project.getSridSet(), handle);
    });
  }

  private final Projector flattenProjector;
  private final StructMember geometryMember;

  /**
   * The SRID for CRS84.
   *
   * GeoJSON geometries are always long/lat coordinate sequences. So we re-project to CRS84
   */
  private final int crs84;
  private final SRIDSet sridSet;
  private final CreateHandle handle;
  private final OutputStreamWriter writer;
  private final Formatter formatter;
  private final GeoJsonWriter geoJsonWriter;
  private boolean first = true;
  @Getter
  private URI storedAt = null;

  private GeoJSONWriter(Projector flattenProjector, StructMember geometryMember, int crs84, SRIDSet sridSet,
      CreateHandle handle) {
    this.flattenProjector = flattenProjector;
    this.geometryMember = geometryMember;
    this.crs84 = crs84;
    this.sridSet = sridSet;
    this.handle = handle;
    this.writer = new OutputStreamWriter(handle.getOutputStream());
    this.formatter = new Formatter(writer);

    this.geoJsonWriter = new GeoJsonWriter();
    this.geoJsonWriter.setEncodeCRS(false);

    // TODO we could add a bbox in here if bounds are known
    this.formatter.format("""
                          {
                            "type":"FeatureCollection",
                            "features":[
                          """);
  }

  @Override
  public void write(Tuple value) {
    Tuple flattened = flattenProjector.apply(value);

    // We create a new json writer for every tuple that gets written so that each tuple is on it's own
    // line. One tuple per line is busy enough, every tuple on the same line would be impossible to follow.
    StringBuilder sb = new StringBuilder();
    org.json.JSONWriter jsonWriter = new org.json.JSONWriter(sb);
    jsonWriter.object();
    jsonWriter.key("type");
    jsonWriter.value("Feature");

    Geometry geom = flattened.fetch(geometryMember);
    if (geom != null) {
      jsonWriter.key("geometry");
      // geometries are always re-projected to CRS84 to ensure the coordinate are long/lat as specified by RFC7946
      jsonWriter.value(new JSONObject(geoJsonWriter.write(sridSet.reproject(geom, crs84))));
    }

    jsonWriter.key("properties");
    try {
      writeInternal(flattened, jsonWriter);
    } catch (JSONException ex) {
      throw new RiskscapeException(
          OutputProblems.get().errorWriting(TupleUtils.getContentSummary(flattened), "GeoJSON")
              .withChildren(Problems.caught(ex)));
    }

    jsonWriter.endObject();

    formatter.format("%s%n    %s", first ? "" : ",", sb.toString());

    first = false;
  }

  protected void writeInternal(Tuple value, org.json.JSONWriter jsonWriter) {

    jsonWriter.object();

    for (StructMember entry : value.getStruct().getMembers()) {
      if (entry.equals(geometryMember)) {
        // we don't want the the geometry member to be included as geometry and text
        continue;
      }
      String key = entry.getKey();
      if ("geometry".equals(key)) {
        // the struct has a `geometry` entry. If we write this entry here then we wouldn't be able to
        // read the produced geojson back into RiskScape as we'd have something like
        // {geometry: GEOMETRY, geometry: TEXT}
        if (entry == geometryMember) {
        // If this is the actual geometry member then we can skip it here as it's the feature geometry
          continue;
        }
        // otherwise we can adjust the key name to prevent the collision. But we need to ensure we aren't
        // duplicating some other struct member key.
        for (int i = 1; true; i++) {
          key = String.format("geometry-%d", i);
          if (! value.getStruct().hasMember(key)) {
            break;
          }
        }
      }
      jsonWriter.key(key);

      Object childValue = value.fetch(entry);
      // TODO consider if geometry members should all be re-projected to CRS:84 for consistency, but our shapefile
      // writers don't do that either.
      if (childValue instanceof Tuple) {
        writeInternal((Tuple) childValue, jsonWriter);
      } else {
        jsonWriter.value(childValue);
      }
    }

    jsonWriter.endObject();

  }

  @Override
  public void close() throws IOException {
    formatter.format("""
                       ]
                     }
                     """);
    writer.close();
    storedAt = handle.store();
  }

}
