"""Controller-closure baseline-proof gate (#529, criterion 6).

A controller (or any session) may close a tracking issue with a closure
report that summarizes validation. When that report calls a non-zero
test-suite exit an "expected pre-existing failure" (or baseline / known
failure) it must carry pre-merge proof; otherwise the closure buries an
unproven regression as an accepted baseline and weakens controller
confidence in the durable state.

This module fails closed on exactly that case by reusing the pre-merge
baseline proof verifier (#533). A closure report is allowed when it is
empty (no validation claim), a clean pass, or a baseline failure proven on
the PR pre-merge base commit (or a documented known-failure record that
predates the PR).
"""

from __future__ import annotations

from typing import Any

from premerge_baseline_proof import CLEAN_PASS, assess_premerge_baseline_proof


def assess_controller_closure_baseline_proof(
    closure_report: str | None,
) -> dict[str, Any]:
    """Assess whether an issue-closure report may proceed.

    Returns a dict with ``block``, ``proven``, ``label``, ``reasons``,
    ``skipped`` and ``safe_next_action``. Only blocks when the closure
    report claims a non-zero validation exit is an expected
    pre-existing/baseline failure without valid pre-merge proof.
    """
    text = (closure_report or "").strip()
    if not text:
        return {
            "block": False,
            "proven": True,
            "label": CLEAN_PASS,
            "reasons": [],
            "skipped": True,
            "safe_next_action": "",
        }

    result = assess_premerge_baseline_proof(text)
    block = bool(result.get("block"))
    return {
        "block": block,
        "proven": not block,
        "label": result.get("label"),
        "reasons": list(result.get("reasons") or []),
        "skipped": bool(result.get("skipped", False)),
        "safe_next_action": (
            result.get("safe_next_action")
            or (
                "provide pre-merge baseline proof (base commit, tested commit, "
                "command, exit status, failure signature) before closing on an "
                "expected pre-existing failure"
            )
        )
        if block
        else "",
    }
