/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.paimon.flink.action.cdc.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/** DFS sort algorithm for topological sorting of a DAG (Directed Acyclic Graph). */
public class DfsSort {
    public static <K> LinkedHashMap<K, K> sort(LinkedHashMap<K, K> depMap) {
        List<K> sortedKeys = sortKeys(depMap);
        LinkedHashMap<K, K> sortedMap = new LinkedHashMap<>();
        for (K key : sortedKeys) {
            sortedMap.put(key, depMap.get(key));
        }
        return sortedMap;
    }

    public static <K> List<K> sortKeys(LinkedHashMap<K, K> depMap) {

        Map<K, Set<K>> revMap = new LinkedHashMap<>();

        List<K> noDeps = new ArrayList<>();

        for (Map.Entry<K, K> entry : depMap.entrySet()) {
            K key = entry.getKey();
            K val = entry.getValue();

            if (val == null || !depMap.containsKey(val)) {
                noDeps.add(key);
            } else {
                revMap.computeIfAbsent(val, k -> new HashSet<>()).add(key);
            }
        }

        List<K> sorted = new ArrayList<>();

        Set<K> visited = new HashSet<>();
        Set<K> tempMark = new HashSet<>(); // for cycle reference detection

        for (Map.Entry<K, K> entry : depMap.entrySet()) {
            K key = entry.getKey();
            K val = entry.getValue();
            if (val == null || !depMap.containsKey(val)) {
                continue;
            }

            if (!visited.contains(key)) {
                dfs(key, revMap, sorted, visited, tempMark);
            }
        }

        Collections.reverse(noDeps);

        sorted.addAll(noDeps);

        Collections.reverse(sorted);

        return sorted;
    }

    private static <K> void dfs(
            K node, Map<K, Set<K>> revMap, List<K> sorted, Set<K> visited, Set<K> tempMark) {
        if (tempMark.contains(node)) {
            throw new IllegalArgumentException("Cycle detected: " + node);
        }
        if (visited.contains(node)) {
            return;
        }

        tempMark.add(node);

        // Process the dependencies
        for (K dependent : revMap.getOrDefault(node, Collections.emptySet())) {
            dfs(dependent, revMap, sorted, visited, tempMark);
        }

        tempMark.remove(node);
        visited.add(node);
        sorted.add(node);
    }
}
