/*
 * 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.
 */
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nz.org.riskscape.engine.plugin;


import java.lang.reflect.Constructor;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.jar.Manifest;
import java.util.stream.Collectors;

import com.google.common.base.Strings;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.problem.Problems;

@Slf4j
@ToString(of= {"pluginId", "source"})
@EqualsAndHashCode(of= {"source", "pluginId"})
public class DefaultPluginDescriptor implements PluginDescriptor {

  @Getter
  private final URL source;
  @Getter
  private final PluginClassLoader classLoader;
  @Getter
  private final Manifest manifest;

  @Getter
  private Optional<Class<?>> pluginClass = Optional.empty();

  @Getter
  private final String pluginId;
  @Getter
  private final String pluginClassName;
  @Getter
  private final String version;

  @Getter
  private final Set<String> pluginDependencies;

  public DefaultPluginDescriptor(URL source, PluginClassLoader classLoader, Manifest manifest) {
    this.source = source;
    this.classLoader = classLoader;
    this.manifest = manifest;

    this.pluginClassName = manifest.getMainAttributes().getValue("Riskscape-Plugin");

    if (this.pluginClassName == null) {
      throw new RuntimeException(String.format("Manifest from %s does not include a Riskscape-Plugin entry", source));
    }

    String manifestId = manifest.getMainAttributes().getValue("Riskscape-Plugin-ID");

    if (manifestId == null) {
      log.info(String.format("Plugin from %s does not define a plugin id, using plugin class name %s",
          source, pluginClassName));
      this.pluginId = pluginClassName;
    } else {
      this.pluginId = manifestId;
    }

    String manifestVersion = manifest.getMainAttributes().getValue("Riskscape-Plugin-Version");
    if (manifestVersion != null) {
      this.version = manifestVersion;
    } else {
      this.version = "unknown";
    }

    // look for any declared dependencies - these are comma separated
    String dependencies = manifest.getMainAttributes().getValue("Riskscape-Plugin-Dependency-IDs");
    if (!Strings.isNullOrEmpty(dependencies)) {
      this.pluginDependencies = Arrays.asList(dependencies.split(","))
        .stream().map(String::trim)
        .filter(str -> !str.isEmpty())
        .collect(Collectors.toSet());
    } else {
      this.pluginDependencies = Collections.emptySet();
    }

    // form a soul-bond with the class loader
    classLoader.setPluginDescriptor(this);
  }

  @Override
  public boolean hasPluginDependencies() {
    return !pluginDependencies.isEmpty();
  }

  @Override
  public Path getSourcePath() {
    try {
      return Paths.get(getSource().toURI());
    } catch (URISyntaxException e) {
      throw new RiskscapeException(Problems.caught(e));
    }
  }

  @Override
  public void addDependency(PluginDescriptor dependencyDescriptor) {
    if (!(dependencyDescriptor instanceof DefaultPluginDescriptor)) {
      throw new IllegalArgumentException("DefaultPluginDescriptor can only depend on other DefaultPluginDescriptor "
          + "instances");
    }
    classLoader.addDependency(((DefaultPluginDescriptor)dependencyDescriptor).classLoader);

  }

  @Override
  public ClassLoader getI18nClassLoader() {
    return classLoader.getI18nResourceLoader();
  }

  @Override
  public Plugin newPluginInstance() {
    String className = getPluginClassName();
    Constructor<Plugin> constructor;
    try {
      Class<?> loadedClass = classLoader.loadClass(className);
      Class<Plugin> loadedPluginClass;

      if (!Plugin.class.isAssignableFrom(loadedClass)) {
        throw new PluginRuntimeException(this, null, "Plugin class %s does not extend %s", loadedClass, Plugin.class);
      } else {
        loadedPluginClass = (Class<Plugin>) loadedClass;
      }

      constructor = loadedPluginClass.getConstructor(PluginDescriptor.class);
    } catch (ClassNotFoundException e) {
      throw new PluginRuntimeException(this, e, "Plugin source %s does not include class %s", this.getSource(),
          className);
    } catch (NoSuchMethodException e) {
      throw new PluginRuntimeException(this, e, "Plugin class %s does not define %s(%s)", className, className,
          PluginDescriptor.class);
    } catch (Throwable e) {
      throw new PluginRuntimeException(this, e, "Could not initialize plugin %s", this);
    }

    ClassLoader classLoaderToRestore = Thread.currentThread().getContextClassLoader();

    try {
      Thread.currentThread().setContextClassLoader(classLoaderToRestore);

      Plugin constructed;
      try {
        constructed = constructor.newInstance(this);
      } catch (Throwable e) {
        throw new PluginRuntimeException(this, e, "Could not create instance of plugin class using %s from plugin %s",
            constructor, this);
      }
      return constructed;
    } finally {
      Thread.currentThread().setContextClassLoader(classLoaderToRestore);
    }
  }
}
