/*
 * 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.Assert.*;
import static nz.org.riskscape.engine.Matchers.*;
import static nz.org.riskscape.problem.StandardCodes.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import org.junit.Test;

import nz.org.riskscape.engine.bind.Parameter;
import nz.org.riskscape.engine.bind.ParameterBindingException;
import nz.org.riskscape.engine.types.TypeProblems;
import nz.org.riskscape.problem.Problem.Severity;
import nz.org.riskscape.rl.ExpressionParser;
import nz.org.riskscape.rl.ast.Constant;
import nz.org.riskscape.rl.ast.Expression;
import nz.org.riskscape.rl.ast.ExpressionProblems;
import nz.org.riskscape.rl.ast.PropertyAccess;
import nz.org.riskscape.rl.ast.StructDeclaration;

public class ExpressionBinderTest extends BaseBinderTest {

  static final Parameter ANY_EXPRESSION = Parameter.required("expression", Expression.class);
  static final Parameter CONSTANT_EXPRESSION = Parameter.required("expression", Constant.class);
  static final Parameter PROPERTY_EXPRESSION = Parameter.required("expression", PropertyAccess.class);

  ExpressionBinder binder = new ExpressionBinder();

  @Test
  public void canBind() {
    assertThat(binder.canBind(String.class, Expression.class), is(true));
    assertThat(binder.canBind(String.class, Constant.class), is(true));
    assertThat(binder.canBind(String.class, PropertyAccess.class), is(true));
  }

  @Test
  public void canBindConstants() {
    assertThat(binder.bind(context, ANY_EXPRESSION, "1"), instanceOf(Constant.class));
    assertThat(binder.bind(context, CONSTANT_EXPRESSION, "1"), instanceOf(Constant.class));

    assertThat(binder.bind(context, ANY_EXPRESSION, "'constant text'"), instanceOf(Constant.class));
    assertThat(binder.bind(context, CONSTANT_EXPRESSION, "'constant text'"), instanceOf(Constant.class));
  }

  @Test
  public void canBindPropertyExpressions() {
    assertThat(binder.bind(context, ANY_EXPRESSION, "foo"), instanceOf(PropertyAccess.class));
    assertThat(binder.bind(context, PROPERTY_EXPRESSION, "foo"), instanceOf(PropertyAccess.class));

    assertThat(binder.bind(context, ANY_EXPRESSION, "my_function().foo"), instanceOf(PropertyAccess.class));
    assertThat(binder.bind(context, PROPERTY_EXPRESSION, "my_function().foo"), instanceOf(PropertyAccess.class));
  }

  @Test
  public void canBindFromThingsOtherThanStrings() throws Exception {
    assertThat(binder.bindValue(context, 1.0, Expression.class).get(), equalTo(Constant.floating(1.0)));
    assertThat(binder.bindValue(context, 1.0D, Expression.class).get(), equalTo(Constant.floating(1.0)));
    assertThat(binder.bindValue(context, 1, Expression.class).get(), equalTo(Constant.integer(1)));
    assertThat(binder.bindValue(context, 1L, Expression.class).get(), equalTo(Constant.integer(1)));
    assertThat(binder.bindValue(context, true, Expression.class).get(), equalTo(Constant.TRUE));
    assertThat(binder.bindValue(context, false, Expression.class).get(), equalTo(Constant.FALSE));
  }

  @Test
  public void failsIfExpressionNotAllowedType() {
    assertThat(
      binder.bindValue(context, "1", PropertyAccess.class),
      failedResult(equalTo(TypeProblems.get().mismatch(
          ExpressionParser.parseString("1"),
          PropertyAccess.class,
          Constant.class
      )))
    );
  }

  @Test
  public void failsIfExpressionIsEmpty() {
    // this used to be a special case in the binder, but it's now a special case in the expression parser
    assertThat(
        binder.bindValue(context, "", Expression.class),
        failedResult(equalTo(ExpressionProblems.get().emptyStringNotValid()))
    );

    assertThat(
        binder.bindValue(context, "    \n \t  ", Expression.class),
        failedResult(equalTo(ExpressionProblems.get().emptyStringNotValid()))
    );
  }

  @Test
  public void badExpressionSyntaxResultsInParameterBindingException() {
    ParameterBindingException pbe = assertThrows(ParameterBindingException.class,
        () -> binder.bind(context, ANY_EXPRESSION, "= foo"));
    assertThat(pbe.getProblem(), isProblem(Severity.ERROR, PROBLEMS_FOUND, contains(
        equalIgnoringChildren(ExpressionProblems.get().malformedExpression("= foo")))
    ));
  }

  @Test
  public void canBindNormalStructDeclarations() {
    assertThat(
      binder.bindValue(context, "  { foo as bar, baz\n\t}\n", StructDeclaration.class).map(StructDeclaration::toSource),
      result("{foo as bar, baz}")
    );
  }

  @Test
  public void canBindStructDeclarationsWithoutBraces() {
    // as a convenience, we will put the braces on for you if you've forgotten them
    assertThat(
      binder.bindValue(context, "  foos + 1, baz(bar, bar, bar) \n", StructDeclaration.class)
       .map(StructDeclaration::toSource),
      result("{foos + 1, baz(bar, bar, bar)}")
    );
  }

  @Test
  public void canBindNestedStructDeclarationsWithoutBraces() {
    // we can have braces within the expression
    assertThat(
      binder.bindValue(context, "{foo: bar} as baz", StructDeclaration.class)
       .map(StructDeclaration::toSource),
      result("{{foo: bar} as baz}")
    );

    // the other way around, too
    assertThat(
      binder.bindValue(context, "baz: {foo: bar} ", StructDeclaration.class)
       .map(StructDeclaration::toSource),
      result("{baz: {foo: bar}}")
    );

    // now a bit more complex - NB we used to not allow this, but it was dubious rationale - i think if we've explicitly
    // asked the user for a struct and they leave the braces off, then we can just put them back on for them
    assertThat(
        binder.bindValue(context, "{foo: bar} as baz, {baz: bar} as foo", StructDeclaration.class)
         .map(StructDeclaration::toSource),
        result("{{foo: bar} as baz, {baz: bar} as foo}")
      );
  }

}
