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

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.google.common.base.CaseFormat;

import nz.org.riskscape.ReflectionUtils;
import nz.org.riskscape.engine.bind.BaseBinder;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.bind.ParamProblems;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.wizard.Composite;
import nz.org.riskscape.wizard.CompositeField;
import nz.org.riskscape.wizard.Question;

/**
 * Binds a {@link Map} to a class tagged with {@link Composite}
 */
public class CompositeBinder extends BaseBinder {

  /**
   * @return the name that would be appended to the sub-question for this field
   */
  public static String fieldName(Field field) {
    return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, field.getName());
  }

  /**
   * Pulls the field name back out of a sub-question we've already created
   */
  public static String fieldName(Question question) {
    String fullName = question.getName();
    return fullName.substring(fullName.lastIndexOf('.') + 1);
  }

  /**
   * Returns a new {@link Question} that is modified for representing a sub-question for a given field
   * @param originalQuestion the question with a {@link Composite} annotated type to modify
   * @param clazz the {@link Composite} annotated class
   * @param fieldName the name of the public field that the new question will be for
   */
  public static Question fieldifyQuestion(Question originalQuestion, Class<?> clazz, String fieldName) {
    return fieldifyQuestion(originalQuestion, ReflectionUtils.getPublicField(clazz, fieldName).get());
  }

  /**
   * Returns a new {@link Question} that is modified for representing a sub-question for a given field
   * @param originalQuestion the question with a {@link Composite} annotated type to modify
   * @param field a {@link CompositeField} annotated field that the new question will be for
   */
  public static Question fieldifyQuestion(Question originalQuestion, Field field) {
    CompositeField compositeField = field.getAnnotation(CompositeField.class);

    Question subQuestion = originalQuestion
        .withType(field.getType())
        .withName(originalQuestion.getName() + "." + fieldName(field));

    // add any tags, if specified, to help jujz the asker behaviour
    if (!compositeField.tagKey().isEmpty()) {
      subQuestion = subQuestion.withAnnotations(compositeField.tagKey(), compositeField.tagValue());
    }

    return subQuestion;
  }
  @Override
  public boolean canBind(Class<?> sourceType, Class<?> destinationType) {
    return destinationType.getAnnotation(Composite.class) != null && Map.class.isAssignableFrom(sourceType);
  }

  @Override
  public <T> ResultOrProblems<T> bindValue(BindingContext context, Object value, Class<T> destinationType) {
    // clone the map - don't alter the original
    Map<?, ?> valueMap = new HashMap<>((Map<?, ?>) value);

    List<Problem> problems = new LinkedList<>();
    T compositeInstance = ReflectionUtils.newInstance(destinationType);
    List<Field> fields = ReflectionUtils.getAnnotatedFields(destinationType, CompositeField.class);

    for (Field field : fields) {
      Class<?> fieldType = field.getType();
      // go from fooBar to foo-bar
      String mapKey = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, field.getName());

      // we empty the map as we go so we can check after for stray keys at the end
      Object unboundFieldValue = valueMap.remove(mapKey);

      // all fields must be set
      if (unboundFieldValue == null) {
        problems.add(ParamProblems.get().wrongNumberGiven(mapKey, "1", 0));
        continue;
      }

      ResultOrProblems<?> bound = context.bind(unboundFieldValue, fieldType);

      if (bound.hasErrors()) {
        problems.add(Problems.foundWith(CompositeField.class, mapKey, bound.getProblems()));
      } else {
        // collect any warnings from the sub-binding
        bound = bound.drainWarnings(p -> problems.add(Problems.foundWith(CompositeField.class, mapKey, p)));
        ReflectionUtils.setField(
          field,
          compositeInstance,
          bound.get()
        );
      }
    }

    // warn if there are surplus keys we are ignoring
    if (!valueMap.isEmpty()) {
      problems.add(ParamProblems.get().ignored(
          valueMap.keySet().stream().map(Object::toString).collect(Collectors.joining(", ")))
      );
    }

    if (Problem.hasErrors(problems)) {
      return ResultOrProblems.failed(problems);
    }

    return ResultOrProblems.of(compositeInstance, problems);
  }

}
