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

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

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import org.junit.Test;

import nz.org.riskscape.engine.Assert;
import nz.org.riskscape.engine.bind.Parameter;
import nz.org.riskscape.engine.bind.ParameterBindingException;
import nz.org.riskscape.engine.data.Bookmark;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.resource.Resource;
import nz.org.riskscape.engine.types.Floating;
import nz.org.riskscape.engine.types.Integer;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Text;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.TypeProblems;
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;
import nz.org.riskscape.engine.typeset.IdentifiedType;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.ExpressionProblems;

public class TypeBinderTest extends BaseBinderTest {

  Parameter typeParameter = Parameter.required("type", Type.class);
  Parameter structParameter = Parameter.required("struct", Struct.class);

  TypeBinder subject = new TypeBinder();

  @Test
  public void bindingToIdentifiedTypeReturnsUnderlyingType() {
    Struct underlyingType = Struct.of("foo", Types.TEXT);
    project.getTypeSet().add("foo", underlyingType);

    Type bound = bind("foo");
    assertThat(bound, is(underlyingType));

    // quotes get stripped off from identified types.
    assertThat(bind("'foo'"), is(underlyingType));
    assertThat(bind("\"foo\""), is(underlyingType));

    // using lookup works as well
    assertThat(bind("lookup('foo')"), is(underlyingType));
  }

  @Test
  public void cannotBindIdentifiedTypeToIncorrectType() {
    Struct underlyingType = Struct.of("foo", Types.TEXT);
    project.getTypeSet().add("foo", underlyingType);

    // and try to have a known identified type cast to some thing it isn't. we want to make sure this case,
    // however contrived, doesn't throw an unhandled class cast exception.
    assertThat(
      subject.bindValue(bindingContext, "foo", WithinRange.class), failedResult(
          hasAncestorProblem(equalTo(TypeProblems.get().mismatch("foo", WithinRange.class, Struct.class)))
      )
    );

    // same for lookup
    assertThat(
      subject.bindValue(bindingContext, "lookup('foo')", WithinRange.class), failedResult(
          hasAncestorProblem(equalTo(TypeProblems.get().mismatch("lookup('foo')", WithinRange.class, Struct.class)))
      )
    );
  }

  @Test
  public void canBindToSimpleType() {
    Type bound = bind("floating");
    assertThat(bound, is(Types.FLOATING));
  }

  @Test
  public void canBindToStruct() {
    Struct expected = Struct.of("foo", Types.TEXT);
    Type bound = bind("struct(foo: text)");
    assertThat(bound, is(expected));

    // can also bind this struct to a parameter that requires a struct type
    bound = bind("struct(foo: text)", structParameter);
    assertThat(bound, is(expected));
  }

  @Test
  public void canBindStrtuctIdentifiedTypeToStruct() {
    Struct expected = Struct.of("foo", Types.TEXT);
    CanonicalType fooType = project.getTypeSet().add("foo", expected);

    Type bound = bind("foo", structParameter);
    // we want the struct underlying type.
    assertThat(bound, is(expected));

    // same with lookup
    bound = bind("lookup('foo')", structParameter);
    assertThat(bound, is(expected));
  }

  @Test
  public void canBindWrappingTypeWhenUnderlyingIsRequired() {
    assertThat(
        subject.bindValue(context, "set(text, 'foo', 'bar')", Text.class),
        result(Types.TEXT)
    );

    assertThat(
        subject.bindValue(context, "range(floating, 10.0, 20.0)", Floating.class),
        result(Types.FLOATING)
    );

    // sanity check that if required is Type then you get what you give it
    assertThat(
        subject.bindValue(context, "range(floating, 10.0, 20.0)", Type.class),
        result(new WithinRange(Types.FLOATING, 10D, 20D))
    );
  }

  @Test
  public void canBindIdentifiedWrappingTypeWhenUnderlyingIsRequired() {
    project.getTypeSet().add("foo", new WithinSet(Types.TEXT, "foo", "bar"));

    // by id
    assertThat(
        subject.bindValue(context, "foo", Text.class),
        result(Types.TEXT)
    );

    // same with lookup
    assertThat(
        subject.bindValue(context, "lookup('foo')", Text.class),
        result(Types.TEXT)
    );
  }

  @Test
  public void canBindToIdentifiedType() {
    CanonicalType cType = project.getTypeSet().add("foo", new WithinSet(Types.TEXT, "foo", "bar"));

    // by id
    assertThat(
        subject.bindValue(context, "foo", IdentifiedType.class),
        result(cType)
    );

    // lookup returns the linked type (not the canonical)
    assertThat(
        subject.bindValue(context, "lookup('foo')", IdentifiedType.class),
        result(project.getTypeSet().getLinkedType("foo"))
    );
  }

