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

import java.io.File;
import java.net.URI;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;

import com.google.common.base.Strings;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import nz.org.riskscape.config.Config;
import nz.org.riskscape.config.ConfigProblems;
import nz.org.riskscape.config.ConfigSection;
import nz.org.riskscape.config.ini4j.Ini4jConfigConstants;
import nz.org.riskscape.config.ini4j.Ini4jConfigSection;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.resource.Resource;
import nz.org.riskscape.engine.resource.ResourceFactory;
import nz.org.riskscape.engine.resource.ResourceProblems;
import nz.org.riskscape.ini.IniFile;
import nz.org.riskscape.ini.IniParser2;
import nz.org.riskscape.ini.Section;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.ProblemSink;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * RiskScape {@link Config} implementation, based on our home-brew ini file parser -
 * {@link IniParser2}.
 */
@RequiredArgsConstructor
@Slf4j
public class IniConfig implements Config, Ini4jConfigConstants {

  /**
   * Testing constructor to build ini config from an already parsed inifile, without processing any
   * imports
   */
  public static IniConfig fromIniFile(URI location, IniFile inifile) {
    return fromIniFile(location, inifile, ProblemSink.DEVNULL);
  }

  /**
   * Testing constructor to build ini config from an already parsed inifile, without processing any
   * imports
   */
  public static IniConfig fromIniFile(URI location, IniFile inifile, ProblemSink problemSink) {
    IniConfig config = new IniConfig(location);
    config.add(inifile, location)
        .stream()
        .forEach(problem -> problemSink.accept(problem));
    return config;
  }


  private static final String FILE_PROTO = "file";

  @RequiredArgsConstructor
  static class Builder implements Ini4jConfigConstants {

    final ResourceFactory factory;
    final IniConfig building;
    final List<Problem> problems = new LinkedList<>();

    IniFile loadInifile(URI location, String prefix) {
      Resource resource = factory.load(location);
      try {
        IniParser2 parser = new IniParser2();
        IniFile root = parser.parse(resource.getContentAsString());

        List<Section> projectSections = root.getSections()
            .stream()
            .filter(s -> s.getName().equals(PROJECT_SECTION))
            .toList();

        Section projectSection = null;

        if (projectSections != null) {
          for (int i = 0; i < projectSections.size(); i++) {
            if (i == 0) {
              // We use the first project section defined
              projectSection = projectSections.get(i);
            } else {
              // and warn for every other project section that exists
              problems.add(ConfigProblems.get().duplicateSection(PROJECT_SECTION, location, location));
            }
          }
        }
        problems.addAll(
          building.add(root, resource.getLocation(), Strings.isNullOrEmpty(prefix) ? "" : prefix + " ")
        );

        if (projectSection != null) {
          addImports(projectSection, location);
        }

        return root;
      } catch (RuntimeException e) {
        throw new RiskscapeException(Problems.foundWith(Config.class, location.toString(), Problems.caught(e)));
      }
    }

    private void addImports(Section section, URI uri) {
      if (section != null) {
        // look for type specific imports, import them
        for (Entry<String, String> entry : Ini4jConfigSection.TYPE_PREFIXES.entrySet()) {
          String importType = entry.getKey();

          List<String> imports = section.getAll(importType);

          if (imports == null) {
            continue;
          }

          for (String importThis : imports) {
            // should this be a warning?  Or accept it and allow other types apart from ini to be imported using these
            // statements?
            if (!importThis.endsWith(".ini")) {
              continue;
            }
            // users may use windows style separators which need to be translated to forward slashes.
            URI importLocation = uri.resolve(importThis.replaceAll("\\\\", "/"));
            log.debug("Processing import {}", importLocation);
            loadInifile(importLocation, entry.getValue());
          }
        }
      }

      // now untyped imports
      List<String> imports = section.getAll(IMPORT_KEY);
      if (imports != null) {
        for (String untypedImport : imports) {
          // users may use windows style separators which need to be translated to forward slashes.
          URI importLocation = uri.resolve(untypedImport.replaceAll("\\\\", "/"));
          log.debug("Processing import {}", importLocation);
          loadInifile(importLocation, null);
        }
      }
    }

