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


import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;

import lombok.Getter;
import lombok.Setter;
import nz.org.riskscape.cli.Terminal;
import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.FileProblems;
import nz.org.riskscape.engine.OsUtils;
import nz.org.riskscape.engine.i18n.DefaultMessages;
import nz.org.riskscape.engine.i18n.Messages;
import nz.org.riskscape.picocli.CommandLine.Command;
import nz.org.riskscape.picocli.CommandLine.Option;
import nz.org.riskscape.problem.Problems;

@Command(name = "i18n")
public class I18nCommand implements ChildCommand, EngineCommand, TerminalCommand {

  public static final List<Character> ESCAPE_IN_VALUE = Arrays.asList('\n', '\r', '\t', '!', ':', '#', '=', '\f');
  public static final List<Character> ESCAPE_IN_KEY = Arrays.asList(' ', '\n', '\r', '\t', '!', ':', '#', '=', '\f');


  @Getter @Setter
  private Engine engine;

  @Getter @Setter
  private Terminal terminal;

  @Getter @Setter
  private Messages messages;

  @Option(names = "--newline-char", required = false)
  String newline = OsUtils.LINE_SEPARATOR;

  @Option(names = "--indent", required = false, defaultValue = "  ")
  String indent;

  @Option(names = "--locale")
  String locale;

  @Option(names = {"-o", "--output-dir"}, defaultValue = ".")
  File outputDir;

  @Override
  public Object run() {
    // this relies on some implementation details
    DefaultMessages defaultMessages = (DefaultMessages) getMessages();
    Locale l = Locale.getDefault();
    Set<String> bundles = defaultMessages.getKnownBundleNames(engine.getExtensionPoints());

    for (String bundleName : bundles) {
      ResourceBundle bundle = defaultMessages.newMessageSource(bundleName).getBundle(l);
      String baseName = bundle.getBaseBundleName();
      File outputFile = new File(
          outputDir,
          baseName + (locale == null ? "" : "_" + locale) + ".properties"
      );
      try {
        PrintStream writer = new PrintStream(outputFile, "UTF-8");
        int keyCount = writeBundles(writer, bundle);
        writer.close();
        printerr("Wrote %d keys for %s", keyCount, baseName);
        print(outputFile.getAbsolutePath());
      } catch (IOException e) {
        throw new ExitException(
            FileProblems.get().cantWriteTo(outputFile.toPath()).withChildren(Problems.caught(e)), e);
      }
    }
    return null;
  }

  private int writeBundles(PrintStream writer, ResourceBundle bundle) throws IOException {
    Enumeration<String> keys = bundle.getKeys();
    int counter = 0;
    while (keys.hasMoreElements())  {
      String key = keys.nextElement();
      Object value = bundle.getObject(key);

      if (value instanceof String) {
        writer.append(escape(key, ESCAPE_IN_KEY)).append(" = \\").append(newline);
        writer.append(indent).append(escape(value.toString(), ESCAPE_IN_VALUE)).append(newline).append(newline);
      } else if (value != null) {
        writer.append("# unrecognised resource in bundle " + bundle + " - " + value.getClass())
        .append(newline).append(newline);
      }
      counter++;
    }
    return counter;
  }

  private String escape(String string, List<Character> escapeChars) {
    StringBuffer buf = new StringBuffer(string.length()); // worst case - everything has to be escaped
    for (int i = 0; i < string.length(); i++) {
      char ch = string.charAt(i);
      if (escapeChars.contains(ch)) {
        buf.append('\\');
      }
      buf.append(ch);

      if (ch == '\n') {
        buf.append(indent);
      }
    }

    return buf.toString();
  }


}
