package com.correx.core.transitions.analysis

import com.correx.core.events.types.StageId
import com.correx.core.transitions.analysis.canonicalization.CycleCanonicalizer.canonicalize
import com.correx.core.transitions.graph.WorkflowGraph
import com.correx.core.transitions.state.CycleDfs
import com.correx.core.transitions.state.VisitState

internal class CycleExtractor(
    private val adjacencyBuilder: DeterministicAdjacencyBuilder,
    private val dfs: CycleDfs,
) {

    fun extract(graph: WorkflowGraph): List<DetectedCycle> {

        val adjacency = adjacencyBuilder.build(graph)

        val state = mutableMapOf<StageId, VisitState>()
        val path = mutableListOf<StageId>()

        val cycles = mutableListOf<DetectedCycle>()

        val sortedNodes = graph.stageIds
            .sortedBy { it.value }

        for (node in sortedNodes) {
            if (state[node] == null) {
                dfs.dfs(node, adjacency, state, path, cycles)
            }
        }

        return canonicalize(cycles)
    }
}
