package com.correx.core.validation.graph

import com.correx.core.validation.model.ValidationContext
import com.correx.core.validation.model.ValidationIssue
import com.correx.core.validation.model.ValidationLocation
import com.correx.core.validation.model.ValidationSection
import com.correx.core.validation.model.ValidationSeverity
import com.correx.core.validation.pipeline.Validator

class GraphValidator : Validator {

    override suspend fun validate(context: ValidationContext): ValidationSection {

        val graph = context.graph
        val issues = mutableListOf<ValidationIssue>()

        // 1. start node exists (redundant safety check)
        if (graph.start !in graph.stages) {
            issues += ValidationIssue(
                code = "GRAPH_START_INVALID",
                message = "Start stage does not exist in graph",
                severity = ValidationSeverity.ERROR
            )
        }

        // 2. dangling transitions
        graph.transitions.forEach { edge ->
            if (edge.from !in graph.stages || edge.to !in graph.stages) {
                issues += ValidationIssue(
                    code = "GRAPH_DANGLING_TRANSITION",
                    message = "Transition references missing stage",
                    severity = ValidationSeverity.ERROR,
                    location = ValidationLocation.Graph(
                        transitionId = edge.id
                    )
                )
            }
        }

        // 3. cycles (ONLY attach, no interpretation)
        context.detectedCycles.forEach { cycle ->
            issues += ValidationIssue(
                code = "GRAPH_CYCLE_DETECTED",
                message = "Cycle detected: ${cycle.nodes}",
                severity = ValidationSeverity.INFO
            )
        }

        return ValidationSection(
            name = "graph",
            issues = issues
        )
    }
}
