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

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;

import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.RiskscapeIOException;
import nz.org.riskscape.engine.auth.HttpSecret;
import nz.org.riskscape.engine.auth.SecretProblems;
import nz.org.riskscape.engine.auth.Secrets;
import nz.org.riskscape.engine.resource.BaseResource;
import nz.org.riskscape.engine.resource.Resource;
import nz.org.riskscape.engine.resource.ResourceLoader;
import nz.org.riskscape.engine.resource.ResourceProblems;
import nz.org.riskscape.engine.util.Pair;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * Loads {@link Resource}s accessible via http(s).
 */
@RequiredArgsConstructor
public class HttpResourceLoader implements ResourceLoader {

  private final Engine engine;

  @Override
  public String getId() {
    return "http";
  }

  @Override
  public String getDescription() {
    return "Load resources from the web using http/https. E.g https://riskscape.org.nz/resources/flood-project.ini";
  }

  @Override
  public boolean canLoad(URI target) {
    return "http".equals(target.getScheme()) || "https".equals(target.getScheme());
  }

  /**
   * Get a connection to the given target.
   *
   * This method exists for test purposes.
   */
  HttpURLConnection getConnection(HttpSecret.Request request) throws IOException {

    HttpURLConnection conn = (HttpURLConnection) request.getURI().toURL().openConnection();
    conn.setRequestProperty("User-Agent",
        String.format("RiskScape-Engine/%s", engine.getBuildInfo().getVersion()));
    // set the connect and read timeouts so we don't wait forever if the target does not respond.
    conn.setConnectTimeout((int) TimeUnit.MILLISECONDS.convert(30, TimeUnit.SECONDS));
    conn.setReadTimeout((int) TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES));

    for (Pair<String, String> header : request.getHeaders()) {
      conn.addRequestProperty(header.getLeft(), header.getRight());
    }

    return conn;
  }

  @Override
  public Resource load(URI target) {
    return new BaseResource(target) {
      @Override
      public InputStream getContentStream() throws RiskscapeIOException {
        ResultOrProblems<InputStream> is = getInputStream(target);
        if (is.isPresent()) {
          return is.get();
        }
        throw new RiskscapeIOException(is.getAsSingleProblem());
      }

      private ResultOrProblems<InputStream> getInputStream(URI myTarget) {
        try {
          HttpSecret.Request request = HttpSecret.getRequest(target, engine);
          HttpURLConnection conn = getConnection(request);

          int responseCode = conn.getResponseCode();
          if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
            if (request.isSecretApplied()) {
              return ResultOrProblems.failed(ResourceProblems.get().notFound(
                  location,
                  SecretProblems.get().notFoundWithSecret(request.getSecret().get())
              ));
            }
            return ResultOrProblems.failed(ResourceProblems.get().notFound(location));
          } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            Problem hint = request.getSecret()
                .map(secret -> SecretProblems.get().secretsHint(secret))
                .orElseGet(() -> SecretProblems.get().noSecretsHint(Secrets.getUserHomeSecrets(engine)));
            return ResultOrProblems.failed(ResourceProblems.get().unauthorized(location, hint));
          } else if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
            return ResultOrProblems.failed(ResourceProblems.get().forbidden(location));

          }
          // XXX GL1002 deal with other non success responses and redirection

          return ResultOrProblems.of(conn.getInputStream());
        } catch (IOException e) {
          throw new RiskscapeIOException(String.format("Could not access resource from '%s'", myTarget), e);
        }
      }

      @Override
      public ResultOrProblems<Path> ensureLocal(Options options) {
        return ensureLocal(options, null);
      }

      @Override
      public ResultOrProblems<Path> ensureLocal(Options options, String extension) {
        if ("http".equals(location.getScheme()) && !options.allowInsecure) {
          return ResultOrProblems.failed(ResourceProblems.get().insecureNotAllowed(location));
        }
        return super.ensureLocal(options, extension);
      }

    };
  }

}
