# #region data_purity [C:5] [TYPE Module] [SEMANTICS clean-release, data, purity, validate, manifest]
# @BRIEF Evaluate manifest purity counters and emit blocking violations for prohibited artifacts.
# @LAYER Domain
# @RELATION IMPLEMENTS -> [ComplianceStage]
# @RELATION DEPENDS_ON -> [ComplianceStageBase]
# @INVARIANT  prohibited_detected_count > 0 always yields BLOCKED stage decision.
# @SIDE_EFFECT  None (read-only validation)
# @DATA_CONTRACT  Manifest -> DataPurityVerdict

from __future__ import annotations

from ....core.logger import belief_scope, logger
from ..enums import ComplianceDecision, ComplianceStageName, ViolationSeverity
from .base import ComplianceStageContext, StageExecutionResult, build_violation


# #region DataPurityStage [TYPE Class]
# @BRIEF Validate manifest summary for prohibited artifacts.
# @PRE  context.manifest.content_json contains summary block or defaults to safe counters.
# @POST  Returns PASSED when no prohibited artifacts are detected, otherwise BLOCKED with violations.
class DataPurityStage:
    stage_name = ComplianceStageName.DATA_PURITY

    def execute(self, context: ComplianceStageContext) -> StageExecutionResult:
        with belief_scope("DataPurityStage.execute"):
            summary = context.manifest.content_json.get("summary", {})
            prohibited_count = int(summary.get("prohibited_detected_count", 0) or 0)
            included_count = int(summary.get("included_count", 0) or 0)

            logger.reason(
                f"Data purity evaluation run={context.run.id} included={included_count} prohibited={prohibited_count}"
            )

            if prohibited_count <= 0:
                return StageExecutionResult(
                    decision=ComplianceDecision.PASSED,
                    details_json={
                        "included_count": included_count,
                        "prohibited_detected_count": 0,
                    },
                    violations=[],
                )

            violation = build_violation(
                run_id=context.run.id,
                stage_name=self.stage_name,
                code="DATA_PURITY_PROHIBITED_ARTIFACTS",
                message=f"Detected {prohibited_count} prohibited artifact(s) in manifest snapshot",
                severity=ViolationSeverity.CRITICAL,
                evidence_json={
                    "prohibited_detected_count": prohibited_count,
                    "manifest_id": context.manifest.id,
                },
                blocked_release=True,
            )
            return StageExecutionResult(
                decision=ComplianceDecision.BLOCKED,
                details_json={
                    "included_count": included_count,
                    "prohibited_detected_count": prohibited_count,
                },
                violations=[violation],
            )


# #endregion DataPurityStage

# #endregion data_purity
