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

import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;

import static nz.org.riskscape.engine.Matchers.*;

import org.geotools.geometry.jts.ReferencedEnvelope;
import org.junit.Before;
import org.junit.Test;

import nz.org.riskscape.engine.GeometryMatchers;
import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.RelationMatchers;
import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.TupleMatchers;
import nz.org.riskscape.engine.function.StringFunctions;
import nz.org.riskscape.engine.gt.GeometryHelper;
import nz.org.riskscape.engine.rl.DefaultOperators;
import nz.org.riskscape.engine.rl.GeometryFunctions;
import nz.org.riskscape.engine.rl.LanguageFunctions;
import nz.org.riskscape.engine.rl.LogicFunctions;
import nz.org.riskscape.engine.rl.MathsFunctions;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Referenced;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;

public class RelationBestTypeInferrerTest extends ProjectTest {

  RelationBestTypeInferrer inferrer = new RelationBestTypeInferrer(realizationContext);
  GeometryHelper latLongGeometryHelper = GeometryHelper.latLong(project.getSridSet());

  @Before
  public void setup() throws Exception {
    project.getFunctionSet().insertFirst(DefaultOperators.INSTANCE);
    project.getFunctionSet().addAll(LanguageFunctions.FUNCTIONS);
    project.getFunctionSet().addAll(LogicFunctions.LOGIC_FUNCTIONS);
    project.getFunctionSet().addAll(new GeometryFunctions(engine).getFunctions());
    project.getFunctionSet().addAll(MathsFunctions.FUNCTIONS);
    project.getFunctionSet().addAll(StringFunctions.FUNCTIONS);
  }

  @Test
  public void doesNotInferFromNonTextColumns() {
    ListRelation rel = new ListRelation(tuples("[{foo: 3, bar: 3.5}]"));
    assertThat(inferrer.infer(rel), Matchers.isEmptyOptional());
  }

  @Test
  public void doesNotInferIfSomeColumnsHaveNonNumeric() {
    ListRelation rel = new ListRelation(tuples("[{foo: '3', bar: 3.5}, {foo: 'four', bar: 4.0}]"));
    assertThat(inferrer.infer(rel), Matchers.isEmptyOptional());
  }

  @Test
  public void willProjectNumericStringsToNumericTypes() {
    assertThat(
        infer(new ListRelation(tuples("[{foo: '3', bar: '3.5'}, {foo: '4', bar: '4.0'}]"))),
        RelationMatchers.relationWithTuples(
            tuple("{foo: 3.0, bar: 3.5}"),
            tuple("{foo: 4.0, bar: 4.0}")
        )
    );
  }

  @Test
  public void willProjectNumericStringsToNumericTypesWithQuotedAttributes() {
    Struct expected = Struct.of("foo bar", Types.FLOATING);
    assertThat(
        infer(new ListRelation(tuples("[{\"foo bar\": '3'}, {\"foo bar\": '4'}]"))),
        RelationMatchers.relationWithTuples(
            tupleOfType(expected, "{\"foo bar\": 3.0}"),
            tupleOfType(expected, "{\"foo bar\": 4.0}")
        )
    );
  }

  @Test
  public void willProjectNumericStringsToNullableNumericTypesWithQuotedAttributes() {
    Struct expected = Struct.of("foo bar", Nullable.FLOATING);
    assertThat(
        infer(new ListRelation(tuples("[{\"foo bar\": '3'}, {\"foo bar\": null_of('text')}]"))),
        RelationMatchers.relationWithTuples(
            tupleOfType(expected, "{\"foo bar\": 3.0}"),
            tupleOfType(expected, "{\"foo bar\": null_of('floating')}")
        )
    );
  }

  @Test
  public void willProjectNumericStringsToNullableNumericTypes() {
    Struct expected = Struct.of("foo", Nullable.FLOATING, "bar", Types.FLOATING);
    assertThat(
        infer(new ListRelation(tuples("[{foo: '3', bar: '3.5'}, {foo: '', bar: '4.0'}]"))),
        RelationMatchers.relationWithTuples(
            tupleOfType(expected, "{foo: 3.0, bar: 3.5}"),
            tupleOfType(expected, "{foo: null_of('floating'), bar: 4.0}")
        )
    );
  }

