/*
** Job Arranger for ZABBIX
** Copyright (C) 2025 Daiwa Institute of Research Ltd. All Rights Reserved.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/
package main

import (
	"jobarranger2/src/libs/golibs/common"
	"slices"
)

// buildAdjacency builds an adjacency list from flow records
func buildAdjacency(flows []common.RunFlowTable) map[uint64][]uint64 {
	adj := make(map[uint64][]uint64)
	for _, f := range flows {
		adj[f.StartInnerJobID] = append(adj[f.StartInnerJobID], f.EndInnerJobID)
	}
	return adj
}

// dfsCycleFinder performs DFS and collects all cycles
func dfsCycleFinder(u uint64, adj map[uint64][]uint64, visited, recStack map[uint64]bool,
	path []uint64, allCycles *[][]uint64) {

	visited[u] = true
	recStack[u] = true
	path = append(path, u)

	for _, v := range adj[u] {
		if !visited[v] {
			dfsCycleFinder(v, adj, visited, recStack, path, allCycles)
		} else if recStack[v] {
			// Found a cycle: extract cycle portion from path
			cycle := extractCycle(path, v)
			*allCycles = append(*allCycles, cycle)
		}
	}

	recStack[u] = false
}

// extractCycle gets the part of the path forming the cycle
func extractCycle(path []uint64, start uint64) []uint64 {
	for i, node := range path {
		if node == start {
			cycle := append([]uint64(nil), path[i:]...) // copy slice
			// cycle = append(cycle, start)                // complete the loop
			return cycle
		}
	}
	return nil
}

// FindAllCycles detects all cycles in the directed graph
func FindAllCycles(flows []common.RunFlowTable) [][]uint64 {
	adj := buildAdjacency(flows)
	visited := make(map[uint64]bool)
	recStack := make(map[uint64]bool)
	var allCycles [][]uint64

	for node := range adj {
		if !visited[node] {
			dfsCycleFinder(node, adj, visited, recStack, []uint64{}, &allCycles)
		}
	}

	return allCycles
}

func IsAllInSameLoop(innerJobIDs []uint64, flows []common.RunFlowTable) bool {
	cycles := FindAllCycles(flows)
	inLoopCount := 0

	for _, c := range cycles {
		// each cycle
		inLoopCount = 0
		for _, j := range c {
			for _, innerJobID := range innerJobIDs {
				if j == innerJobID {
					inLoopCount++
				}
			}
		}

	}

	return inLoopCount == 0 || inLoopCount == len(innerJobIDs)
}

func IsNoneInLoop(innerJobIDs []uint64, flows []common.RunFlowTable) bool {
	cycles := FindAllCycles(flows)
	for _, c := range cycles {
		for _, j := range c {
			if slices.Contains(innerJobIDs, j) {
				return false
			}
		}
	}

	return true
}
