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

import static nz.org.riskscape.dsl.ProblemCodes.*;
import static nz.org.riskscape.engine.Assert.*;
import static nz.org.riskscape.engine.Matchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.io.ByteArrayInputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import nz.org.riskscape.config.ConfigProblems;
import nz.org.riskscape.engine.FailedObjectException;
import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.engine.typeset.CanonicalType;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problem.Severity;
import nz.org.riskscape.problem.Problems;

public class IniFileTypeBuilderTest extends ProjectTest {

  IniFileTypeBuilder subject = new IniFileTypeBuilder(project);
  ByteArrayInputStream iniBytes;

  @Test
  public void doesNothingForEmptyIniFile() throws Exception {
    assertThat(project.getTypeSet().getAll(), empty());
  }

  @Test
  public void canConstructATypeFromASingleLineDefinition() throws Exception {
    populate(
      "[type foo]",
      "type = nullable(text)"
    );

    assertEquals(Nullable.of(Types.TEXT), project.getTypeSet().getRequired("foo").getUnderlyingType());
  }

  @Test
  public void firstTypeWins() throws Exception {
    List<Problem> warnings = new ArrayList<>();
    populate(p -> warnings.add(p),
        "[type foo]",
        "type = nullable(text)",
        "[type foo]",
        "type = integer"
    );

    assertThat(
      project.getTypeSet().getRequired("foo").getUnderlyingType(),
      equalTo(Nullable.TEXT)
    );
    assertThat(warnings, contains(
        ConfigProblems.get().duplicateSection("type foo",
            URI.create("test:/project.ini#I0L1C1"), URI.create("test:/project.ini#I33L3C1"))
    ));
  }

  @Test
  public void canConstructAStructFromASingleLineDefinition() throws Exception {
    Struct expectedType = Struct.of("foo", Types.TEXT, "bar", Nullable.of(Types.INTEGER));
    populate(
        "[type my-struct]",
        "type = struct(foo: text, bar: nullable(integer))");

    assertThat(
      project.getTypeSet().getRequired("my-struct").getUnderlyingType(),
      equalTo(expectedType)
    );
  }

  @Test
  public void canConstructAStructFromAMultiLineDefinition() throws Exception {
    Struct expectedType = Struct.of("foo", Types.TEXT, "bar", Nullable.of(Types.INTEGER));
    populate(
        "[type my-struct]",
        "type.foo = text",
        "type.bar = nullable(integer)"
    );

    assertThat(project.getTypeSet().getRequired("my-struct").getUnderlyingType(), equalTo(expectedType));
  }

  @Test
  public void aBadMultilineDefinitionDoesNotCreateAnIncompleteType() throws Exception {
    populate(
        "[type my-struct]",
        "type.foo = text",
        "type.bar = integer unexpected text"
    );

    FailedObjectException ex = assertThrows(FailedObjectException.class, () -> project.getTypeSet().get("my-struct"));

    Problem p = ex.getProblem();

    assertThat(
        p,
        allOf(
          equalIgnoringChildren(
              Problems.get(GeneralProblems.class).failedResourceLookedUp(
                  "my-struct",
                  URI.create("test:/project.ini#I0L1C1"),
                  CanonicalType.class
              )
            .affecting(CanonicalType.class, "my-struct")
          ),
          hasAncestorProblem(isError(UNEXPECTED_TOKEN))
        )
    );
  }

  @Test
  public void cannotReuseAttributeNamesInMultilineDefinition() throws Exception {
    populate(
        "[type my-struct]",
        "type.foo = text",
        "type.foo = integer"
    );


    FailedObjectException ex = assertThrows(FailedObjectException.class, () -> project.getTypeSet().get("my-struct"));
    assertThat(ex.getProblem(), hasAncestorProblem(
            isProblem(Severity.ERROR, is("Attribute 'foo' has been defined more than once"))
        )
    );
  }

  @Test
  public void errorWhenTypeNotSpecified() throws Exception {
    populate(
        "[type my-struct]"
    );

    FailedObjectException ex = assertThrows(FailedObjectException.class, () -> project.getTypeSet().get("my-struct"));
    assertThat(ex.getProblem(), hasAncestorProblem(
      isProblem(Severity.ERROR, is("requires either a type or type.<ATTR_NAME> entry(s)"))
    )
    );
  }

  @Test
  public void errorWhenTypeNotSpecifiedAndExtraAttributesExist() throws Exception {
    populate(
        "[type my-struct]",
        "types.x = integer" // should have been 'type.x'
    );

    FailedObjectException ex = assertThrows(FailedObjectException.class, () -> project.getTypeSet().get("my-struct"));
    assertThat(ex.getProblem(), hasAncestorProblem(
        isProblem(Severity.ERROR, is("requires either a type or type.<ATTR_NAME> entry(s)"))
        )
    );
    assertThat(ex.getProblem(), hasAncestorProblem(
        isProblem(Severity.WARNING, is("spurious attribute - types.x"))
        )
    );
  }

}
