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

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

import org.python.core.Py;
import org.python.core.PyBoolean;
import org.python.core.PyDictionary;
import org.python.core.PyFloat;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.core.PyString;

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;

public interface JavaJythonHelpers {

  /**
   * Performs a Riskscape {@link Type} aware conversion of a python object to a java object.
   * @param ob object to convert to a plain old Java Object
   * @param type a Riskscape {@link Type} that we wish to convert to
   * @return a java object that conforms to {@link Type}
   */
  default Object convertFromPython(PyObject ob, Type type) {
    Object convertedValue;
    if (ob instanceof PyBoolean) {
      convertedValue = ((PyBoolean)ob).getBooleanValue();
    } else if (ob instanceof PyInteger) {
      convertedValue = ((PyInteger)ob).getValue();
    } else if (ob instanceof PyFloat) {
      convertedValue = ((PyFloat) ob).getValue();
    } else if (ob instanceof PyString) {
      convertedValue = ((PyString) ob).getString();
    } else if (ob instanceof PyDictionary) {
      Map<PyObject, PyObject> returned = ((PyDictionary)ob).getMap();

      if (type.getUnwrappedType() instanceof Struct) {
        Struct struct = (Struct) type.getUnwrappedType();
        Tuple converted = new Tuple(struct);
        returned.forEach((k, v) -> {
          String key = k.toString();

          Type keyType = struct.getMember(key).map(StructMember::getType).orElseThrow(() ->
            new RuntimeException(String.format("Python object %s does not match described "
                + "return type %s", ob, type)));

          // do coercion?
          converted.set(key, keyType.coerce(convertFromPython(v, keyType)));
        });
        convertedValue = converted;

      } else {
        Map<String, Object> converted = new HashMap<>();
        returned.forEach((k, v) -> {
          converted.put(convertFromPython(k, Types.ANYTHING).toString(), convertFromPython(v, Types.ANYTHING));
        });
        convertedValue = converted;

      }
    } else {
      return ob.__tojava__(Object.class);
    }
    return convertedValue;
  }

  /**
   * @return a PyObject that is callable which runs the given function, applying Java <-> Python conversion as
   * necessary.
   */
  @SuppressWarnings("serial")
  default <X, Y> PyObject toPyCallable(Class<X> in, Class<Y> out, Function<X, Y> toWrap) {
    return new PyObject() {

      @Override
      // CHECKSTYLE:OFF
      public PyObject __call__(PyObject[] args, String[] keywords) {
      // CHECKSTYLE:ON

        if (keywords.length > 0) {
          // TODO PyError
          throw new RuntimeException("keywords not supported");
        }

        if (args.length != 1) {
          // TODO PyError
          throw new RuntimeException(String.format("Function %s expected exactly %d args, got %d", toWrap, 1,
              args.length));

        }

        @SuppressWarnings("unchecked")
        Object returned = toWrap.apply((X) args[0].__tojava__(in));

        return Py.java2py(returned);
      }

    };

  }
}
