/*
 * 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 com.google.common.base.Strings;
import java.io.InputStream;
import java.net.URI;
import lombok.Getter;
import nz.org.riskscape.engine.RiskscapeIOException;
import nz.org.riskscape.engine.resource.Resource;
import nz.org.riskscape.engine.resource.ResourceLoader;
import nz.org.riskscape.engine.resource.ResourceLoadingException;
import nz.org.riskscape.engine.resource.BaseResource;
import org.openstack4j.api.OSClient;
import org.openstack4j.api.exceptions.AuthenticationException;
import org.openstack4j.model.common.Identifier;
import org.openstack4j.model.storage.object.SwiftObject;
import org.openstack4j.openstack.OSFactory;

/**
 * Loads {@link Resource}s from a cloud storage using the swift APIs.
 */
public class SwiftObjectStorageResourceLoader implements ResourceLoader {

  static class SwiftResource {

    @Getter
    private final String projectUUID;
    @Getter
    private final String containerName;
    @Getter
    private final String path;

    /**
     * Make a swift resource from a {@link URI} expected to be in the form:
     *
     * swift://<project-uuid>/<container-name>/<path-to-file>
     *
     * @param target URI
     * @throws IllegalArgumentException if target is not a valid swift URI
     */
    SwiftResource(URI target) throws IllegalArgumentException {
      if (!"swift".equals(target.getScheme())) {
        throw new IllegalArgumentException(String.format("URI '%s' is not a swift uri", target));
      }
      this.projectUUID = target.getAuthority();
      //look for the second slash
      int slash = target.getPath().indexOf("/", 1);
      if (slash == -1) {
        throw new IllegalArgumentException(String.format("URI '%s' is not a complete swift uri", target));
      }
      this.containerName = target.getPath().substring(1, slash);
      this.path = target.getPath().substring(slash + 1);
    }
  }

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

  @Override
  public String getDescription() {
    return String.format("Loads resources from an Openstack Cloud using the 'swift' APIs. "
        + "URI format is: 'swift://<project-uuid>/<container-name>/<path-to-file>' "
        + "Also requires the following standard Openstack environment variables to be defined:"
        + "'OS_AUTH_URL', 'OS_USERNAME' and 'OS_PASSWORD'");
  }

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

  @Override
  public Resource load(URI target) {
    SwiftResource pointer = null;
    try {
      pointer = new SwiftResource(target);
    } catch (IllegalArgumentException e) {
      throw new ResourceLoadingException(target, e.getMessage());
    }

    String authUrl = System.getenv("OS_AUTH_URL");
    String username = System.getenv("OS_USERNAME");
    String passwd = System.getenv("OS_PASSWORD");

    if (Strings.isNullOrEmpty(authUrl)
        || Strings.isNullOrEmpty(username)
        || Strings.isNullOrEmpty(passwd)) {
      //Auth variable missing or empty is going to be a problem
      throw new ResourceLoadingException(target,
          "Missing required swift authentication settings");
    }

    try {
      Identifier domainIdentifier = Identifier.byName("Default");
      OSClient.OSClientV3 os = OSFactory.builderV3()
          .endpoint(authUrl)
          .credentials(username, passwd, domainIdentifier)
          .scopeToProject(Identifier.byId(pointer.getProjectUUID()))
          .authenticate();

      SwiftObject resource = os.objectStorage().objects().get(pointer.getContainerName(), pointer.getPath());
      if (resource == null) {
        throw new ResourceLoadingException(target,
            String.format("Could not retrieve '%s' from object storage. Does it exist?", target));
      }
      return new BaseResource(target) {

        @Override
        public InputStream getContentStream() throws RiskscapeIOException {
          return resource.download().getInputStream();
        }

      };
    } catch (AuthenticationException e) {
      //AuthenticationException is thrown if the auth settings are wrong, which includes an incorrect
      //container-name  in the URI
      throw new ResourceLoadingException(target,
          "Could not authenticate for object storage, Check connection settings and swift://<container-name>", e);
    }
  }

}
