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

import static org.hamcrest.Matchers.*;

import org.junit.Test;

import static org.junit.Assert.*;

import java.util.regex.PatternSyntaxException;

import com.google.common.collect.Range;

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.problem.ProblemMatchers;
import nz.org.riskscape.engine.rl.BaseExpressionRealizerTest;
import nz.org.riskscape.engine.rl.LanguageFunctions;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.RSList;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.TypeProblems;
import nz.org.riskscape.engine.types.Types;

public class SelectFunctionTest extends BaseExpressionRealizerTest {

  public SelectFunctionTest() {
    project.getFunctionSet().addAll(LanguageFunctions.FUNCTIONS);
    project.getFunctionSet().add(new SelectFunction().identified("select_attr"));
  }

  @Test
  public void canSelectAttributesStartingWith() {
    assertThat(
        evaluateConstant("select_attr({loss1: 100, loss2: 200, hazard: 33}, '^loss')"),
        is(tuple("{loss1: 100, loss2: 200}"))
    );
  }

  @Test
  public void noMatchesIsWarned() {
    assertThat(
        evaluateConstant("select_attr({loss1: 100, loss2: 200, hazard: 33}, '^Loss')"),
        is(tuple("{}"))
    );

    assertThat(sunkProblems, contains(Matchers.hasAncestorProblem(
        SelectFunction.PROBLEMS.noAttributesMatched("^Loss",
            Struct.of("loss1", Types.INTEGER, "loss2", Types.INTEGER, "hazard", Types.INTEGER))
    )));
  }

  @Test
  public void canSelectAttributesEndingWith() {
    assertThat(
        evaluateConstant("select_attr({loss1: 100, loss2: 200, hazard: 33}, '[a-z]+$')"),
        is(tuple("{hazard: 33}"))
    );
  }

  @Test
  public void canSelectAndReplaceAttributes() {
    assertThat(
        evaluateConstant("select_attr({loss1: 1, loss2: 2}, '(loss)', ['my_loss'])"),
        is(tuple("{my_loss1: 1, my_loss2: 2}"))
    );
  }

  @Test
  public void canReplaceOptionalCaptureGroups() {
    assertThat(
        evaluateConstant("select_attr({foobarbaz: 22}, '(foo)(bar)?(baz)', ['FOO', 'BAR', 'BAZ'])"),
        is(tuple("{FOOBARBAZ: 22}"))
    );

    assertThat(
        evaluateConstant("select_attr({foobaz: 22}, '(foo)(bar)?(baz)', ['FOO', 'BAR', 'BAZ'])"),
        is(tuple("{FOOBAZ: 22}"))
    );

    assertThat(
        evaluateConstant("select_attr({foobarbaz: 22}, '(foo)(bar)*(baz)', ['FOO', 'BAR', 'BAZ'])"),
        is(tuple("{FOOBARBAZ: 22}"))
    );

    assertThat(
        evaluateConstant("select_attr({foobarbarbarbarbaz: 22}, '(foo)((?:bar)*)(baz)', ['FOO', 'BAR', 'BAZ'])"),
        is(tuple("{FOOBARBAZ: 22}"))
    );
  }

  @Test
  public void nullSafeWrapperIsApplied() {
    Struct childType = Struct.of("foo", Types.TEXT);
    Struct parentType = Struct.of("child", Nullable.of(childType));

    realize(parentType, parse("select_attr(child, '^(f)', ['F'])"));
    assertThat(realized.getResultType(), is(Nullable.of(Struct.of("Foo", Types.TEXT))));

    assertThat(realized.evaluate(Tuple.ofValues(parentType)), nullValue());
    assertThat(
        realized.evaluate(Tuple.ofValues(parentType, Tuple.ofValues(childType, "bar"))),
        is(tuple("{Foo: 'bar'}"))
    );
  }

  @Test
  public void cannotReplaceWithNullValue() {
    // it makes no sense to replace a capture group with a null value. this test is to ensure that the
    // type system/arg checking prevents this from getting to the function itself.
    assertThat(
        realizeOnly("select_attr({loss1: 1, loss2: 2}, '(loss)', [null_of('text')])", Struct.EMPTY_STRUCT),
        Matchers.failedResult(Matchers.hasAncestorProblem(
            ProblemMatchers.isProblem(TypeProblems.class, (r, p) -> p.mismatch(r.any(),
                r.eq(Nullable.of(RSList.create(Types.TEXT))), r.eq(RSList.create(Nullable.TEXT)))
            ))
        )
    );
  }

