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

import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;

import nz.org.riskscape.config.ConfigSection;
import nz.org.riskscape.config.ConfigString;
import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.IdentifiedCollection;
import nz.org.riskscape.engine.auth.Secret;
import nz.org.riskscape.engine.auth.SecretBuilder;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.bind.BoundParameters;
import nz.org.riskscape.engine.bind.Parameter;
import nz.org.riskscape.engine.resource.Resource;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * Almost an IdentifiedObjectBuilder for {@link Secret}, except they are added to an engine, not a project.
 */
public class IniFileSecretBuilder {

  private final Engine engine;
  private final IdentifiedCollection<SecretBuilder> secretBuilders;
  private final IdentifiedCollection<Secret> engineSecrets;

  public IniFileSecretBuilder(Engine engine) {
    this.engine = engine;
    this.secretBuilders = engine.getCollectionByClass(SecretBuilder.class);
    this.engineSecrets = engine.getCollectionByClass(Secret.class);
  }

  /**
   * Builds the secret contained in section immediately and adds it secrets collection if there were
   * no build errors.
   */
  public void addSecret(String id, ConfigSection section) {
    engineSecrets.add(id, new Resource.PseudoResource(section.getLocation()), () -> {
      // building the secret is defered until it is required. this prevents any race conditions that
      // would otherwise be created by the user secrets being added by an engine bootstrapper which
      // could be before a plugin has added the secret implementation.
      ResultOrProblems<Secret> built = build(id, section);
      if (built.hasProblems()) {
        // there were some problems building the secret. we need to ensure the user knows what the problem
        // is. normally we'd let whatever uses the secret worry about that but that won't work in this case
        // because secrets are not looked up and used by id. instead secret user's look over the entire collection
        // to find ones that match. but IdentifiedCollection.getAll silently discards those that have failed
        // to build. so we send the problems to the problem sink to ensure they are output.
        engine.getProblemSink().accept(built.getAsSingleProblem());
      }
      return built;
    });
  }

  public ResultOrProblems<Secret> build(String id, ConfigSection section) {
    return ProblemException.catching(() -> {
      SecretBuilder secretBuilder = secretBuilders.getOr(
          section.getOneRequired("framework").getOrThrow()
      ).getOrThrow();

      BindingContext bindingContext = engine.newBindingContext();

      Map<ConfigString, List<ConfigString>> unbound = new HashMap<>(section.toConfigMap());
      // wrap the id pseudo-parameter in a config string that points back to where the section was defined - this
      // should point users to the right place if there's something wrong with the secret.
      URI uri = section.getLocation();
      unbound.putIfAbsent(ConfigString.wrap(uri, "id"), Lists.newArrayList(ConfigString.wrap(uri, id)));

      Parameter hostnameParameter = secretBuilder.getParameters().get("hostname");
      if (hostnameParameter != null && !hostnameParameter.hasDefaultValue()) {
        // if the secret requires a hostname but the user hasn't provided one we use the id
        // but not if the parameter has a default (see PlatformSecret).
        // NB: This is by far the simplest way of implementing this behaviour while the secret builder code is not
        // DRYd up at all.  I think it would be cleaner to have this in the binding logic instead, but things aren't
        // factored in a way to make that possible at the moment.
        unbound.putIfAbsent(ConfigString.wrap(uri, "hostname"), Lists.newArrayList(ConfigString.wrap(uri, id)));
      }

      BoundParameters bound = secretBuilder.getParameters().bindConfig(
          bindingContext,
          unbound
      );

      if (!bound.isValid()) {
        throw new ProblemException(Problems.toSingleProblem(bound.getValidationProblems()));
      }

      return secretBuilder.getBuilder().apply(bound).getOrThrow();
    }).composeProblems((sev, probs) -> {
      return Problems.foundWith(section.getLocation(), probs);
    });
  }

}
