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

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.stream.Collectors;

import com.google.common.collect.ImmutableSet;

import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import nz.org.riskscape.engine.Identified;
import nz.org.riskscape.engine.plugin.ExtensionPoints;
import nz.org.riskscape.engine.plugin.Plugin;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.StandardCodes;

@RequiredArgsConstructor
@Slf4j
public class DefaultMessages implements Messages {

  /**
   * Construct an i18n code for looking up messages belonging to an identified object based on its id.
   */
  public static String getCode(Identified object, String... parts) {
    return getCode(object.getIdentifiedClass().getName(), object.getId(), parts);
  }

  /**
   * Same as {@link #getCode(Identified, String...)} except it strips off the
   * package-name and just uses the class's simple name. As the Identified object
   * should already have a unique ID, the package-name is a bit unnecessary.
   */
  public static String getShortCode(Identified object, String... parts) {
    return getCode(object.getIdentifiedClass().getSimpleName(), object.getId(), parts);
  }

  /**
   * Construct an i18n code for looking up messages belonging to an identified
   * object based on its id. Keys take the form
   * `nz.org.riskscape.engine.${API_CLASS}.by-id.${ID}.${part¹}.${part²}...`. For
   * a model, this might look like
   * `nz.org.riskscape.engine.model.Model.by-id.default.param.filter`.
   *
   */
  public static String getCode(String className, String id, String... parts) {
    StringBuilder builder = new StringBuilder();
    key(builder, className, "by-id", id);
    key(builder, parts);

    return builder.toString();
  }

  private static StringBuilder key(StringBuilder builder, String... parts) {

    for (String string : parts) {
      if (builder.length() != 0) {
        builder.append(".");
      }
      builder.append(string);
    }

    return builder;
  }


  @Getter
  protected final I18nClassLoader classLoader;

  @Getter
  protected final ResourceBundleControl control;

  @Getter
  private final RiskscapeMessageSource help;

  @Getter
  private final RiskscapeMessageSource labels;

  @Getter
  private final RiskscapeMessageSource problems;

  @Getter @Setter
  private Locale defaultLocale = Locale.getDefault();

  private final DefaultObjectRenderer objectRenderer;

  private final ExtensionPoints extensionPoints;

  // package scoped for injecting mocks for testing
  DefaultMessages(Map<String, ResourceBundle> bundles, DefaultObjectRenderer renderer, ExtensionPoints eps) {
    classLoader = new I18nClassLoader();
    control = ResourceBundleControl.INSTANCE;
    help = new RiskscapeMessageSource(l -> bundles.get("help"));
    labels = new RiskscapeMessageSource(l -> bundles.get("labels"));
    problems = new RiskscapeMessageSource(l -> bundles.get("problems"));
    objectRenderer = renderer;
    this.extensionPoints = eps;
  }

  public DefaultMessages(ExtensionPoints extensionPoints) {
    classLoader = new I18nClassLoader();
    control = ResourceBundleControl.INSTANCE;
    help = newMessageSource("help");
    labels = newMessageSource("labels");
    problems = newMessageSource("problems");
    objectRenderer = new DefaultObjectRenderer();
    this.extensionPoints = extensionPoints;
  }

  @Override
  public RiskscapeMessageSource newMessageSource(String baseName) {
    return new RiskscapeMessageSource(baseName, classLoader);
  }

  /**
   * Shortcut for `newMessageSource(baseName).getBundle(locale)`
   */
  public ResourceBundle getResourceBundle(String baseName, Locale locale) {
    return newMessageSource(baseName).getBundle(locale);
  }

  /**
   * Search through messages for a message belonging to a given identified object.
   * Will only search using an ID code generated from {@link #getCode(Identified, String...)}
   * and will *not* fallback to searching by class name. This allows us to customize
   * highly-specific help for certain models or functions.
   */
  private String findMessageById(MessageSource msgs, Locale locale, Identified object, String... parts) {
    // try to lookup specific help based on the object's ID,
    // e.g. "...model.Model.kaiju-stomp.description"
    String byIdKey = getCode(object, parts);
    String result = msgs.getMessage(byIdKey, null, locale);
    if (result == null) {
      // try the short i18n code without the package name
      result = msgs.getMessage(getShortCode(object, parts), null, locale);
    }
    return result;
  }

  /**
   * Search through help messages for a message belonging to a given identified
   * object. Will first search using {@link #findHelpMessageById(Identified, String...)}
   * before falling back to searching by class name via {@link #findHelpMessage(Object, String...)}
   */
  private String findMessageByInstance(MessageSource msgs, Locale locale, Identified object, String... parts) {
    // first, try to lookup the help by the object's ID
    String lookedUp = findMessageById(msgs, locale, object, parts);

    if (lookedUp != null) {
      return lookedUp;
    } else {
      // fallback to the regular lookup if that didn't work
      return findMessageByClass(msgs, locale, object.getClass(), parts);
    }
  }

