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

import static org.junit.Assert.*;

import java.util.Collections;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.function.IdentifiedFunction;
import nz.org.riskscape.engine.function.IdentifiedFunction.Category;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.resource.Resource;
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.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.Expression;

public class StructConversionTest extends BaseExpressionRealizerTest {

  @Before
  public void setup() {
    project.getFunctionSet().insertFirst(DefaultOperators.INSTANCE);
  }

  @Test
  public void canConvertVariousConstantExpressionInToStructExpressions() throws Exception {
    assertEquals(tuple("{2 as integer}"), evaluate("2", Tuple.EMPTY_TUPLE));
    assertEquals(tuple("{2.0 as floating}"), evaluate("2.0", Tuple.EMPTY_TUPLE));
    assertEquals(tuple("{'foo' as text}"), evaluate("'foo'", Tuple.EMPTY_TUPLE));
    assertEquals(tuple("{}"), evaluate("*", Tuple.EMPTY_TUPLE));
    // should leave it alone
    assertEquals(tuple("{foo: 'bar'}"), evaluate("{foo: 'bar'}", Tuple.EMPTY_TUPLE));
    assertEquals(tuple("{list_integer: [1, 2, 3]}"), evaluate("[1, 2, 3]", Tuple.EMPTY_TUPLE));
  }

  @Test
  public void binaryExpressionsAreNamedAfterResultType() throws Exception {
    assertEquals(tuple("{integer: 4}"), evaluate("2 + 2", Tuple.EMPTY_TUPLE));
  }

  @Test
  public void propertyAccessExpressionsMemberNamedAfterPropertyExpression() throws Exception {
    assertEquals(tuple("{1 as foo}"), evaluate("foo", tuple("{foo: 1}")));
    assertEquals(tuple("{'baz' as bar}"), evaluate("foo.bar", tuple("{foo: {bar: 'baz'}}")));
    assertEquals(tuple("{'baz' as bar}"), evaluate("foo.bar", tuple("{foo: {bar: 'baz'}}")));
  }

  @Test
  public void aPropertyExpressionThatReturnsAStructIsLeftUnmolested() throws Exception {
    assertEquals(tuple("{bar: 'baz'}"), evaluate("foo", tuple("{foo: {bar: 'baz'}}")));
  }

  @Test
  public void aPropertyExpressionThatReturnsANullableStructIsWrapped() throws Exception {
    // the point of asStruct is so that a non-struct expression can be given by a user where a
    // struct type is required - so something like a nullable struct introduces extra complexity
    // for the calling code, so let's leave this for now while we gather our thoughts
    Tuple inner = tuple("{foo: 'bar'}");
    Tuple outer = Tuple.ofValues(Struct.of("baz", Nullable.of(inner.getStruct())), inner);

    assertEquals(outer, evaluate("baz", outer));
  }

  @Test
  public void aFunctionExpressionMembersNameIsNamedAfterIdent() throws Exception {
    RiskscapeFunction func = Mockito.mock(RiskscapeFunction.class);
    Mockito.when(func.getReturnType()).thenReturn(Types.TEXT);
    Mockito.when(func.getArgumentTypes()).thenReturn(Collections.emptyList());
    Mockito.when(func.call(Mockito.anyList())).thenReturn("baz");

    project.getFunctionSet().add(new IdentifiedFunction.Wrapping(func, "foo", "", Resource.UNKNOWN_URI, Category.MISC));

    assertEquals(tuple("{foo: 'baz'}"), evaluate("foo()", Tuple.EMPTY_TUPLE));
  }

  @Test
  public void aStructReturningFunctionReturnsAStruct() throws Exception {
    Tuple tuple = tuple("{bar: 'baz'}");
    RiskscapeFunction func = Mockito.mock(RiskscapeFunction.class);
    Mockito.when(func.getReturnType()).thenReturn(tuple.getStruct());
    Mockito.when(func.getArgumentTypes()).thenReturn(Collections.emptyList());
    Mockito.when(func.call(Mockito.anyList())).thenReturn(tuple);

    project.getFunctionSet().add(new IdentifiedFunction.Wrapping(func, "foo", "", Resource.UNKNOWN_URI, Category.MISC));

    assertEquals(tuple, evaluate("foo()", Tuple.EMPTY_TUPLE));
    assertSame(realized.getResultType(), tuple.getStruct());
  }

  @Override
  protected RealizedExpression realize(Type inputType, Expression anExpr) {
    ResultOrProblems<RealizedExpression> realizedOr = realizer.realize(inputType, anExpr);
    realizationProblems = realizedOr.getProblems();
    realized = realizedOr.map(rexpr -> realizer.asStruct(realizationContext, rexpr)).orElse(null);
    realizedOr.ifPresent(re -> re.getResultType().find(Struct.class).ifPresent(struct ->
      // it should already have been normalized - prove it by throwing in a different but equal struct and check we get
      // the OG back
      assertSame(struct, realizationContext.normalizeStruct(Struct.builder().addAll(struct).build()))
    ));

    return realized;
  }

}
