package com.correx.core.validation.approval

import com.correx.core.validation.model.ValidationReport
import com.correx.core.validation.model.ValidationSeverity

class ApprovalTrigger {

    /**
     * Evaluates whether a validation report requires human approval.
     *
     * All approvals produced here are implicitly **Tier.T2 (REVERSIBLE)** — validation decisions
     * affect workflow progression but not external state. This tier will be made explicit on
     * [ApprovalRequest] once the risk model (Epic 12, task 4) is wired in.
     */
    fun evaluate(report: ValidationReport): ApprovalRequest? {

        val errors = report.sections
            .flatMap { it.issues }
            .count { it.severity == ValidationSeverity.ERROR }

        val warnings = report.sections
            .flatMap { it.issues }
            .count { it.severity == ValidationSeverity.WARNING }

        val hasCyclePolicyIssue = report.sections
            .flatMap { it.issues }
            .any { it.code == "CYCLE_POLICY_MISSING" }

        val risk = ValidationRiskStats(
            errorCount = errors,
            warningCount = warnings,
            hasCyclePoliciesMissing = hasCyclePolicyIssue
        )

        // decision boundary (still NOT execution)
        if (errors > 0 || hasCyclePolicyIssue) {
            return ApprovalRequest(
                sessionId = null,
                riskSummary = risk,
                validationReport = report
            )
        }

        return null
    }
}