    void loadFromFiles(URI base) throws ProblemException {
      File baseFile = Paths.get(base).toFile();

      if (!baseFile.exists()) {
        throw new ProblemException(ResourceProblems.get().notFound(base));
      }

      URI projectIniLocation;
      File dir;
      if (baseFile.isDirectory()) {
        dir = baseFile;
        projectIniLocation = base.resolve(DEFAULT_PROJECT_INI);
      } else {
        // nb if we want to allow auto import from a dir, this is where we'll do it, but we'll need to know if
        // the dir was explicitly given or not - probably don't want to autoimport from pwd without `-P .`
        dir = baseFile.getParentFile();
        projectIniLocation = base;
      }

      loadInifile(projectIniLocation, null);

      boolean autoimport = "true".equals(
        building.getSection(PROJECT_SECTION)
          .flatMap(section -> section.getOne(AUTOIMPORT_KEY))
          .map(ror -> ror.orElse(null))
          .orElse(AUTOIMPORT_DEFAULT)
      );

      if (autoimport) {
        addRecursively(dir, 0);
      }
    }


    void addRecursively(File dir, int rCount) {
      if (!dir.isDirectory() || !dir.canRead()) {
        return;
      }

      // add in files from this dir
      File[] iniFiles = dir.listFiles((d, name) -> name.endsWith(INI_SUFFIX));
      for (File inifile : iniFiles) {
        String prefix = getWellKnownTypePrefix(inifile.getName());

        // ignore files that don't begin with a well known prefix
        if (prefix != null) {
          loadInifile(inifile.toURI(), prefix);
        }
      }

      // too many open files likely to play havoc
      if (rCount == RECURSION_LIMIT) {
        log.warn("Recursion limit reached, not descending in to directories below {}", dir);
        return;
      }
      rCount++;

      // now descend in to any subdirs
      for (File subdir : dir.listFiles(file -> file.isDirectory())) {
        addRecursively(subdir, rCount);
      }
    }
  }

  /**
   * Attempt to build a {@link IniConfig} instance from the given URI.  Will process any top level import keys to
   * recursively load other files.
   */
  public static ResultOrProblems<IniConfig> load(URI base, ResourceFactory factory) {
    Builder builder = new Builder(factory, new IniConfig(base));
    try {
      if (FILE_PROTO.equals(base.getScheme())) {
        builder.loadFromFiles(base);
      } else {
        builder.loadInifile(base, null);
      }
    } catch (ProblemException e) {
      return e.toResult();
    } catch (RiskscapeException e) {
      return ResultOrProblems.failed(Problems.caught(e));
    }

    if (Problem.hasErrors(builder.problems)) {
      return ResultOrProblems.failed(builder.problems);
    }

    return ResultOrProblems.of(builder.building, builder.problems);
  }

  @Getter
  private final URI rootLocation;
  private final LinkedHashMap<String, IniConfigSection> sections = new LinkedHashMap<>();

  @Override
  public List<ConfigSection> getAll() {
    return sections.values().stream().collect(Collectors.toList());
  }

  @Override
  public Optional<ConfigSection> getSection(String name) {
    return Optional.ofNullable(sections.get(name));
  }

  public List<Problem> add(IniFile ini, URI location) {
    return add(ini, location, "");
  }

  public List<Problem> add(IniFile ini, URI location, String implicitPrefix) {

    boolean wasFirst = sections.isEmpty();

    LinkedList<Problem> problems = new LinkedList<>();
    for (Section section : ini.getSections()) {
     String nameToUse;
      if (section.getName().equals(PROJECT_SECTION)) {
        nameToUse = PROJECT_SECTION + " " + location;
      } else {
        if (implicitPrefix != null && !section.getName().startsWith(implicitPrefix)) {
          nameToUse= implicitPrefix + section.getName();
        } else {
          nameToUse = section.getName();
        }
      }

      IniConfigSection newSection = new IniConfigSection(location, nameToUse, section);
        // we use the derived name, rather than the declared name, so we can detect dupes with implicit prefix
        // logic applied
      IniConfigSection existing = this.sections.get(nameToUse);

      if (existing != null) {
        problems.add(ConfigProblems.get().duplicateSection(
          newSection.getName(),
          existing.getLocation(),
          newSection.getLocation()
        ));
      } else {
        log.debug("Adding section {}", newSection.getName());
        // register the first ini files project  as just 'project' - all the others are available with the
        // project prefix followed by the uri
        if (section.getName().equals(PROJECT_SECTION) && wasFirst) {
          this.sections.put(PROJECT_SECTION,
              new IniConfigSection(location, PROJECT_SECTION, section)
          );
        } else {
          this.sections.put(newSection.getName(), newSection);
        }
      }
    }

    return problems;
  }
}
