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

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermission;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;

import lombok.Getter;
import nz.org.riskscape.config.ConfigSection;
import nz.org.riskscape.config.ini.IniConfig;
import nz.org.riskscape.engine.BuildInfo;
import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.auth.HttpHeaderSecret;
import nz.org.riskscape.engine.auth.SecretBuilders;
import nz.org.riskscape.engine.auth.SecretProblems;
import nz.org.riskscape.engine.auth.Secrets;
import nz.org.riskscape.engine.i18n.HasMessages;
import nz.org.riskscape.engine.i18n.ObjectRenderer;
import nz.org.riskscape.engine.ini.IniFileSecretBuilder;
import nz.org.riskscape.engine.jai.TileCacheBootstrapper;
import nz.org.riskscape.engine.plugin.BuiltInPluginDescriptor;
import nz.org.riskscape.engine.plugin.Plugin;
import nz.org.riskscape.engine.plugin.PluginDescriptor;
import nz.org.riskscape.engine.plugin.PluginFeature;
import nz.org.riskscape.engine.spi.CliCommand;
import nz.org.riskscape.engine.spi.EngineBootstrapper;
import nz.org.riskscape.engine.spi.EngineCollection;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problems;

/**
 * A not-quite plugin for core SPIs and Features that get initialized like other plugin SPIs and Features, but without
 * the classloader malarkey
  */
public class EnginePlugin extends Plugin {

  public static final PluginDescriptor DESCRIPTOR =
      new BuiltInPluginDescriptor("engine", BuildInfo.getBuildInfo(), EnginePlugin.class, null);

  public static final EnumSet<PosixFilePermission> USER_PERMISSIONS = EnumSet.of(
      PosixFilePermission.OWNER_EXECUTE,
      PosixFilePermission.OWNER_READ,
      PosixFilePermission.OWNER_WRITE
  );

  public EnginePlugin(PluginDescriptor pDescriptor) {
    super(pDescriptor);
  }

  @Getter
  private final List<Class<? extends PluginFeature>> extensionPoints = Arrays.asList(
    CliCommand.class,
    HasMessages.class,
    EngineBootstrapper.class,
    EngineCollection.class,
    ObjectRenderer.class
  );

  @Getter
  private final List<PluginFeature> features = Arrays.asList(
    new EngineBootstrapper("register-engine-collections", engine ->
      engine.getFeaturesOfType(EngineCollection.class).forEach(ec -> engine.registerCollection(ec.newInstance()))),
    EngineCollection.of(Secrets.class),
    EngineCollection.of(SecretBuilders.class),
    new EngineBootstrapper("load-user-secrets", engine -> loadUserSecrets(engine)),
    TileCacheBootstrapper.INSTANCE
  );

  @Override
  public List<Problem> initializeEngine(Engine engine) {
    engine.getCollection(SecretBuilders.class).add(HttpHeaderSecret.BUILDER);

    return Collections.emptyList();
  }

  private void loadUserSecrets(Engine engine) {

    Path secretsPath = Secrets.getUserHomeSecrets(engine);
    if (Files.isReadable(secretsPath)) {
      List<Problem> problems = new ArrayList<>();
      try {
        // secrets files should only allow access by the user. we warn if this is not the case.
        List<PosixFilePermission> excessPermissions = Files.getPosixFilePermissions(secretsPath).stream()
            .filter(perm -> !USER_PERMISSIONS.contains(perm))
            .toList();
        if (! excessPermissions.isEmpty()) {
          problems.add(SecretProblems.get().insecure(secretsPath, excessPermissions));
        }
      } catch (Throwable t) {
        // ignore exceptions here, this is an nice to have check and not all file system support the
        // posix attributes
      }

      IniConfig secrets = IniConfig.load(secretsPath.toUri(), engine.getResourceFactory())
          .addProblemsTo(problems)
          .orElse(null);

      if (secrets != null) {
        IniFileSecretBuilder secretBuilder = new IniFileSecretBuilder(engine);
        for (ConfigSection secret : secrets.getAll()) {
          secretBuilder.addSecret(secret.getName(), secret);
        }
      }
      if (!problems.isEmpty()) {
        engine.getProblemSink().accept(Problems.foundWith(secretsPath, problems));
      }
    }
  }

}
