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

import static nz.org.riskscape.engine.Matchers.hasAncestorProblem;
import static nz.org.riskscape.engine.Matchers.isProblem;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.io.IOException;
import java.util.Arrays;

import nz.org.riskscape.engine.Assert;
import nz.org.riskscape.engine.auth.SecretProblems;
import nz.org.riskscape.engine.auth.Secrets;
import nz.org.riskscape.engine.cli.ExitException;
import nz.org.riskscape.test.TestUsesRemoteData;
import org.junit.Test;
import org.junit.experimental.categories.Category;

/**
 * Spot-checks the exemplar koordinates bookmarks via WFS
 */
@Category(TestUsesRemoteData.class)
public class KoordinatesWfsTest extends BaseExemplarTest {

  @Test
  public void statsnzBookmarksRequireSecret() {
    // having a koordinates secret for another site should just be ignored
    addKoordinatesSecret("bad", "not-a-match.ci.rsdev.nz", "invalid-key");

    runCommand.modelId = "region-spot-check";
    runCommand.parameters = Arrays.asList("region=StatsNZ_Regional_Council_2023");
    ExitException ex = Assert.assertThrows(ExitException.class, () -> runCommand.run());

    // bookmark has requires-secret, so we should get an error saying we need the secret
    assertThat(ex.getProblem(), hasAncestorProblem(
            is(SecretProblems.get().requiredNotFound("koordinates", "datafinder.stats.govt.nz",
                    SecretProblems.get().noSecretsHint(Secrets.getUserHomeSecrets(engine))))));
    assertThat(render(ex.getProblem()), allOf(
            containsString("authentication token (or \"secret\") is required in order to use this bookmark"),
            containsString("`framework = koordinates`"),
            containsString("`hostname = datafinder.stats.govt.nz`")
    ));
    engine.getCollection(Secrets.class).remove("bad");
  }

  @Test
  public void cannotAccessLinzDataWithoutSecret() {
    runCommand.modelId = "input-sanity-check";
    runCommand.parameters = Arrays.asList("layer=linz-no-requires-secret");
    ExitException ex = Assert.assertThrows(ExitException.class, () -> runCommand.run());

    // we get an IO exception because we haven't added a LINZ secret, and the bookmark doesn't have requires-secret
    assertThat(ex.getProblem(), hasAncestorProblem(isProblem(IOException.class)));
  }

  @Test
  public void canAccessStatsnzDataServiceWithKey() throws Exception {
    addKoordinatesSecret("statsnz", "datafinder.stats.govt.nz", getApiKey(STATSNZ_KEY));

    runCommand.modelId = "region-spot-check";
    runCommand.parameters = Arrays.asList("region=StatsNZ_Regional_Council_2023");
    runCommand.run();

    assertThat(openCsv("results.csv", "geom", "ID", "Name"), contains(
            Arrays.asList("POINT (-35.50683011015864 173.82563029311714)", "01", "Northland Region")
    ));
    engine.getCollection(Secrets.class).remove("statsnz");
  }

  @Test
  public void canAccessLinzDataServiceWithKey() throws Exception {
    addKoordinatesSecret("linz", "data.linz.govt.nz", getApiKey(LINZ_KEY));

    runCommand.modelId = "region-spot-check";
    runCommand.parameters = Arrays.asList("region=LINZ_Suburbs_and_Localities");
    runCommand.run();

    assertThat(openCsv("results.csv", "geom", "ID", "Name", "Type"), contains(
            Arrays.asList("POINT (-45.63640248561104 168.32247460706776)", "1", "Acton, Southland District", "Locality")
    ));
    engine.getCollection(Secrets.class).remove("linz");
  }

  @Test
  public void statsnzExemplarBookmarksAreValid() throws Exception {
    addKoordinatesSecret("statsnz", "datafinder.stats.govt.nz", getApiKey(STATSNZ_KEY));

    // this basically just sanity checks the bookmark link works OK
    checkbookmarkValid("StatsNZ_Territorial_Authorities_2023");
    checkbookmarkValid("StatsNZ_Statistical_Area_2_2023");
    checkbookmarkValid("StatsNZ_Meshblock_2023");
    checkbookmarkValid("StatsNZ_Ward_2023");
    checkbookmarkValid("StatsNZ_Functional_Urban_Area_2023");
    checkbookmarkValid("StatsNZ_Urban_Rural_2023");
    checkbookmarkValid("Estimated_Resident_Population_Grid_250m");

    engine.getCollection(Secrets.class).remove("statsnz");
  }

  @Test
  public void linzExemplarBookmarksAreValid() throws Exception {
    addKoordinatesSecret("linz", "data.linz.govt.nz", getApiKey(LINZ_KEY));

    // this basically just sanity checks the bookmark link works OK
    checkbookmarkValid("LINZ_Building_Outlines");
    checkbookmarkValid("LINZ_Road_Centrelines");
    checkbookmarkValid("LINZ_Primary_Land_Parcels");
    checkbookmarkValid("LINZ_Railway_Centrelines");
    checkbookmarkValid("LINZ_Rail_Station_Points");
    checkbookmarkValid("LINZ_NZ_Facilities");
    checkbookmarkValid("LINZ_NZ_Addresses");

    engine.getCollection(Secrets.class).remove("linz");
  }

  @Test
  public void transpowerExemplarBookmarksAreValid() throws Exception {
    // this basically just sanity checks the bookmark link works OK
    // These bookmarks actually use ArcGIS On-Line, but it's the same assertion as the Koordinates bookmarks
    checkbookmarkValid("Transpower_Transmission_Lines");
    checkbookmarkValid("Transpower_Sites");
    // in this case we have to pull down the whole GeoJSON file, so it's too slow to test the bigger datasets
    //checkbookmarkValid("Transpower_Line_Spans");
    //checkbookmarkValid("Transpower_Structures");
  }

  private void checkbookmarkValid(String bookmark) throws Exception {
    // this uses limit=0 so should be fairly quick, but will still blow up if the bookmark is bad
    runCommand.modelId = "input-sanity-check";
    runCommand.parameters = Arrays.asList("layer=" + bookmark);
    runCommand.run();
  }
}
