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

import java.util.Objects;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.hamcrest.TypeSafeDiagnosingMatcher;

import nz.org.riskscape.rl.ast.AST;
import nz.org.riskscape.rl.ast.FunctionCall;
import nz.org.riskscape.rl.ast.GenericArgument;
import nz.org.riskscape.rl.ast.InputChain;
import nz.org.riskscape.rl.ast.StepChain;
import nz.org.riskscape.rl.ast.StepDeclaration;
import nz.org.riskscape.rl.ast.StepDefinition;
import nz.org.riskscape.rl.ast.StepLink;
import nz.org.riskscape.rl.ast.StepReference;

public class PipelineASTMatchers {

  public static Matcher<GenericArgument<?>> isAnonArg(
      Class<? extends AST> expectedType,
      String expectedSource
  ) {
    return keywordArg(null, expectedType, expectedSource);
  }

  public static Matcher<GenericArgument<?>> isAnonArg(
      Class<? extends AST> expectedType,
      Matcher<? extends AST> argMatcher
  ) {
    return keywordArg(null, expectedType, argMatcher);
  }


  public static Matcher<GenericArgument<?>> keywordArg(
      String expectedKeyword,
      Class<? extends AST> expectedClass,
      String expectedSource
  ) {

    return keywordArg(expectedKeyword, expectedClass, hasSource(expectedSource));
  }

  public static Matcher<GenericArgument<?>> keywordArg(
      String expectedKeyword,
      Class<? extends AST> expectedClass,
      Matcher<? extends AST> argMatcher
  ) {

    return new TypeSafeDiagnosingMatcher<GenericArgument<?>>(GenericArgument.class) {

      @Override
      public void describeTo(Description description) {
        if (expectedKeyword == null) {
          description.appendText("anonymous arg ");
        } else {
          description.appendText("keyword arg ").appendValue(expectedKeyword);
        }
        description
          .appendText(" of type ").appendValue(expectedClass);

        argMatcher.describeTo(description);
      }

      @Override
      protected boolean matchesSafely(GenericArgument<?> item, Description mismatchDescription) {
        boolean matches = true;

        if (!Objects.equals(item.getName().orElse(null), expectedKeyword)) {
          matches = false;
          mismatchDescription.appendText(" had keyword ").appendValue(item.getName().orElse(null));
        }

        if (!item.getValue().getClass().equals(expectedClass)) {
          matches = false;
          mismatchDescription.appendText(" was type ").appendValue(item.getValue().getClass());
        }

        argMatcher.describeMismatch(item.getValue(), mismatchDescription);
        matches &= argMatcher.matches(item.getValue());

        return matches;
      }
    };
  }

  public static Matcher<AST> hasSource(
      String expectedSource
  ) {

    Matcher<String> sourceMatcher = Matchers.equalToCompressingWhiteSpace(expectedSource);

    return new TypeSafeDiagnosingMatcher<AST>(AST.class) {

      @Override
      public void describeTo(Description description) {
          description.appendText(" has source ").appendValue(expectedSource);
      }

      @Override
      protected boolean matchesSafely(AST item, Description mismatchDescription) {
        mismatchDescription.appendText(item.toSource());
        return sourceMatcher.matches(item.toSource());
      }
    };
  }


  public static Matcher<StepDeclaration> isStepDefinition(String expectedStepId) {
    return isStepDefinition(expectedStepId, null, null);
  }

  public static Matcher<StepDeclaration> isStepDefinition(String expectedStepId, String expectedName) {
    return isStepDefinition(expectedStepId, expectedName, null);
  }

  public static Matcher<StepDeclaration> isStepDefinition(
      String expectedStepId,
      String expectedName,
      Matcher<? extends Iterable<? extends FunctionCall.Argument>> argsMatcher
  ) {
    return isStepDefinition(expectedStepId, expectedName, argsMatcher, null);
  }