  @Test
  public void errorWhenDuplicateAttributesGenerated() {
    assertThat(
        realizeOnly("select_attr({foo1: 'foos', bar1: 2}, '(foo|bar)', [''])", Struct.EMPTY_STRUCT),
        Matchers.failedResult(Matchers.hasAncestorProblem(
            SelectFunction.PROBLEMS.duplicateKeyGenerated("bar1", "1", Struct.of("1", Types.TEXT))
        ))
    );
  }

  @Test
  public void errorWhenPatternInvalid() {
    assertThat(
        realizeOnly("select_attr({foo1: 'foos', bar1: 2}, '(foo|bar', [''])", Struct.EMPTY_STRUCT),
        Matchers.failedResult(Matchers.hasAncestorProblem(
            Matchers.isProblem(PatternSyntaxException.class)
        ))
    );
  }

  @Test
  public void excessGroupReplacementsAreWarned() {
    assertThat(
        evaluateConstant("select_attr({loss1: 1, loss2: 2}, '(loss)', ['my_loss', 'ignored'])"),
        is(tuple("{my_loss1: 1, my_loss2: 2}"))
    );
    assertThat(sunkProblems, contains(Matchers.hasAncestorProblem(
        SelectFunction.PROBLEMS.captureGroupMismatch(1, 2)
    )));
  }

  @Test
  public void replacementsWithNoCaptureGroupsIsWarned() {
    assertThat(
        evaluateConstant("select_attr({loss1: 1, loss2: 2}, 'loss', ['my_loss', 'ignored'])"),
        is(tuple("{loss1: 1, loss2: 2}"))
    );
    assertThat(sunkProblems, contains(Matchers.hasAncestorProblem(
        SelectFunction.PROBLEMS.captureGroupMismatch(0, 2)
    )));
  }

  @Test
  public void capatureGroupsWithNoReplacementsIsWarned() {
    assertThat(
        evaluateConstant("select_attr({loss1: 1, loss2: 2}, '(loss)')"),
        is(tuple("{loss1: 1, loss2: 2}"))
    );
    assertThat(sunkProblems, contains(Matchers.hasAncestorProblem(
        SelectFunction.PROBLEMS.captureGroupMismatch(1, 0)
    )));
  }

  @Test
  public void errorIfReplacementsNotListOfStrings() {
    assertThat(
        realizeOnly("select_attr({foo1: 'foos'}, '(foo)', [2])", Struct.EMPTY_STRUCT),
        Matchers.failedResult(Matchers.hasAncestorProblem(
            ProblemMatchers.isProblem(TypeProblems.class, (r, p) -> p.mismatch(
                r.any(), r.eq(Nullable.of(RSList.create(Types.TEXT))), r.eq(RSList.create(Types.INTEGER))
            ))
        ))
    );

    assertThat(
        realizeOnly("select_attr({foo1: 'foos'}, '(foo)', 'bar')", Struct.EMPTY_STRUCT),
        Matchers.failedResult(Matchers.hasAncestorProblem(
            ProblemMatchers.isProblem(TypeProblems.class, (r, p) -> p.mismatch(
                r.any(), r.eq(Nullable.of(RSList.create(Types.TEXT))), r.eq(Types.TEXT)
            ))
        ))
    );
  }

  @Test
  public void errorIfWrongArgCount() {
    assertThat(
        realizeOnly("select_attr({foo1: 'foos'}, '(foo)', ['bar'], 'excess')", Struct.EMPTY_STRUCT),
        Matchers.failedResult(Matchers.hasAncestorProblem(
            ArgsProblems.get().wrongNumber(Range.closed(2, 3), 4)
        ))
    );

    assertThat(
        realizeOnly("select_attr({foo1: 'foos'})", Struct.EMPTY_STRUCT),
        Matchers.failedResult(Matchers.hasAncestorProblem(
            ArgsProblems.get().wrongNumber(Range.closed(2, 3), 1)
        ))
    );
  }

}
