package parser

// CodeParseFanInComplete reports whether all code files for a snapshot have been
// accounted for (parsed, skipped, or permanently failed).
func CodeParseFanInComplete(expected, processed, pathCount, snapshotCodeFiles int) bool {
	// Completion is measured ONLY by the distinct processed-path count reaching
	// the expected code-file total. Two other signals are intentionally NOT used:
	//  - `processed` (the scalar counter) can be inflated above the true distinct
	//    count by reconcile/increment interactions.
	//  - `snapshotCodeFiles` (the repo-sync snapshot_files inventory count) reads a
	//    collection whose value can be momentarily partial; treating
	//    pathCount>=snapshotCodeFiles as complete let finalize seal a truncated
	//    snapshot graph at ~9 files (the premature-seal bug), which the terminal
	//    "already finalized" guard then made permanent.
	_ = processed
	_ = snapshotCodeFiles
	if expected <= 0 {
		return true
	}
	return pathCount >= expected
}

// CodeParseFailureRate returns failed / expected in [0,1], or 0 when expected is 0.
func CodeParseFailureRate(failed, expected int) float64 {
	if expected <= 0 || failed <= 0 {
		return 0
	}
	return float64(failed) / float64(expected)
}

// CodeParseStageStatus picks the code_parse stage status after fan-in completes.
func CodeParseStageStatus(failed, expected int, threshold float64) string {
	if expected <= 0 {
		return "completed"
	}
	if threshold > 0 && CodeParseFailureRate(failed, expected) >= threshold {
		return "failed"
	}
	return "completed"
}

// AccountedCodeFiles returns the best-known number of code files with recorded outcomes.
func AccountedCodeFiles(processed, pathCount int) int {
	if pathCount > processed {
		return pathCount
	}
	return processed
}