  public static Matcher<StepDeclaration> isStepDefinition(
      String expectedStepId,
      String expectedName,
      Matcher<? extends Iterable<? extends FunctionCall.Argument>> argsMatcher,
      String expectedInputName
  ) {
    return new TypeSafeDiagnosingMatcher<StepDeclaration>(StepDeclaration.class) {

      @Override
      public void describeTo(Description description) {
        description.appendText("step with id").appendValue(expectedStepId);
        if (expectedName != null) {
          description.appendText(" and name ").appendValue(expectedName);
        } else {
          description.appendText(" and no name");
        }

        if (argsMatcher != null) {
          description.appendText("and arguments ").appendDescriptionOf(argsMatcher);
        }

        if (expectedInputName != null) {
          description.appendText(" and input ").appendValue(expectedInputName);
        }
      }

      @Override
      protected boolean matchesSafely(StepDeclaration item, Description mismatchDescription) {
        if (item instanceof StepDefinition) {
          StepDefinition ref = (StepDefinition) item;
          boolean matches = true;
          if (!ref.getStepId().equals(expectedStepId)) {
            mismatchDescription.appendText(" definition id was ").appendValue(ref.getStepId());
            matches = false;
          }

          String actualName = ref.getName().orElse(null);
          if (expectedName == null) {
            if (actualName != null) {
              mismatchDescription.appendText(" definition had a name").appendValue(actualName);
              matches = false;
            }
          } else if (!actualName.equals(expectedName)) {
            mismatchDescription.appendText(" definition name was ").appendValue(actualName);
            matches = false;
          }

          if (argsMatcher != null && !argsMatcher.matches(ref.getArguments())) {
            mismatchDescription.appendText(" step with parameters ");
            argsMatcher.describeMismatch(ref.getArguments(), mismatchDescription);
            matches = false;
          }

          if (!Objects.equals(expectedInputName, ref.getNamedInput().orElse(null))) {
            matches = false;
            mismatchDescription.appendText(" input name was ").appendValue(ref.getNamedInput().orElse(null));
          }

          return matches;
        } else {
          mismatchDescription.appendText("not a definition, was a reference: ").appendValue(item);
          return false;
        }
      }
    };
  }

  public static Matcher<InputChain> isInputChain(Matcher<StepChain> chainMatcher) {
    return new TypeSafeDiagnosingMatcher<InputChain>() {

      @Override
      public void describeTo(Description describeTo) {
        describeTo.appendText("step chain input of ").appendDescriptionOf(chainMatcher);
      }

      @Override
      protected boolean matchesSafely(InputChain input, Description mismatchDescription) {
        mismatchDescription.appendText("step chain input with ");
        chainMatcher.describeMismatch(input, mismatchDescription);

        return chainMatcher.matches(input.getChain());
      }
    };
  }

  public static Matcher<StepChain> isChainWith(Matcher<? extends Iterable<? extends StepDeclaration>> stepsMatcher) {
    return new TypeSafeDiagnosingMatcher<StepChain>(StepChain.class) {

      @Override
      public void describeTo(Description description) {
        description.appendText("chain with ").appendDescriptionOf(stepsMatcher);
      }

      @Override
      protected boolean matchesSafely(StepChain item, Description mismatchDescription) {
        mismatchDescription.appendText("was chain with steps ").appendValue(item.getSteps());
        return stepsMatcher.matches(item.getSteps());
      }
    };
  }

  public static Matcher<StepDeclaration> isStepReference(String expectedStepName) {
    return isStepReference(expectedStepName, null);
  }

  public static Matcher<StepDeclaration> isStepReference(String expectedStepName, String expectedInputName) {
    return new TypeSafeDiagnosingMatcher<StepDeclaration>(StepDeclaration.class) {

      @Override
      public void describeTo(Description description) {
        description.appendText("step reference to ").appendValue(expectedStepName);

        if (expectedInputName != null) {
          description.appendText(" and input ").appendValue(expectedInputName);
        }
      }

      @Override
      protected boolean matchesSafely(StepDeclaration item, Description mismatchDescription) {
        if (item instanceof StepReference) {
          StepReference ref = (StepReference) item;
          boolean matches = true;

          if (!ref.getIdent().equals(expectedStepName)) {
            mismatchDescription.appendText("reference name was ").appendValue(ref.getIdent());
            matches = false;
          }

          if (!Objects.equals(expectedInputName, ref.getNamedInput().orElse(null))) {
            matches = false;
            mismatchDescription.appendText(" input name was ").appendValue(ref.getNamedInput().orElse(null));
          }

          return matches;
        } else {
          mismatchDescription.appendText("not a reference, was a definition: ").appendValue(item);
          return false;
        }
      }
    };
  }

  public static Matcher<StepLink> isStepLink(Matcher<StepDeclaration> lhsMatcher, Matcher<StepDeclaration> rhsMatcher) {
    return new TypeSafeDiagnosingMatcher<StepLink>(StepLink.class) {
      @Override
      protected boolean matchesSafely(StepLink item, Description mismatchDescription) {
        if (!lhsMatcher.matches(item.getLhs())) {
          lhsMatcher.describeMismatch(item.getLhs(), mismatchDescription);
        }
        if (!rhsMatcher.matches(item.getRhs())) {
          rhsMatcher.describeMismatch(item.getRhs(), mismatchDescription);
        }

        return rhsMatcher.matches(item.getRhs()) && lhsMatcher.matches(item.getLhs());
      }

      @Override
      public void describeTo(Description description) {
        description
          .appendText("link from ")
          .appendDescriptionOf(lhsMatcher)
          .appendText(" to ").appendDescriptionOf(rhsMatcher);
      }
    };
  }
}