  @Test
  public void bindingCanRequireWrappingType() {
    assertThat(
        subject.bindValue(context, "set(text, 'foo', 'bar')", WithinSet.class),
        result(new WithinSet(Types.TEXT, "foo", "bar"))
    );

    assertThat(
        subject.bindValue(context, "range(integer, 5, 10)", WithinRange.class),
        result(new WithinRange(Types.INTEGER, 5L, 10L))
    );
  }

  @Test
  public void cannotBindUnderlyingTypeWhenWrappingTypeIsRequired() {
    assertThat(
        subject.bindValue(context, "text", WithinSet.class),
        failedResult(
            hasAncestorProblem(equalTo(TypeProblems.get().mismatch("text", WithinSet.class, Text.class)))
        )
    );

    assertThat(
        subject.bindValue(context, "integer", WithinRange.class),
        failedResult(
            hasAncestorProblem(equalTo(TypeProblems.get().mismatch("integer", WithinRange.class, Integer.class)))
        )
    );
  }

  @Test
  public void cannotBindSimpleTypeToStructParameter() {
    ParameterBindingException ex = bindThrows("floating", structParameter);
    assertThat(ex.getProblem(), hasAncestorProblem(equalIgnoringChildren(
        TypeProblems.get().mismatch("floating", Struct.class, Floating.class)
    )));

    // add a simple identified type and see that binding to that fails as well.
    project.getTypeSet().add("foo", Types.FLOATING);
    ex = bindThrows("foo", structParameter);
    assertThat(ex.getProblem(), hasAncestorProblem(equalIgnoringChildren(
        TypeProblems.get().mismatch("foo", Struct.class, Floating.class)
    )));
  }

  @Test
  public void cannotBindToUnknownType() {
    ParameterBindingException ex = bindThrows("foo");
    assertThat(ex.getProblem(), hasAncestorProblem(equalIgnoringChildren(
        ExpressionProblems.get().notAValid(Type.class, "foo")
    )));
  }

  @Test
  public void cannotBindToInvalidType() {
    // add a linkded type, but this will blow up when the backing type is fetched
    project.getTypeSet().add("invalid", Resource.UNKNOWN, () -> ResultOrProblems.failed(Problem.error("boom")));
    ParameterBindingException ex = bindThrows("invalid");
    assertThat(ex.getProblem(), hasAncestorProblem(
        isError(GeneralProblems.class, "failedObjectLookedUp")
    ));

    ex = bindThrows("lookup('invalid')");
    assertThat(ex.getProblem(), hasAncestorProblem(
        isError(GeneralProblems.class, "failedObjectLookedUp")
    ));

    // the types in list shouldn't be quoted
    ex = bindThrows("list('text')");
    assertThat(ex.getProblem(), hasAncestorProblem(equalIgnoringChildren(
        ExpressionProblems.get().notAValid(Type.class, "list('text')")
    )));

    // enum only accepts constant values
    ex = bindThrows("enum('foo', bar)");
    assertThat(ex.getProblem(), hasAncestorProblem(equalIgnoringChildren(
        ExpressionProblems.get().notAValid(Type.class, "enum('foo', bar)")
    )));
  }

  @Test
  public void canBindToAllowedTypes() {
    assertThat(subject.canBind(String.class, Type.class), is(true));
    assertThat(subject.canBind(String.class, Text.class), is(true));
    assertThat(subject.canBind(String.class, Integer.class), is(true));
    assertThat(subject.canBind(String.class, Struct.class), is(true));
    assertThat(subject.canBind(String.class, IdentifiedType.class), is(true));
  }

  @Test
  public void cannotBindToNonTypes() {
    assertThat(subject.canBind(String.class, String.class), is(false));
    assertThat(subject.canBind(String.class, Bookmark.class), is(false));
  }

  private Type bind(String value) {
    return bind(value, typeParameter);
  }

  private Type bind(String value, Parameter parameter) {
    return (Type) subject.bind(context, parameter, value);
  }

  private ParameterBindingException bindThrows(String value) {
    return bindThrows(value, typeParameter);
  }

  private ParameterBindingException bindThrows(String value, Parameter parameter) {
    return Assert.assertThrows(ParameterBindingException.class, () -> bind(value, parameter));
  }

}
