/*
 * SPDX-FileCopyrightText: NVIDIA CORPORATION & AFFILIATES
 * Copyright (c) 2012-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 * SPDX-License-Identifier: LicenseRef-NvidiaProprietary
 *
 * This software is available to you under a choice of one of two
 * licenses.  You may choose to be licensed under the terms of the GNU
 * General Public License (GPL) Version 2, available from the file
 * COPYING in the main directory of this source tree, or the
 * OpenIB.org BSD license below:
 *
 *     Redistribution and use in source and binary forms, with or
 *     without modification, are permitted provided that the following
 *     conditions are met:
 *
 *      - Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer.
 *
 *      - Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, 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.
 *
 */

#pragma once

#include <memory>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include "agg_types.h"
#include "port_data.h"
#include "sub_tree_score.h"
#include "tree_node.h"

struct DescendantGroup;
struct QuasiFatTreeAnInfo;
struct JobSubTreeScore;
struct JobSubTreeInfo;
struct DfpIslandInfo;
struct BestRouteInfo;
class AggNodeFabricInfo;
class TreeNode;
class AggNode;

typedef std::vector<std::unique_ptr<TreeNode>> TreeNodesVecUniquePtr;
typedef std::unordered_map<coordinate_t, std::unique_ptr<DfpIslandInfo>> MapIslandToDfpIslandInfo;
typedef std::queue<AggNodeFabricInfo*> AggNodeFabricInfoQ;
typedef std::unordered_map<AggNodeFabricInfo*, std::unique_ptr<QuasiFatTreeAnInfo>> MapANToQuasiFatTreeInfo;
typedef std::map<const AggNodeFabricInfo*, QuasiFatTreeAnInfo*> MapNodeToQuasiFatTreeAnInfo;
typedef std::vector<DescendantGroup*> VecPtrDescendantGroup;
typedef std::list<DescendantGroup> ListDescendantGroup;
typedef std::unordered_set<AggNodeFabricInfo*> SetANInfo;
typedef std::unordered_map<AggNodeFabricInfo*, BestRouteInfo> MapANToBestRouteInfo;
typedef std::unordered_map<uint64_t, DescendantGroup*> MapHashToDescendantGroup;
typedef std::unordered_map<const AggNode*, std::unordered_set<const AggNode*>> MapNodeToNodes;
typedef std::unordered_map<AggNodeFabricInfo*, int> MapANInfoToCount;

class OnDemandTreeCreator
{
    TreeNodesVecUniquePtr m_tree_node_repo;

   public:
    OnDemandTreeCreator() {}
    // was Fabric::BuildQuasiFatTreeForJob
    int CreateTree(const SetPortDataConstPtr& compute_ports,
                   const JobResource& job_resource,
                   const SharpExtJobId& external_job_id,
                   JobSubTreeInfo& job_sub_tree_info,
                   JobSubTreeScore& sub_tree_score);

   private:
    int BuildDynamicQuasiFatTree(const SetAnFabricInfoPtr& leaf_nodes_set,
                                 const JobResource& job_resource,
                                 JobSubTreeInfo& job_sub_tree_info,
                                 JobSubTreeScore& sub_tree_score);

    int QuasiFatTreeBFSBottomUp(AggNodeFabricInfoQ& agg_node_info_q,
                                MapANToQuasiFatTreeInfo& agg_node_to_quasi_fat_tree_info,
                                MapNodeToQuasiFatTreeAnInfo& quasi_fat_tree_an_info_of_roots,
                                JobSubTreeInfo& job_sub_tree_info,
                                const JobResource& job_resource,
                                ListDescendantGroup& all_descendant_groups,
                                const SetAnFabricInfoPtr& leaf_nodes_set,
                                bool till_rank0);

    int QuasiFatTreeBFSUpBottom(const JobResource& job_resource,
                                QuasiFatTreeAnInfo* root_quasi_an_info,
                                JobSubTreeInfo& job_sub_tree_info,
                                MapANToQuasiFatTreeInfo& agg_node_to_quasi_fat_tree_info,
                                JobSubTreeScore& sub_tree_score,
                                SetANInfo& used_agg_nodes);

    int QuasiFatTreeSelectBestRoute(MapANToBestRouteInfo& leaves_route,
                                    JobSubTreeInfo& job_sub_tree_info,
                                    MapANToQuasiFatTreeInfo& agg_node_to_quasi_fat_tree_info,
                                    MapNodeToQuasiFatTreeAnInfo& next_rank_quasi_fat_tree_an_info,
                                    SetANInfo& used_agg_nodes);

    int DfpLinkIslandGraphs(const MapIslandToDfpIslandInfo& map_island_to_info,
                            const JobResource& job_resource,
                            JobSubTreeInfo& job_sub_tree_info,
                            JobSubTreeScore& sub_tree_score,
                            SetANInfo& used_agg_nodes);

    int DfpFindPathThruIslands(const MapIslandToDfpIslandInfo& map_island_to_info,
                               const JobResource& job_resource,
                               JobSubTreeInfo& sub_tree_info,
                               std::unordered_set<const AggNode*>& best_tree_nodes,
                               MapNodeToNodes& map_node_to_siblings,
                               AggNode const*& p_max_degree_node);

    int LinkNodes(const AggNodeFabricInfo* p_parent_agg_node,
                  const AggNodeFabricInfo* p_child_agg_node,
                  JobSubTreeInfo& job_sub_tree_info,
                  SetANInfo& used_agg_nodes) const;

    int LinkDFPRootNodes(const MapIslandToDfpIslandInfo& map_island_to_info,
                         AggNodeFabricInfo* p_parent_node,
                         AggNodeFabricInfo* p_child_node,
                         JobSubTreeInfo& job_sub_tree_info,
                         SetANInfo& used_agg_nodes);

    const AggNode* FindTreeCenter(const MapNodeToNodes& map_node_to_adjacents) const;

    int UpdateQuasiFatTreeJobSubTreeInfo(JobSubTreeInfo& job_sub_tree_info, JobSubTreeScore& sub_tree_score);

    void CombineGroups(const QuasiFatTreeAnInfo& quasi_fat_tree_info,
                       VecPtrDescendantGroup& combined_groups,
                       JobSubTreeInfo& job_sub_tree_info,
                       ListDescendantGroup& all_descendant_groups);

    void CombineGroupsWithRawGroup(VecPtrDescendantGroup& combined_groups,
                                   DescendantGroup& raw_group,
                                   JobSubTreeInfo& job_sub_tree_info,
                                   const QuasiFatTreeAnInfo& quasi_fat_tree_info,
                                   ListDescendantGroup& all_descendant_groups);

    bool CheckIfAggNodeSatisfyJobRequest(const AggNodeFabricInfo& agg_node, const JobResource& job_resource);

    OnDemandTreeCreator(const OnDemandTreeCreator&) = delete;
    OnDemandTreeCreator(OnDemandTreeCreator&&) = delete;
    OnDemandTreeCreator& operator=(const OnDemandTreeCreator&) = delete;
};
