from __future__ import annotations

from supersonar.models import ScanResult, Severity


SEVERITY_ORDER: dict[Severity, int] = {
    "low": 1,
    "medium": 2,
    "high": 3,
    "critical": 4,
}


def evaluate_gate(
    result: ScanResult,
    fail_on: Severity | None = None,
    max_issues: int | None = None,
) -> tuple[bool, list[str]]:
    failed_reasons: list[str] = []

    if fail_on is not None:
        threshold = SEVERITY_ORDER[fail_on]
        if any(SEVERITY_ORDER[issue.severity] >= threshold for issue in result.issues):
            failed_reasons.append(f"Detected issue severity >= '{fail_on}'")

    if max_issues is not None and len(result.issues) > max_issues:
        failed_reasons.append(f"Issue count {len(result.issues)} exceeds max_issues={max_issues}")

    return (len(failed_reasons) == 0, failed_reasons)

