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

import com.csvreader.CsvReader;
import com.google.common.collect.ImmutableMap;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import org.geotools.api.data.DataStore;
import org.geotools.api.data.DataStoreFinder;
import org.geotools.data.DataUtilities;
import org.geotools.api.data.FeatureSource;
import org.geotools.data.csv.CSVDataStoreFactory;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.api.data.SimpleFeatureSource;
import org.geotools.data.wfs.WFSDataStoreFactory;
import org.geotools.api.feature.simple.SimpleFeature;
import org.geotools.api.feature.simple.SimpleFeatureType;

/**
 * TODO start to pair back all of the support in here so that it lives in the resolvers - strip this back to just
 * local file support maybe
 */
public class FeatureSources {

  //The CSV column name the WKT geometries are required to be in
  public static final String GEOMETRY_COLUMN_NAME = "the_geom";
  public static final int WFS_TIMEOUT_MS = 600000;

  public static SimpleFeatureSource open(String target, Optional<String> typeName) {
    if (target.startsWith("http") && target.toLowerCase().contains("wfs")) {
      //Treat it as WFS
      return openDataSource(target, ImmutableMap.of(
          WFSDataStoreFactory.TIMEOUT.key, WFS_TIMEOUT_MS,
          WFSDataStoreFactory.URL.key, target
      ), typeName);
    }
    //Not WFS, then assume target should be local file.
    return open(new File(target), typeName);
  }

  public static SimpleFeatureSource open(File target) {
    return open(target, Optional.empty());
  }

  public static SimpleFeatureSource open(File target, Optional<String> requestedType) {
    Map<String, Object> map = new HashMap<>();
    try {
      map.put("url", target.toURI().toURL());
      if (target.getName().endsWith(".csv")) {
        //It's a CSV
        setCsvOptions(target, map);
      } else if (target.getName().endsWith(".shp")) {
        // TODO make this linux  only - it does seem to give us a a decent speed improvement
        map.put(ShapefileDataStoreFactory.MEMORY_MAPPED.key, true);
      }
    } catch (MalformedURLException e) {
      throw new RuntimeException(e);
    }
    return openDataSource(target.getName(), map, requestedType);
  }

  /**
   * CSV files may contain either a single column of WKT or two columns of lat/long.
   *
   * This method inspects the file header to attempt to deduce what the geom style is.
   */
  private static void setCsvOptions(File csvFile, Map<String, Object> map) {
    //Default WKT, for writing
    boolean useWKT = true;
    if (csvFile.exists()) {
      useWKT = false; //For reading we'll only use WKT if a the_geom column is found
      try (BufferedReader reader = new BufferedReader(new FileReader(csvFile))) {
        //Read the first line of file. Thats all we need for now.
        try (Reader header = new StringReader(reader.readLine())) {
          CsvReader csvReader = new CsvReader(header);
          csvReader.readHeaders();
          String[] headers = csvReader.getHeaders();
          for (String columnHeader : headers) {
            if (GEOMETRY_COLUMN_NAME.equals(columnHeader)) {
              useWKT = true;
              break;
            }
          }
          csvReader.close();
        }
      } catch (IOException e) {
        throw new RuntimeException("Could not read from CSV file", e);
      }
    }
    if (useWKT) {
      map.put("strategy", CSVDataStoreFactory.WKT_STRATEGY);
      map.put("wktField", GEOMETRY_COLUMN_NAME);
    } else {
      //Guess strategy is lat/long that attempts to infer the lat/long columns from file content
      map.put("strategy", CSVDataStoreFactory.GUESS_STRATEGY);
    }
  }

  private static SimpleFeatureSource openDataSource(String source, Map<String, Object> map,
      Optional<String> requestedType) {

    DataStore dataStore;
    String typeName;
    try {
      dataStore = DataStoreFinder.getDataStore(map);

      if (dataStore == null) {
        throw new RuntimeException(String.format("Could not read features from %s - is it in a supported format?",
            source));
      }
      typeName = requestedType.orElse(dataStore.getTypeNames()[0]);
    } catch (IOException e) {
      throw new RuntimeException(
          String.format("Could not extract features from %s, reason: %s", source, e.getMessage()), e);
    }

    FeatureSource<SimpleFeatureType, SimpleFeature> featureSource;
    try {
      featureSource = dataStore.getFeatureSource(typeName);

    } catch (IOException e) {
      throw new RuntimeException("Unhandled error trying to access features: %s", e);
    }

    return DataUtilities.simple(featureSource);
  }


}