  @Test
  public void willProjectNumericStringsWithNullValueToNullableNumericTypes() {
    // similar to above test but in this one the input is null text (rather than empty string)
    Struct inputType = Struct.of("foo", Nullable.TEXT, "bar", Types.FLOATING);
    Struct expected = Struct.of("foo", Nullable.FLOATING, "bar", Types.FLOATING);
    assertThat(
        infer(new ListRelation(tuples(inputType, "['3', '3.5']", "[null_of('text'), '4.0']"))),
        RelationMatchers.relationWithTuples(
            tupleOfType(expected, "{foo: 3.0, bar: 3.5}"),
            tupleOfType(expected, "{foo: null_of('floating'), bar: 4.0}")
        )
    );
  }

  @Test
  public void findsLatLongAttributesInDifferentForms() {
    doLatLongTest("lat", "long");
    doLatLongTest("lat", "lon");
    doLatLongTest("latitude", "longitude");
    // mixed case don't matter
    doLatLongTest("LatiTude", "LongiTude");
  }

  void doLatLongTest(String latAttr, String longAttr) {
    Struct expected = Struct.of(
        latAttr, Types.FLOATING,
        longAttr, Types.FLOATING,
        "geometry", Referenced.of(Types.POINT, SRIDSet.EPSG4326_LATLON)
    );
    assertThat(
        infer(new ListRelation(tuples(String.format("[{%s: '3', %s: '3.5'}]", latAttr, longAttr)))),
        allOf(
            RelationMatchers.relationWithType(expected),
            RelationMatchers.relationWithTuples(contains(
                TupleMatchers.tupleWithValue("geometry", allOf(
                    // ensure the SRID is set correctly otherwise reprojections etc won't work
                    GeometryMatchers.geometryWithSrid(project.getSridSet().get(SRIDSet.EPSG4326_LATLON)),
                    GeometryMatchers.isGeometry(latLongGeometryHelper.point(3, 3.5))
                ))
            ))
        )
    );
  }

  @Test
  public void willCreateNullableGeometryIfLatIsNullable() {
    Struct expected = Struct.of(
        "lat", Nullable.FLOATING,
        "lon", Types.FLOATING,
        "geometry", Nullable.of(Referenced.of(Types.POINT, SRIDSet.EPSG4326_LATLON))
    );
    Relation inferred = infer(new ListRelation(tuples("[{lat: '', lon: '3.5'}, {lat: '4', lon: '3.5'}]")));
    assertThat(
        inferred,
        allOf(
            RelationMatchers.relationWithType(expected),
            RelationMatchers.relationWithTuples(contains(
                is(Tuple.ofValues(expected, null, 3.5D, null)),
                TupleMatchers.tupleWithValue("geometry", allOf(
                    // ensure the SRID is set correctly otherwise reprojections etc won't work
                    GeometryMatchers.geometryWithSrid(project.getSridSet().get(SRIDSet.EPSG4326_LATLON)),
                    GeometryMatchers.isGeometry(latLongGeometryHelper.point(4, 3.5))
                ))
            ))
        )
    );
    // spatial metadata is set (required to calc relation bounds)
    assertThat(inferred.getSpatialMetadata().map(SpatialMetadata::getCrs), isPresent(SRIDSet.EPSG4326_LATLON));
    assertThat(
        inferred.calculateBounds(),
        // only one geom so bounds is a point
        isPresent(new ReferencedEnvelope(4D, 4D, 3.5D, 3.5D, SRIDSet.EPSG4326_LATLON))
    );
  }

  @Test
  public void willCreateGeometryIfAttributesContainingLatitudeAndLongitudeAreFound() {
    Struct expected = Struct.of(
        "annoying_prefix_latitude", Types.FLOATING,
        "longiTUDE_annoying_suffix", Types.FLOATING,
        "geometry", Referenced.of(Types.POINT, SRIDSet.EPSG4326_LATLON)
    );
    Relation inferred = infer(new ListRelation(
        // there's an annoying mix of case here to show that doesn't matter
        tuples("[{annoying_prefix_latitude: '4', longiTUDE_annoying_suffix: '3.5'}]")
    ));
    assertThat(
        inferred,
        allOf(
            RelationMatchers.relationWithType(expected),
            RelationMatchers.relationWithTuples(contains(
                TupleMatchers.tupleWithValue("geometry", allOf(
                    // ensure the SRID is set correctly otherwise reprojections etc won't work
                    GeometryMatchers.geometryWithSrid(project.getSridSet().get(SRIDSet.EPSG4326_LATLON)),
                    GeometryMatchers.isGeometry(latLongGeometryHelper.point(4, 3.5))
                ))
            ))
        )
    );
  }