  @Override
  public Optional<String> getMessage(MessageSource msgs, Locale locale, @NonNull Object owner, String... parts) {
    if (owner instanceof Identified) {
      return Optional.ofNullable(findMessageByInstance(msgs, locale, (Identified) owner, parts));
    } else if (owner instanceof Class) {
      return Optional.ofNullable(findMessageByClass(msgs, locale, (Class<?>)owner, parts));
    } else {
      return Optional.ofNullable(findMessageByClass(msgs, locale, owner.getClass(), parts));
    }
  }

  private String[] appendToParts(String[] origParts, int toAdd) {
    String[] newParts = new String[origParts.length + 1];
    System.arraycopy(origParts, 0, newParts, 0, origParts.length);
    newParts[origParts.length] = Integer.toString(toAdd);
    return newParts;
  }

  @Override
  public List<String> getDetailedMessage(MessageSource msgs, Locale locale, Object owner, String... parts) {
    List<String> results = new ArrayList<>();
    String lookup = getMessage(msgs, locale, owner, parts).orElse(null);
    int i = 1;

    while (lookup != null) {
      results.add(lookup);
      lookup = getMessage(msgs, locale, owner, appendToParts(parts, i++)).orElse(null);
    }
    return results;
  }

  private String findMessageByClass(MessageSource msgs, Locale locale, Class<?> owner, String... parts) {
    StringBuilder builder = new StringBuilder();
    // NB this used to use class name, which meant we needed yukky '$' in the translations - we don't want that
    key(builder, owner.getCanonicalName());
    key(builder, parts);

    String result = msgs.getMessage(builder.toString(), null, locale);

    if (result == null && owner.getSuperclass() != Object.class) {
      return findMessageByClass(msgs, locale, owner.getSuperclass(), parts);
    } else {
      return result;
    }
  }

  /**
   * @return a set of resource bundle names that are either well known riskscape bundles (such as help) or ones that
   * have been registered via a plugin with the {@link HasMessages} feature interface.
   */
  public Set<String> getKnownBundleNames(ExtensionPoints eps) {
    Set<String> wellKnownBundles = ImmutableSet.of("help", "labels", "problems");
    Set<String> fromPlugins = eps.getFeaturesOfType(HasMessages.class)
        .stream()
        .map(hm -> hm.getBundleName())
        .collect(Collectors.toSet());

    return ImmutableSet.<String>builder().addAll(wellKnownBundles).addAll(fromPlugins).build();
  }

  @Override
  public String renderObject(Object object, Locale locale) {
    // NB feature lookup has to be dynamic as there's no obvious/simple checkpoint during init to signal that all
    // features have been registered.  It probably doesn't matter anyway, it should be relatively quick
    for (ObjectRenderer renderer : this.extensionPoints.getFeaturesOfType(ObjectRenderer.class)) {
      String rendered = renderer.render(this, object, locale).orElse(null);

      if (rendered != null) {
        return rendered;
      }
    }

    return objectRenderer.render(this, object, locale).orElse(null);
  }

  @Override
  public RenderedProblem renderProblem(Problem problem, Locale locale) {
    return renderProblem(problem, locale, 0);
  }

  private RenderedProblem renderProblem(Problem problem, Locale locale, int nesting) {
    String message;
    if (problem.getCode() != StandardCodes.NONE) {
      message = problems.getMessage(problem.getCode().toKey(), getRenderedArguments(problem, locale), locale);
      if (message == null) {
        log.warn("Possible missing i18n key - {}", problem.getCode().toKey());
        message = problem.getDefaultMessage();
      }
    } else {
      message = problem.getDefaultMessage();
    }

    List<RenderedProblem> children = new ArrayList<>(problem.getChildren().size());
    for (Problem child : problem.getChildren()) {
      children.add(renderProblem(child, locale, nesting + 1));
    }

    return new RenderedProblem(message, problem, nesting, Collections.unmodifiableList(children));
  }

  private String[] getRenderedArguments(Problem problem, Locale locale) {
    Object[] args = problem.getArguments();
    String[] renderedArgs = new String[args.length];
    for (int i = 0; i < args.length; i++) {
      renderedArgs[i] = renderObject(args[i], locale);
    }
    return renderedArgs;
  }

  @Override
  public void addPluginResources(Plugin plugin) {
    classLoader.append(plugin, plugin.getI18nClassLoader());
  }
}
