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

import static nz.org.riskscape.engine.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

import org.junit.Test;

import nz.org.riskscape.engine.PluginProjectTest;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.relation.UnexpectedNullValueException;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.engine.types.WithinRange;
import nz.org.riskscape.engine.types.WithinSet;
import nz.org.riskscape.engine.typeset.CanonicalType;

public class CPythonSerializerTest extends PluginProjectTest {

  CPythonSerializer serializer = new CPythonSerializer();

  private Object serialize(Object value, Type type) throws Exception {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    serializer.serialize(dos, type, value);
    return CPythonSerializer.nullSafeType(type).fromBytes(
        new DataInputStream(new ByteArrayInputStream(bos.toByteArray())));
  }

  private Tuple serialize(Tuple value, Type type) throws Exception {
    return (Tuple) serialize((Object) value, type);
  }

  @Test
  public void serializesBooleanNullValueSafely() throws Exception {
    assertThat(serialize(true, Types.BOOLEAN), is(true));
    assertThat(serialize(true, Nullable.BOOLEAN), is(true));
    assertThat(serialize(null, Types.BOOLEAN), is(nullValue()));
  }

  @Test
  public void serializesTextNullValueSafely() throws Exception {
    assertThat(serialize("one", Types.TEXT), is("one"));
    assertThat(serialize("two", Nullable.TEXT), is("two"));
    assertThat(serialize(null, Types.TEXT), is(nullValue()));
  }

  @Test
  public void serializesNumberNullValueSafely() throws Exception {
    assertThat(serialize(20L, Types.INTEGER), is(20L));
    assertThat(serialize(20L, Nullable.INTEGER), is(20L));
    assertThat(serialize(null, Types.INTEGER), is(nullValue()));

    assertThat(serialize(10.0D, Types.FLOATING), is(10.0D));
    assertThat(serialize(10.0D, Nullable.FLOATING), is(10.0D));
    assertThat(serialize(null, Types.FLOATING), is(nullValue()));
  }

  @Test
  public void serializesWrappedTypeNullValueSafely() throws Exception {
    assertThat(serialize(null, new WithinRange(Types.FLOATING, 0.0D, 10.0D)), is(nullValue()));
    assertThat(serialize(null, new WithinSet(Types.INTEGER, 0L, 10L, 20L)), is(nullValue()));
    assertThat(serialize(null, new WithinSet(Types.TEXT, "one", "two", "three")), is(nullValue()));
  }

  @Test
  public void serializesStructNullValueSafely() throws Exception {
    Struct struct = Struct.of("foo", Types.TEXT, "bar", Types.INTEGER, "baz", Types.FLOATING);
    Tuple tuple = Tuple.ofValues(struct, "one", 2L, 3.0D);
    assertThat(serialize(tuple, struct).toArray(), is(tuple.toArray()));

    Tuple tupleWithNulls = Tuple.ofValues(struct, null, null, null);
    assertThat(serialize(tupleWithNulls, struct).toArray(), is(tupleWithNulls.toArray()));

    Tuple tupleWithOneNull = Tuple.ofValues(struct, "one", 2L, null);
    assertThat(serialize(tupleWithOneNull, struct).toArray(), is(tupleWithOneNull.toArray()));
  }

  @Test
  public void serializesIdentifiedTypeNullValueSafely() throws Exception {
    Struct struct = Struct.of("bar", Types.INTEGER, "baz", Types.FLOATING);
    CanonicalType fooType = project.getTypeSet().add("foo", struct);
    Tuple tuple = Tuple.ofValues(struct, 10L, 3.14D);
    assertThat(serialize(tuple, fooType).toArray(), is(tuple.toArray()));

    Tuple tupleWithNull = Tuple.ofValues(struct, 10L, null);
    assertThat(serialize(tupleWithNull, fooType).toArray(), is(tupleWithNull.toArray()));
  }

  @Test
  public void cannotSerializeNullableStructNullValues() throws Exception {
    // TODO Nullable[Struct] currently is not supported, purely for simplicity.
    // This could still happen when the hazard-layer is vector data, but we probably shouldn't
    // pass null hazard values to the risk function, so the user should fix this up themselves
    Struct nested = Struct.of("bar", Types.INTEGER, "baz", Types.FLOATING);
    Struct struct = Struct.of("foo", Nullable.of(nested));
    Tuple tuple = Tuple.ofValues(struct, Tuple.ofValues(nested, 1, null));
    assertThrows(UnexpectedNullValueException.class, () -> serialize(tuple, struct));
  }

  @Test
  public void usesNullSafeTypesForSerialization() {
    assertThat(CPythonSerializer.nullSafeType(Types.INTEGER), is(Nullable.INTEGER));
    assertThat(CPythonSerializer.nullSafeType(Types.FLOATING), is(Nullable.FLOATING));
    assertThat(CPythonSerializer.nullSafeType(Types.BOOLEAN), is(Nullable.BOOLEAN));

    Struct struct = Struct.of("foo", Types.FLOATING, "bar", Types.INTEGER);
    Struct expected = Struct.of("foo", Nullable.FLOATING, "bar", Nullable.INTEGER);
    assertThat(CPythonSerializer.nullSafeType(struct), is(expected));
  }

  public void unsupportedTypesAreUnalteredForSerialization() {
    // unsupported types in CPython
    assertThat(CPythonSerializer.nullSafeType(Types.DECIMAL), is(Types.DECIMAL));
    assertThat(CPythonSerializer.nullSafeType(Types.DATE), is(Types.DATE));
    // geometry should never be null
    assertThat(CPythonSerializer.nullSafeType(Types.GEOMETRY), is(Types.GEOMETRY));

    // for simplicity, we don't support null-safe members if the struct itself is nullable
    Type nullableStruct = Nullable.of(Struct.of("foo", Types.FLOATING));
    assertThat(CPythonSerializer.nullSafeType(nullableStruct), is(nullableStruct));
  }
}
