/****************************************************************************
 *   This file is part of the aGrUM/pyAgrum library.                        *
 *                                                                          *
 *   Copyright (c) 2005-2026 by                                             *
 *       - Pierre-Henri WUILLEMIN(_at_LIP6)                                 *
 *       - Christophe GONZALES(_at_AMU)                                     *
 *                                                                          *
 *   The aGrUM/pyAgrum library is free software; you can redistribute it    *
 *   and/or modify it under the terms of either :                           *
 *                                                                          *
 *    - the GNU Lesser General Public License as published by               *
 *      the Free Software Foundation, either version 3 of the License,      *
 *      or (at your option) any later version,                              *
 *    - the MIT license (MIT),                                              *
 *    - or both in dual license, as here.                                   *
 *                                                                          *
 *   (see https://agrum.gitlab.io/articles/dual-licenses-lgplv3mit.html)    *
 *                                                                          *
 *   This aGrUM/pyAgrum library is distributed in the hope that it will be  *
 *   useful, but WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,          *
 *   INCLUDING BUT NOT LIMITED TO THE WARRANTIES MERCHANTABILITY or FITNESS *
 *   FOR A PARTICULAR PURPOSE  AND NONINFRINGEMENT. IN NO EVENT SHALL THE   *
 *   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
 *   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,        *
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR  *
 *   OTHER DEALINGS IN THE SOFTWARE.                                        *
 *                                                                          *
 *   See LICENCES for more details.                                         *
 *                                                                          *
 *   SPDX-FileCopyrightText: Copyright 2005-2026                            *
 *       - Pierre-Henri WUILLEMIN(_at_LIP6)                                 *
 *       - Christophe GONZALES(_at_AMU)                                     *
 *   SPDX-License-Identifier: LGPL-3.0-or-later OR MIT                      *
 *                                                                          *
 *   Contact  : info_at_agrum_dot_org                                       *
 *   homepage : http://agrum.gitlab.io                                      *
 *   gitlab   : https://gitlab.com/agrumery/agrum                           *
 *                                                                          *
 ****************************************************************************/


#pragma once

#include <agrum/base/graphs/algorithms/generic/moralization.h>

namespace gum::graph {

  /// @cond INTERNAL
  inline void _marryParents_(const NodeSet& parents, UndiGraph& g) {
    for (auto it1 = parents.begin(); it1 != parents.end(); ++it1) {
      auto it2 = it1;
      for (++it2; it2 != parents.end(); ++it2)
        g.addEdge(*it1, *it2);
    }
  }

  /// @endcond

  template < GUM_DiGraphable G >
  UndiGraph moralGraph(const G& g) {
    UndiGraph moral;
    for (const auto node: g.nodes())
      moral.addNodeWithId(node);

    if constexpr (GUM_MixedGraphable< G >) {
      for (const auto node: g.nodes()) {
        for (const auto p: g.parents(node))
          moral.addEdge(node, p);
        for (const auto n: g.neighbours(node))
          moral.addEdge(node, n);
      }

      NodeSet already;
      for (const auto node: g.nodes()) {
        if (already.contains(node)) continue;
        already.insert(node);

        NodeSet par      = g.parents(node);
        NodeSet frontier = g.neighbours(node);
        while (!frontier.empty()) {
          const NodeId nei = frontier.popFirst();
          if (already.contains(nei)) continue;
          already.insert(nei);
          par += g.parents(nei);
          frontier += g.neighbours(nei) - already;
        }

        _marryParents_(par, moral);
      }
    } else {
      for (const auto node: g.nodes()) {
        const auto& par = g.parents(node);
        for (const auto p: par)
          moral.addEdge(node, p);
        _marryParents_(par, moral);
      }
    }
    return moral;
  }

  template < GUM_DiGraphable G >
  UndiGraph moralizedAncestralGraph(const G& g, const NodeSet& query) {
    if constexpr (GUM_MixedGraphable< G >) {
      MixedGraph ancestral;
      NodeSet    frontier{query};
      for (const auto n: query)
        ancestral.addNodeWithId(n);

      while (!frontier.empty()) {
        const NodeId current = *frontier.begin();
        frontier.erase(current);

        for (const auto p: g.parents(current)) {
          if (!ancestral.existsNode(p)) {
            ancestral.addNodeWithId(p);
            frontier.insert(p);
          }
          ancestral.addArc(p, current);
        }
        for (const auto n: g.neighbours(current)) {
          if (!ancestral.existsNode(n)) {
            ancestral.addNodeWithId(n);
            frontier.insert(n);
          }
          ancestral.addEdge(n, current);
        }
      }
      return moralGraph(ancestral);

    } else {
      UndiGraph res;
      NodeSet   frontier{query};

      while (!frontier.empty()) {
        const NodeId current = *frontier.begin();
        frontier.erase(current);
        res.addNodeWithId(current);
        for (const auto p: g.parents(current))
          if (!res.existsNode(p) && !frontier.contains(p)) frontier.insert(p);
      }

      for (const auto node: res.nodes()) {
        const auto& par = g.parents(node);
        for (const auto p: par)
          res.addEdge(node, p);
        _marryParents_(par, res);
      }
      return res;
    }
  }

}   // namespace gum::graph