  @Test
  public void willNotCreateGeometryIfLatLongNotNumeric() {
    Struct expected = Struct.of(
        "lat", Types.TEXT,
        "lon", Types.FLOATING
    );
    assertThat(
        infer(new ListRelation(tuples("[{lat: 'four', lon: '3.5'}, {lat: '4', lon: '3.5'}]"))),
        allOf(
            RelationMatchers.relationWithType(expected),
            RelationMatchers.relationWithTuples(
                is(tuples("[{lat: 'four', lon: 3.5}, {lat: '4', lon: 3.5}]"))
            )
        )
    );
  }

  @Test
  public void willCreateNullableGeometryIfLonIsNullable() {
    Struct expected = Struct.of(
        "lat", Types.FLOATING,
        "lon", Nullable.FLOATING,
        "geometry", Nullable.of(Referenced.of(Types.POINT, SRIDSet.EPSG4326_LATLON))
    );
    assertThat(
        infer(new ListRelation(tuples("[{lat: '3.5', lon: ''}, {lat: '4', lon: '3.5'}]"))),
        allOf(
            RelationMatchers.relationWithType(expected),
            RelationMatchers.relationWithTuples(contains(
                is(Tuple.ofValues(expected, 3.5D, null, null)),
                TupleMatchers.tupleWithValue("geometry", allOf(
                    // ensure the SRID is set correctly otherwise reprojections etc won't work
                    GeometryMatchers.geometryWithSrid(project.getSridSet().get(SRIDSet.EPSG4326_LATLON)),
                    GeometryMatchers.isGeometry(latLongGeometryHelper.point(4, 3.5))
                ))
            ))
        )
    );
  }

  @Test
  public void canMakeNumbericLatLongToGeoemtryWithOutRelationScan() {
    Struct expected = Struct.of(
        "lat", Types.FLOATING,
        "lon", Types.FLOATING,
        "geometry", Referenced.of(Types.POINT, SRIDSet.EPSG4326_LATLON)
    );
    assertThat(
        // we use an empty relation in this test to prove that a data scan is not necessary to infer
        // geometry if the lat/long are already numeric types.
        // This could be useful in the future if we want to make use of this in NetCDR/HDF5 but we'd want
        // to add other modes so the relation scan is not applied in that case.
        infer(new EmptyRelation(Struct.of("lat", Types.FLOATING, "lon", Types.FLOATING))),
        RelationMatchers.relationWithType(expected)
    );
  }

  @Test
  public void willNotCreateGeometryIfAttributeAlreadyExists() {
    Struct expected = Struct.of(
        "lat", Types.FLOATING,
        "lon", Types.FLOATING,
        "geometry", Types.TEXT
    );
    assertThat(
        infer(new ListRelation(tuples("[{lat: '3.5', lon: '2.5', geometry: 'POINT(1 3)'}]"))),
        RelationMatchers.relationWithTuples(contains(
            is(Tuple.ofValues(expected, 3.5D, 2.5, "POINT(1 3)"))
        ))
    );
  }

  @Test
  public void willNotCreateGeometryIfGeometryTypeAlreadyPresent() {
    Struct expected = Struct.of(
        "lat", Types.FLOATING,
        "lon", Types.FLOATING,
        "g", Types.GEOMETRY
    );
    assertThat(
        infer(new ListRelation(tuples("[{lat: '3.5', lon: '2.5', g: geom_from_wkt('POINT(1 3)', 'EPSG:4326')}]"))),
        RelationMatchers.relationWithTuples(contains(
            // lat/lon columns are converted to numeric, but g is left alone, and no additional geometries added.
            is(Tuple.ofValues(expected, 3.5D, 2.5D, latLongGeometryHelper.point(1, 3)))
        ))
    );
  }

  private Relation infer(Relation source) {
    return inferrer.infer(source).get().get();
  }

}
