<?php

declare(strict_types=1);

namespace App\Support\Ui\GovernanceArtifactTruth;

use App\Filament\Resources\BaselineSnapshotResource;
use App\Filament\Resources\EnvironmentReviewResource;
use App\Filament\Resources\EvidenceSnapshotResource;
use App\Filament\Resources\ReviewPackResource;
use App\Models\BaselineSnapshot;
use App\Models\EnvironmentReview;
use App\Models\EvidenceSnapshot;
use App\Models\FindingExceptionDecision;
use App\Models\OperationRun;
use App\Models\ReviewPack;
use App\Models\StoredReport;
use App\Services\Baselines\BaselineSnapshotTruthResolver;
use App\Services\Baselines\SnapshotRendering\FidelityState;
use App\Support\Badges\BadgeCatalog;
use App\Support\Badges\BadgeDomain;
use App\Support\EnvironmentReviewCompletenessState;
use App\Support\EnvironmentReviewStatus;
use App\Support\Evidence\EvidenceCompletenessState;
use App\Support\OperationCatalog;
use App\Support\OperationRunLinks;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OpsUx\SummaryCountsNormalizer;
use App\Support\ReasonTranslation\ReasonPresenter;
use App\Support\ReasonTranslation\ReasonResolutionEnvelope;
use App\Support\ReviewPackStatus;
use App\Support\Ui\DerivedState\DerivedStateFamily;
use App\Support\Ui\DerivedState\DerivedStateKey;
use App\Support\Ui\DerivedState\RequestScopedDerivedStateStore;
use App\Support\Ui\OperatorExplanation\CountDescriptor;
use App\Support\Ui\OperatorExplanation\OperatorExplanationBuilder;
use Filament\Facades\Filament;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;

final class ArtifactTruthPresenter
{
    public function __construct(
        private readonly ReasonPresenter $reasonPresenter,
        private readonly BaselineSnapshotTruthResolver $snapshotTruthResolver,
        private readonly OperatorExplanationBuilder $operatorExplanationBuilder,
        private readonly RequestScopedDerivedStateStore $derivedStateStore,
    ) {}

    public function for(mixed $record): ?ArtifactTruthEnvelope
    {
        return match (true) {
            $record instanceof BaselineSnapshot => $this->forBaselineSnapshot($record),
            $record instanceof EvidenceSnapshot => $this->forEvidenceSnapshot($record),
            $record instanceof EnvironmentReview => $this->forEnvironmentReview($record),
            $record instanceof ReviewPack => $this->forReviewPack($record),
            $record instanceof StoredReport => $this->forStoredReport($record),
            $record instanceof FindingExceptionDecision => $this->forFindingExceptionDecision($record),
            $record instanceof OperationRun => $this->forOperationRun($record),
            default => null,
        };
    }

    public function forFresh(mixed $record): ?ArtifactTruthEnvelope
    {
        return match (true) {
            $record instanceof BaselineSnapshot => $this->forBaselineSnapshotFresh($record),
            $record instanceof EvidenceSnapshot => $this->forEvidenceSnapshotFresh($record),
            $record instanceof EnvironmentReview => $this->forEnvironmentReviewFresh($record),
            $record instanceof ReviewPack => $this->forReviewPackFresh($record),
            $record instanceof StoredReport => $this->forStoredReportFresh($record),
            $record instanceof FindingExceptionDecision => $this->forFindingExceptionDecisionFresh($record),
            $record instanceof OperationRun => $this->forOperationRunFresh($record),
            default => null,
        };
    }

    public function compressedOutcomeFor(
        mixed $record,
        SurfaceCompressionContext|string|null $context = null,
        bool $fresh = false,
    ): ?CompressedGovernanceOutcome {
        $truth = $fresh ? $this->forFresh($record) : $this->for($record);

        if (! $truth instanceof ArtifactTruthEnvelope) {
            return null;
        }

        $resolvedContext = $this->resolveCompressionContext($truth, $context);

        if (! $record instanceof Model) {
            return $this->compressedOutcomeFromEnvelope($truth, $resolvedContext);
        }

        $key = DerivedStateKey::fromModel(
            DerivedStateFamily::ArtifactTruth,
            $record,
            $resolvedContext->cacheVariant(),
        );

        /** @var CompressedGovernanceOutcome $compressedOutcome */
        $compressedOutcome = $fresh
            ? $this->derivedStateStore->resolveFresh(
                $key,
                fn (): CompressedGovernanceOutcome => $this->buildCompressedOutcome($truth, $resolvedContext),
                DerivedStateFamily::ArtifactTruth->defaultFreshnessPolicy(),
                DerivedStateFamily::ArtifactTruth->allowsNegativeResultCache(),
            )
            : $this->derivedStateStore->resolve(
                $key,
                fn (): CompressedGovernanceOutcome => $this->buildCompressedOutcome($truth, $resolvedContext),
                DerivedStateFamily::ArtifactTruth->defaultFreshnessPolicy(),
                DerivedStateFamily::ArtifactTruth->allowsNegativeResultCache(),
            );

        return $compressedOutcome;
    }

    /**
     * @return array<string, mixed>|null
     */
    public function surfaceStateFor(
        mixed $record,
        SurfaceCompressionContext|string|null $context = null,
        bool $fresh = false,
    ): ?array {
        $truth = $fresh ? $this->forFresh($record) : $this->for($record);

        if (! $truth instanceof ArtifactTruthEnvelope) {
            return null;
        }

        $compressedOutcome = $this->compressedOutcomeFor($record, $context, $fresh);

        return $truth->toArray($compressedOutcome);
    }

    public function compressedOutcomeFromEnvelope(
        ArtifactTruthEnvelope $truth,
        SurfaceCompressionContext|string|null $context = null,
    ): CompressedGovernanceOutcome {
        return $this->buildCompressedOutcome(
            $truth,
            $this->resolveCompressionContext($truth, $context),
        );
    }

    public function forBaselineSnapshot(BaselineSnapshot $snapshot): ArtifactTruthEnvelope
    {
        return $this->resolveEnvelope(
            record: $snapshot,
            variant: 'baseline_snapshot',
            resolver: fn (): ArtifactTruthEnvelope => $this->buildBaselineSnapshotEnvelope($snapshot),
        );
    }

    public function forBaselineSnapshotFresh(BaselineSnapshot $snapshot): ArtifactTruthEnvelope
    {
        return $this->resolveEnvelope(
            record: $snapshot,
            variant: 'baseline_snapshot',
            resolver: fn (): ArtifactTruthEnvelope => $this->buildBaselineSnapshotEnvelope($snapshot),
            fresh: true,
        );
    }

    private function buildBaselineSnapshotEnvelope(BaselineSnapshot $snapshot): ArtifactTruthEnvelope
    {
        $snapshot->loadMissing('baselineProfile');

        $summary = is_array($snapshot->summary_jsonb) ? $snapshot->summary_jsonb : [];
        $hasItems = (int) ($summary['total_items'] ?? 0) > 0;
        $fidelity = FidelityState::fromSummary($summary, $hasItems);
        $effectiveSnapshot = $snapshot->baselineProfile !== null
            ? $this->snapshotTruthResolver->resolveEffectiveSnapshot($snapshot->baselineProfile)
            : null;
        $isHistorical = $this->snapshotTruthResolver->isHistoricallySuperseded($snapshot, $effectiveSnapshot);
        $gapReasons = is_array(Arr::get($summary, 'gaps.by_reason')) ? Arr::get($summary, 'gaps.by_reason') : [];
        $severeGapReasons = array_filter(
            $gapReasons,
            static fn (mixed $count, string $reason): bool => is_numeric($count) && (int) $count > 0 && $reason !== 'meta_fallback',
            ARRAY_FILTER_USE_BOTH,
        );
        $reasonCode = $this->snapshotTruthResolver->artifactReasonCode($snapshot, $effectiveSnapshot)
            ?? $this->firstReasonCode($severeGapReasons);
        $reason = $this->reasonPresenter->forArtifactTruth($reasonCode, 'artifact_truth');

        $artifactExistence = match (true) {
            $isHistorical => 'historical_only',
            $snapshot->isBuilding(), $snapshot->isIncomplete() => 'created_but_not_usable',
            ! $snapshot->isConsumable() => 'created_but_not_usable',
            default => 'created',
        };

        $contentState = match ($fidelity) {
            FidelityState::Full => $snapshot->isIncomplete()
                ? ($hasItems ? 'partial' : 'missing_input')
                : ($severeGapReasons === [] ? 'trusted' : 'partial'),
            FidelityState::Partial => $snapshot->isBuilding() ? 'missing_input' : 'partial',
            FidelityState::ReferenceOnly => $snapshot->isBuilding() ? 'missing_input' : 'reference_only',
            FidelityState::Unsupported => $snapshot->isBuilding() ? 'missing_input' : ($hasItems ? 'unsupported' : 'trusted'),
        };

        if (($snapshot->isBuilding() || $snapshot->isIncomplete()) && $reasonCode !== null) {
            $contentState = 'missing_input';
        }

        $freshnessState = match (true) {
            $snapshot->isBuilding() => 'unknown',
            $isHistorical => 'stale',
            default => 'current',
        };
        $supportState = in_array($contentState, ['reference_only', 'unsupported'], true) ? 'limited_support' : 'normal';
        $actionability = match (true) {
            $artifactExistence === 'historical_only' => 'none',
            $snapshot->isBuilding() => 'optional',
            $contentState === 'trusted' && $freshnessState === 'current' => 'none',
            $freshnessState === 'stale' => 'optional',
            in_array($contentState, ['reference_only', 'unsupported'], true) => 'optional',
            default => 'required',
        };

        [$primaryDomain, $primaryState, $primaryExplanation, $diagnosticLabel] = match (true) {
            $artifactExistence === 'historical_only' => [
                BadgeDomain::GovernanceArtifactExistence,
                'historical_only',
                $reason?->shortExplanation ?? 'This snapshot remains readable for history, but a newer complete snapshot is the current baseline truth.',
                BadgeCatalog::spec(BadgeDomain::BaselineSnapshotLifecycle, 'superseded')->label,
            ],
            $artifactExistence === 'created_but_not_usable' => [
                BadgeDomain::GovernanceArtifactExistence,
                'created_but_not_usable',
                $reason?->shortExplanation ?? 'A snapshot row exists, but it does not contain a trustworthy baseline artifact yet.',
                BadgeCatalog::spec(BadgeDomain::BaselineSnapshotLifecycle, $snapshot->lifecycleState()->value)->label,
            ],
            $contentState !== 'trusted' => [
                BadgeDomain::GovernanceArtifactContent,
                $contentState,
                $reason?->shortExplanation ?? $this->contentExplanation($contentState),
                $supportState === 'limited_support'
                    ? 'Support limited'
                    : BadgeCatalog::spec(BadgeDomain::BaselineSnapshotLifecycle, $snapshot->lifecycleState()->value)->label,
            ],
            default => [
                BadgeDomain::GovernanceArtifactContent,
                'trusted',
                $hasItems
                    ? 'Structured capture content is available for this baseline snapshot.'
                    : 'This empty baseline snapshot completed successfully and can still be used for compare.',
                BadgeCatalog::spec(BadgeDomain::BaselineSnapshotLifecycle, $snapshot->lifecycleState()->value)->label,
            ],
        };

        return $this->makeEnvelope(
            artifactFamily: 'baseline_snapshot',
            artifactKey: 'baseline_snapshot:'.$snapshot->getKey(),
            workspaceId: (int) $snapshot->workspace_id,
            tenantId: null,
            executionOutcome: null,
            artifactExistence: $artifactExistence,
            contentState: $contentState,
            freshnessState: $freshnessState,
            publicationReadiness: null,
            supportState: $supportState,
            actionability: $actionability,
            primaryDomain: $primaryDomain,
            primaryState: $primaryState,
            primaryExplanation: $primaryExplanation,
            diagnosticLabel: $diagnosticLabel,
            reason: ArtifactTruthCause::fromReasonResolutionEnvelope($reason, ReasonPresenter::GOVERNANCE_ARTIFACT_TRUTH_ARTIFACT),
            nextActionLabel: $this->nextActionLabel(
                $actionability,
                $reason,
                match ($actionability) {
                    'required' => 'Inspect the related capture diagnostics before using this snapshot',
                    'optional' => 'Review the capture diagnostics before comparing this snapshot',
                    default => null,
                },
            ),
            nextActionUrl: null,
            relatedRunId: null,
            relatedArtifactUrl: BaselineSnapshotResource::getUrl('view', ['record' => $snapshot], panel: 'admin'),
            includePublicationDimension: false,
            countDescriptors: [
                new CountDescriptor(
                    label: 'Captured items',
                    value: (int) ($summary['total_items'] ?? 0),
                    role: CountDescriptor::ROLE_EVALUATION_OUTPUT,
                ),
                new CountDescriptor(
                    label: 'Evidence gaps',
                    value: (int) (Arr::get($summary, 'gaps.count', 0)),
                    role: CountDescriptor::ROLE_COVERAGE,
                    qualifier: (int) (Arr::get($summary, 'gaps.count', 0)) > 0 ? 'review needed' : null,
                ),
            ],
            displayReference: $this->artifactDisplayReference('Baseline snapshot', $snapshot),
            lifecycleState: $isHistorical ? 'superseded' : 'current',
            retentionState: 'retained',
        );
    }

    public function forEvidenceSnapshot(EvidenceSnapshot $snapshot): ArtifactTruthEnvelope
    {
        return $this->resolveEnvelope(
            record: $snapshot,
            variant: 'evidence_snapshot',
            resolver: fn (): ArtifactTruthEnvelope => $this->buildEvidenceSnapshotEnvelope($snapshot),
        );
    }

    public function forEvidenceSnapshotFresh(EvidenceSnapshot $snapshot): ArtifactTruthEnvelope
    {
        return $this->resolveEnvelope(
            record: $snapshot,
            variant: 'evidence_snapshot',
            resolver: fn (): ArtifactTruthEnvelope => $this->buildEvidenceSnapshotEnvelope($snapshot),
            fresh: true,
        );
    }

    private function buildEvidenceSnapshotEnvelope(EvidenceSnapshot $snapshot): ArtifactTruthEnvelope
    {
        $snapshot->loadMissing('tenant');

        $summary = is_array($snapshot->summary) ? $snapshot->summary : [];
        $missingDimensions = (int) ($summary['missing_dimensions'] ?? 0);
        $staleDimensions = (int) ($summary['stale_dimensions'] ?? 0);
        $status = (string) $snapshot->status;

        $artifactExistence = match ($status) {
            'queued', 'generating' => 'not_created',
            'expired', 'superseded' => 'historical_only',
            'failed' => 'created_but_not_usable',
            default => 'created',
        };

        $contentState = match (true) {
            $artifactExistence === 'not_created' => 'missing_input',
            $artifactExistence === 'historical_only' && $snapshot->completeness_state === 'missing' => 'empty',
            $status === 'failed' => 'missing_input',
            $snapshot->completeness_state === 'missing' => 'missing_input',
            $snapshot->completeness_state === 'partial' => 'partial',
            default => 'trusted',
        };

        if ((int) ($summary['dimension_count'] ?? 0) === 0 && $artifactExistence !== 'not_created') {
            $contentState = 'empty';
        }

        $freshnessState = match (true) {
            $artifactExistence === 'historical_only' => 'stale',
            $snapshot->completeness_state === 'stale' || $staleDimensions > 0 => 'stale',
            in_array($status, ['queued', 'generating'], true) => 'unknown',
            default => 'current',
        };

        $actionability = match (true) {
            $artifactExistence === 'historical_only' => 'none',
            in_array($status, ['queued', 'generating'], true) => 'optional',
            $contentState === 'trusted' && $freshnessState === 'current' => 'none',
            $freshnessState === 'stale' => 'optional',
            default => 'required',
        };

        $reasonCode = match (true) {
            $status === 'failed' => 'evidence_generation_failed',
            $missingDimensions > 0 => 'evidence_missing_dimensions',
            $staleDimensions > 0 => 'evidence_stale_dimensions',
            default => null,
        };
        $reason = $this->reasonPresenter->forArtifactTruth($reasonCode, 'artifact_truth');

        [$primaryDomain, $primaryState, $primaryExplanation] = match (true) {
            $artifactExistence === 'not_created' => [
                BadgeDomain::GovernanceArtifactExistence,
                'not_created',
                'The evidence generation request exists, but no tenant snapshot is available yet.',
            ],
            $artifactExistence === 'historical_only' => [
                BadgeDomain::GovernanceArtifactExistence,
                'historical_only',
                'This evidence snapshot remains available for history, but it is not the current working evidence artifact.',
            ],
            $contentState !== 'trusted' => [
                BadgeDomain::GovernanceArtifactContent,
                $contentState,
                $reason?->shortExplanation ?? $this->contentExplanation($contentState),
            ],
            $freshnessState === 'stale' => [
                BadgeDomain::GovernanceArtifactFreshness,
                'stale',
                $reason?->shortExplanation ?? 'The snapshot exists, but one or more evidence dimensions should be refreshed before relying on it.',
            ],
            default => [
                BadgeDomain::GovernanceArtifactContent,
                'trusted',
                'A current evidence snapshot is available for review work.',
            ],
        };

        $nextActionUrl = $snapshot->operation_run_id
            ? OperationRunLinks::tenantlessView((int) $snapshot->operation_run_id)
            : null;

        return $this->makeEnvelope(
            artifactFamily: 'evidence_snapshot',
            artifactKey: 'evidence_snapshot:'.$snapshot->getKey(),
            workspaceId: (int) $snapshot->workspace_id,
            tenantId: $snapshot->managed_environment_id !== null ? (int) $snapshot->managed_environment_id : null,
            executionOutcome: null,
            artifactExistence: $artifactExistence,
            contentState: $contentState,
            freshnessState: $freshnessState,
            publicationReadiness: null,
            supportState: 'normal',
            actionability: $actionability,
            primaryDomain: $primaryDomain,
            primaryState: $primaryState,
            primaryExplanation: $primaryExplanation,
            diagnosticLabel: $missingDimensions > 0 && $staleDimensions > 0
                ? sprintf('%d missing, %d stale dimensions', $missingDimensions, $staleDimensions)
                : null,
            reason: ArtifactTruthCause::fromReasonResolutionEnvelope($reason, ReasonPresenter::GOVERNANCE_ARTIFACT_TRUTH_ARTIFACT),
            nextActionLabel: $this->nextActionLabel(
                $actionability,
                $reason,
                match ($actionability) {
                    'required' => 'Refresh evidence before using this snapshot',
                    'optional' => in_array($status, ['queued', 'generating'], true)
                        ? 'Wait for evidence generation to finish'
                        : ($freshnessState === 'stale'
                            ? 'Refresh the stale evidence before relying on this snapshot'
                            : 'Review the evidence freshness before relying on this snapshot'),
                    default => null,
                },
            ),
            nextActionUrl: $nextActionUrl,
            relatedRunId: $snapshot->operation_run_id !== null ? (int) $snapshot->operation_run_id : null,
            relatedArtifactUrl: $snapshot->tenant !== null
                ? $this->panelSafeTenantArtifactUrl(fn (): string => EvidenceSnapshotResource::getUrl('view', ['record' => $snapshot], tenant: $snapshot->tenant))
                : null,
            includePublicationDimension: false,
            countDescriptors: [
                new CountDescriptor(
                    label: 'Evidence dimensions',
                    value: (int) ($summary['dimension_count'] ?? 0),
                    role: CountDescriptor::ROLE_EVALUATION_OUTPUT,
                ),
                new CountDescriptor(
                    label: 'Missing dimensions',
                    value: $missingDimensions,
                    role: CountDescriptor::ROLE_COVERAGE,
                    qualifier: $missingDimensions > 0 ? 'partial' : null,
                ),
                new CountDescriptor(
                    label: 'Stale dimensions',
                    value: $staleDimensions,
                    role: CountDescriptor::ROLE_RELIABILITY_SIGNAL,
                    qualifier: $staleDimensions > 0 ? 'refresh recommended' : null,
                ),
            ],
            displayReference: $this->artifactDisplayReference('Evidence snapshot', $snapshot),
            integrityAnchor: $snapshot->fingerprint,
            lifecycleState: $this->evidenceLifecycleState($snapshot, $artifactExistence),
            retentionState: $this->evidenceRetentionState($snapshot),
        );
    }

    public function forEnvironmentReview(EnvironmentReview $review): ArtifactTruthEnvelope
    {
        return $this->resolveEnvelope(
            record: $review,
            variant: 'environment_review',
            resolver: fn (): ArtifactTruthEnvelope => $this->buildEnvironmentReviewEnvelope($review),
        );
    }

    public function forEnvironmentReviewFresh(EnvironmentReview $review): ArtifactTruthEnvelope
    {
        return $this->resolveEnvelope(
            record: $review,
            variant: 'environment_review',
            resolver: fn (): ArtifactTruthEnvelope => $this->buildEnvironmentReviewEnvelope($review),
            fresh: true,
        );
    }

    private function buildEnvironmentReviewEnvelope(EnvironmentReview $review): ArtifactTruthEnvelope
    {
        $review->loadMissing(['tenant', 'currentExportReviewPack', 'evidenceSnapshot']);

        $summary = is_array($review->summary) ? $review->summary : [];
        $publishBlockers = $review->publishBlockers();
        $status = $review->statusEnum();
        $completeness = $review->completenessEnum()->value;
        $sectionCounts = is_array($summary['section_state_counts'] ?? null) ? $summary['section_state_counts'] : [];
        $staleSections = (int) ($sectionCounts['stale'] ?? 0);
        $sourceEvidence = $this->evidenceTrustBurden($review->evidenceSnapshot);

        $artifactExistence = match ($status) {
            EnvironmentReviewStatus::Archived, EnvironmentReviewStatus::Superseded => 'historical_only',
            EnvironmentReviewStatus::Failed => 'created_but_not_usable',
            default => 'created',
        };

        $contentState = match (true) {
            $completeness === EnvironmentReviewCompletenessState::Missing->value => 'missing_input',
            $completeness === EnvironmentReviewCompletenessState::Partial->value || $sourceEvidence['isPartial'] => 'partial',
            $sourceEvidence['isMissing'] => 'missing_input',
            $completeness === EnvironmentReviewCompletenessState::Complete->value => 'trusted',
            $completeness === EnvironmentReviewCompletenessState::Stale->value => 'trusted',
            default => 'partial',
        };

        $freshnessState = match (true) {
            $artifactExistence === 'historical_only' => 'stale',
            $completeness === EnvironmentReviewCompletenessState::Stale->value || $staleSections > 0 || $sourceEvidence['isStale'] => 'stale',
            default => 'current',
        };

        $publicationReadiness = match (true) {
            $artifactExistence === 'historical_only' => 'internal_only',
            $publishBlockers !== [] => 'blocked',
            $contentState === 'missing_input' => 'blocked',
            $freshnessState === 'stale' || $contentState === 'partial' => 'internal_only',
            $status === EnvironmentReviewStatus::Published => 'publishable',
            $status === EnvironmentReviewStatus::Ready => 'publishable',
            default => 'internal_only',
        };

        $actionability = match (true) {
            $artifactExistence === 'historical_only' => 'none',
            $publicationReadiness === 'publishable' && $freshnessState === 'current' => 'none',
            $publicationReadiness === 'blocked' => 'required',
            $publicationReadiness === 'internal_only' => 'optional',
            default => 'required',
        };

        $reasonCode = match (true) {
            $publishBlockers !== [] => 'review_publish_blocked',
            $status === EnvironmentReviewStatus::Failed => 'review_generation_failed',
            $contentState === 'missing_input' => 'review_missing_sections',
            $freshnessState === 'stale' => 'review_stale_sections',
            default => null,
        };
        $reason = $this->reasonPresenter->forArtifactTruth($reasonCode, 'artifact_truth');

        [$primaryDomain, $primaryState, $primaryExplanation] = match (true) {
            $artifactExistence === 'historical_only' => [
                BadgeDomain::GovernanceArtifactExistence,
                'historical_only',
                'This review remains available as historical evidence, but it is no longer the current review artifact.',
            ],
            $publicationReadiness === 'blocked' => [
                BadgeDomain::GovernanceArtifactPublicationReadiness,
                'blocked',
                $publishBlockers[0] ?? $reason?->shortExplanation ?? 'This review exists, but it is blocked from publication or export.',
            ],
            $publicationReadiness === 'internal_only' => [
                BadgeDomain::GovernanceArtifactPublicationReadiness,
                'internal_only',
                match (true) {
                    $freshnessState === 'stale' => 'This review is useful internally, but stale evidence should be refreshed before stakeholder publication.',
                    $contentState === 'partial' => 'This review is useful internally, but the evidence basis is partial and should be completed before stakeholder publication.',
                    default => 'This review exists and is useful internally, but it is not yet ready for stakeholder publication.',
                },
            ],
            $freshnessState === 'stale' => [
                BadgeDomain::GovernanceArtifactFreshness,
                'stale',
                $reason?->shortExplanation ?? 'The review exists, but one or more required sections should be refreshed before publication.',
            ],
            default => [
                BadgeDomain::GovernanceArtifactPublicationReadiness,
                'publishable',
                'This review is ready for publication and executive-pack export.',
            ],
        };

        $nextActionUrl = $review->operation_run_id
            ? OperationRunLinks::tenantlessView((int) $review->operation_run_id)
            : null;

        $displayReference = $this->artifactDisplayReference('Review', $review);
        $integrityAnchor = is_string($review->fingerprint) && trim($review->fingerprint) !== ''
            ? $review->fingerprint
            : null;
        $lifecycleState = $artifactExistence === 'historical_only' ? 'historical' : 'current';
        $retentionState = 'retained';

        if ($review->currentExportReviewPack instanceof ReviewPack) {
            $displayReference = $this->artifactDisplayReference('Current export', $review->currentExportReviewPack);
            $integrityAnchor = $review->currentExportReviewPack->sha256 ?: $review->currentExportReviewPack->fingerprint;
            $lifecycleState = $this->reviewPackLifecycleState($review->currentExportReviewPack);
            $retentionState = $this->reviewPackRetentionState($review->currentExportReviewPack);
        }

        if ($publishBlockers !== [] && $review->tenant !== null) {
            $nextActionUrl = $this->panelSafeTenantArtifactUrl(
                fn (): string => EnvironmentReviewResource::environmentScopedUrl('view', ['record' => $review], $review->tenant)
            );
        } elseif (($freshnessState === 'stale' || $contentState === 'partial') && $review->tenant !== null && $review->evidenceSnapshot !== null) {
            $nextActionUrl = $this->panelSafeTenantArtifactUrl(
                fn (): string => EvidenceSnapshotResource::getUrl('view', ['record' => $review->evidenceSnapshot], tenant: $review->tenant)
            );
        }

        return $this->makeEnvelope(
            artifactFamily: 'environment_review',
            artifactKey: 'environment_review:'.$review->getKey(),
            workspaceId: (int) $review->workspace_id,
            tenantId: $review->managed_environment_id !== null ? (int) $review->managed_environment_id : null,
            executionOutcome: null,
            artifactExistence: $artifactExistence,
            contentState: $contentState,
            freshnessState: $freshnessState,
            publicationReadiness: $publicationReadiness,
            supportState: 'normal',
            actionability: $actionability,
            primaryDomain: $primaryDomain,
            primaryState: $primaryState,
            primaryExplanation: $primaryExplanation,
            diagnosticLabel: $contentState !== 'trusted'
                ? BadgeCatalog::spec(BadgeDomain::GovernanceArtifactContent, $contentState)->label
                : null,
            reason: ArtifactTruthCause::fromReasonResolutionEnvelope($reason, ReasonPresenter::GOVERNANCE_ARTIFACT_TRUTH_ARTIFACT),
            nextActionLabel: $this->nextActionLabel(
                $actionability,
                $reason,
                match (true) {
                    $publicationReadiness === 'blocked' => 'Resolve the review blockers before publication',
                    $freshnessState === 'stale' => 'Refresh the evidence basis before publishing this review',
                    $contentState === 'partial' => 'Complete the evidence basis before publishing this review',
                    $actionability === 'optional' => 'Complete the remaining review work before publication',
                    default => null,
                },
            ),
            nextActionUrl: $nextActionUrl,
            relatedRunId: $review->operation_run_id !== null ? (int) $review->operation_run_id : null,
            relatedArtifactUrl: $review->tenant !== null
                ? $this->panelSafeTenantArtifactUrl(
                    fn (): string => EnvironmentReviewResource::environmentScopedUrl('view', ['record' => $review], $review->tenant)
                )
                : null,
            includePublicationDimension: true,
            countDescriptors: [
                new CountDescriptor(
                    label: 'Findings',
                    value: (int) ($summary['finding_count'] ?? 0),
                    role: CountDescriptor::ROLE_EVALUATION_OUTPUT,
                ),
                new CountDescriptor(
                    label: 'Sections',
                    value: (int) ($summary['section_count'] ?? 0),
                    role: CountDescriptor::ROLE_EXECUTION,
                ),
                new CountDescriptor(
                    label: 'Publish blockers',
                    value: count($publishBlockers),
                    role: CountDescriptor::ROLE_RELIABILITY_SIGNAL,
                    qualifier: $publishBlockers !== [] ? 'resolve before publish' : null,
                ),
            ],
            displayReference: $displayReference,
            integrityAnchor: $integrityAnchor,
            lifecycleState: $lifecycleState,
            retentionState: $retentionState,
        );
    }

    public function forReviewPack(ReviewPack $pack): ArtifactTruthEnvelope
    {
        return $this->resolveEnvelope(
            record: $pack,
            variant: 'review_pack',
            resolver: fn (): ArtifactTruthEnvelope => $this->buildReviewPackEnvelope($pack),
        );
    }

    public function forReviewPackFresh(ReviewPack $pack): ArtifactTruthEnvelope
    {
        return $this->resolveEnvelope(
            record: $pack,
            variant: 'review_pack',
            resolver: fn (): ArtifactTruthEnvelope => $this->buildReviewPackEnvelope($pack),
            fresh: true,
        );
    }

    private function buildReviewPackEnvelope(ReviewPack $pack): ArtifactTruthEnvelope
    {
        $pack->loadMissing(['tenant', 'environmentReview', 'evidenceSnapshot']);

        $summary = is_array($pack->summary) ? $pack->summary : [];
        $status = (string) $pack->status;
        $evidenceResolution = is_array($summary['evidence_resolution'] ?? null) ? $summary['evidence_resolution'] : [];
        $sourceReview = $pack->environmentReview;
        $sourceReviewTruth = $sourceReview instanceof EnvironmentReview
            ? $this->forEnvironmentReviewFresh($sourceReview)
            : null;
        $sourceBlockers = $sourceReview instanceof EnvironmentReview ? $sourceReview->publishBlockers() : [];
        $sourceReviewStatus = $sourceReview instanceof EnvironmentReview ? $sourceReview->statusEnum() : null;
        $sourceEvidence = $this->evidenceTrustBurden($pack->evidenceSnapshot);

        $artifactExistence = match ($status) {
            ReviewPackStatus::Queued->value, ReviewPackStatus::Generating->value => 'not_created',
            ReviewPackStatus::Expired->value => 'historical_only',
            ReviewPackStatus::Failed->value => 'created_but_not_usable',
            default => 'created',
        };

        $contentState = match (true) {
            $artifactExistence === 'not_created' => 'missing_input',
            $status === ReviewPackStatus::Failed->value => 'missing_input',
            ($evidenceResolution['outcome'] ?? null) !== 'resolved' => 'missing_input',
            $sourceReviewTruth?->contentState === 'missing_input' => 'missing_input',
            $sourceReviewTruth?->contentState === 'partial' || $sourceEvidence['isPartial'] => 'partial',
            default => 'trusted',
        };

        $freshnessState = match (true) {
            $artifactExistence === 'historical_only' => 'stale',
            $sourceReviewTruth?->freshnessState === 'stale' || $sourceEvidence['isStale'] => 'stale',
            default => 'current',
        };

        $publicationReadiness = match (true) {
            $artifactExistence === 'historical_only' => 'internal_only',
            $artifactExistence === 'not_created' => 'blocked',
            $status === ReviewPackStatus::Failed->value => 'blocked',
            $sourceReviewTruth?->publicationReadiness === 'blocked' => 'blocked',
            $sourceReviewTruth?->publicationReadiness === 'internal_only' => 'internal_only',
            $freshnessState === 'stale' || $contentState === 'partial' => 'internal_only',
            $sourceReviewStatus === EnvironmentReviewStatus::Draft || $sourceReviewStatus === EnvironmentReviewStatus::Failed => 'internal_only',
            default => $status === ReviewPackStatus::Ready->value ? 'publishable' : 'blocked',
        };

        $actionability = match (true) {
            $artifactExistence === 'historical_only' => 'none',
            $publicationReadiness === 'publishable' && $freshnessState === 'current' => 'none',
            $publicationReadiness === 'internal_only' => 'optional',
            default => 'required',
        };

        $reasonCode = match (true) {
            $status === ReviewPackStatus::Failed->value => 'review_pack_generation_failed',
            ($evidenceResolution['outcome'] ?? null) !== 'resolved' => 'review_pack_missing_snapshot',
            $sourceReviewTruth?->publicationReadiness === 'blocked' || $sourceReviewTruth?->publicationReadiness === 'internal_only' => 'review_pack_source_not_publishable',
            $artifactExistence === 'historical_only' => 'review_pack_expired',
            default => null,
        };
        $reason = $this->reasonPresenter->forArtifactTruth($reasonCode, 'artifact_truth');

        [$primaryDomain, $primaryState, $primaryExplanation] = match (true) {
            $artifactExistence === 'historical_only' => [
                BadgeDomain::GovernanceArtifactExistence,
                'historical_only',
                'This pack remains available as a historical export, but it is no longer the current stakeholder artifact.',
            ],
            $publicationReadiness === 'blocked' => [
                BadgeDomain::GovernanceArtifactPublicationReadiness,
                'blocked',
                $sourceBlockers[0] ?? $reason?->shortExplanation ?? 'A pack file is not yet available for trustworthy stakeholder delivery.',
            ],
            $publicationReadiness === 'internal_only' => [
                BadgeDomain::GovernanceArtifactPublicationReadiness,
                'internal_only',
                match (true) {
                    $freshnessState === 'stale' => 'This pack is downloadable, but the source review relies on stale evidence and should stay internal until refreshed.',
                    $contentState === 'partial' => 'This pack is downloadable, but the source review relies on partial evidence and should stay internal until the evidence basis is completed.',
                    default => 'This pack can be reviewed internally, but the source review is not currently publishable.',
                },
            ],
            default => [
                BadgeDomain::GovernanceArtifactPublicationReadiness,
                'publishable',
                'This executive pack is ready for stakeholder delivery.',
            ],
        };

        $nextActionUrl = null;

        if ($sourceReview instanceof EnvironmentReview && $pack->tenant !== null) {
            $nextActionUrl = $this->panelSafeTenantArtifactUrl(
                fn (): string => EnvironmentReviewResource::environmentScopedUrl('view', ['record' => $sourceReview], $pack->tenant)
            );
        } elseif (($freshnessState === 'stale' || $contentState === 'partial') && $pack->tenant !== null && $pack->evidenceSnapshot !== null) {
            $nextActionUrl = $this->panelSafeTenantArtifactUrl(
                fn (): string => EvidenceSnapshotResource::getUrl('view', ['record' => $pack->evidenceSnapshot], tenant: $pack->tenant)
            );
        } elseif ($pack->operation_run_id !== null) {
            $nextActionUrl = OperationRunLinks::tenantlessView((int) $pack->operation_run_id);
        }

        return $this->makeEnvelope(
            artifactFamily: 'review_pack',
            artifactKey: 'review_pack:'.$pack->getKey(),
            workspaceId: (int) $pack->workspace_id,
            tenantId: $pack->managed_environment_id !== null ? (int) $pack->managed_environment_id : null,
            executionOutcome: null,
            artifactExistence: $artifactExistence,
            contentState: $contentState,
            freshnessState: $freshnessState,
            publicationReadiness: $publicationReadiness,
            supportState: 'normal',
            actionability: $actionability,
            primaryDomain: $primaryDomain,
            primaryState: $primaryState,
            primaryExplanation: $primaryExplanation,
            diagnosticLabel: $contentState !== 'trusted'
                ? BadgeCatalog::spec(BadgeDomain::GovernanceArtifactContent, $contentState)->label
                : null,
            reason: ArtifactTruthCause::fromReasonResolutionEnvelope($reason, ReasonPresenter::GOVERNANCE_ARTIFACT_TRUTH_ARTIFACT),
            nextActionLabel: $this->nextActionLabel(
                $actionability,
                $reason,
                match (true) {
                    $publicationReadiness === 'blocked' => 'Open the source review before sharing this pack',
                    $freshnessState === 'stale' => 'Refresh the source review before sharing this pack',
                    $contentState === 'partial' => 'Complete the source review before sharing this pack',
                    $actionability === 'optional' => 'Review the source review before sharing this pack',
                    default => null,
                },
            ),
            nextActionUrl: $nextActionUrl,
            relatedRunId: $pack->operation_run_id !== null ? (int) $pack->operation_run_id : null,
            relatedArtifactUrl: $pack->tenant !== null
                ? $this->panelSafeTenantArtifactUrl(
                    fn (): string => ReviewPackResource::getUrl('view', ['record' => $pack], tenant: $pack->tenant)
                )
                : null,
            includePublicationDimension: true,
            countDescriptors: [
                new CountDescriptor(
                    label: 'Findings',
                    value: (int) ($summary['finding_count'] ?? 0),
                    role: CountDescriptor::ROLE_EVALUATION_OUTPUT,
                ),
                new CountDescriptor(
                    label: 'Reports',
                    value: (int) ($summary['report_count'] ?? 0),
                    role: CountDescriptor::ROLE_EXECUTION,
                ),
                new CountDescriptor(
                    label: 'Operations',
                    value: (int) ($summary['operation_count'] ?? 0),
                    role: CountDescriptor::ROLE_EXECUTION,
                    visibilityTier: CountDescriptor::VISIBILITY_DIAGNOSTIC,
                ),
            ],
            displayReference: $this->artifactDisplayReference('Review pack', $pack),
            integrityAnchor: $pack->sha256 ?: $pack->fingerprint,
            lifecycleState: $this->reviewPackLifecycleState($pack),
            retentionState: $this->reviewPackRetentionState($pack),
        );
    }

    public function forStoredReport(StoredReport $report): ArtifactTruthEnvelope
    {
        return $this->resolveEnvelope(
            record: $report,
            variant: 'stored_report',
            resolver: fn (): ArtifactTruthEnvelope => $this->buildStoredReportEnvelope($report),
        );
    }

    public function forStoredReportFresh(StoredReport $report): ArtifactTruthEnvelope
    {
        return $this->resolveEnvelope(
            record: $report,
            variant: 'stored_report',
            resolver: fn (): ArtifactTruthEnvelope => $this->buildStoredReportEnvelope($report),
            fresh: true,
        );
    }

    private function buildStoredReportEnvelope(StoredReport $report): ArtifactTruthEnvelope
    {
        $report->loadMissing('tenant');

        $latestReport = StoredReport::query()
            ->where('managed_environment_id', (int) $report->managed_environment_id)
            ->where('report_type', $report->report_type)
            ->orderByDesc('created_at')
            ->orderByDesc('id')
            ->first();

        $isCurrent = $latestReport?->is($report) ?? true;
        $artifactExistence = $isCurrent ? 'created' : 'historical_only';
        $freshnessState = $isCurrent ? 'current' : 'stale';
        $lifecycleState = $isCurrent ? 'current' : 'historical';

        return $this->makeEnvelope(
            artifactFamily: 'stored_report',
            artifactKey: 'stored_report:'.$report->getKey(),
            workspaceId: (int) $report->workspace_id,
            tenantId: (int) $report->managed_environment_id,
            executionOutcome: null,
            artifactExistence: $artifactExistence,
            contentState: 'trusted',
            freshnessState: $freshnessState,
            publicationReadiness: null,
            supportState: 'normal',
            actionability: 'none',
            primaryDomain: BadgeDomain::GovernanceArtifactLifecycle,
            primaryState: $lifecycleState,
            primaryExplanation: $isCurrent
                ? 'This report is the latest retained record for its report type.'
                : 'This report remains readable as retained history, but a newer report is the current record.',
            diagnosticLabel: null,
            reason: null,
            nextActionLabel: 'No action needed',
            nextActionUrl: null,
            relatedRunId: null,
            relatedArtifactUrl: null,
            includePublicationDimension: false,
            displayReference: sprintf('Stored report #%d (%s)', $report->getKey(), $this->storedReportReferenceLabel($report)),
            integrityAnchor: $report->fingerprint,
            lifecycleState: $lifecycleState,
            retentionState: 'retained',
        );
    }

    public function forFindingExceptionDecision(FindingExceptionDecision $decision): ArtifactTruthEnvelope
    {
        return $this->resolveEnvelope(
            record: $decision,
            variant: 'finding_exception_decision',
            resolver: fn (): ArtifactTruthEnvelope => $this->buildFindingExceptionDecisionEnvelope($decision),
        );
    }

    public function forFindingExceptionDecisionFresh(FindingExceptionDecision $decision): ArtifactTruthEnvelope
    {
        return $this->resolveEnvelope(
            record: $decision,
            variant: 'finding_exception_decision',
            resolver: fn (): ArtifactTruthEnvelope => $this->buildFindingExceptionDecisionEnvelope($decision),
            fresh: true,
        );
    }

    private function buildFindingExceptionDecisionEnvelope(FindingExceptionDecision $decision): ArtifactTruthEnvelope
    {
        $decision->loadMissing('exception.currentDecision');

        $isCurrent = $decision->exception?->current_decision_id === (int) $decision->getKey();
        $artifactExistence = $isCurrent ? 'created' : 'historical_only';
        $lifecycleState = $isCurrent ? 'current' : 'superseded';

        return $this->makeEnvelope(
            artifactFamily: 'finding_exception_decision',
            artifactKey: 'finding_exception_decision:'.$decision->getKey(),
            workspaceId: (int) $decision->workspace_id,
            tenantId: $decision->managed_environment_id !== null ? (int) $decision->managed_environment_id : null,
            executionOutcome: null,
            artifactExistence: $artifactExistence,
            contentState: 'trusted',
            freshnessState: $isCurrent ? 'current' : 'stale',
            publicationReadiness: null,
            supportState: 'normal',
            actionability: 'none',
            primaryDomain: BadgeDomain::GovernanceArtifactLifecycle,
            primaryState: $lifecycleState,
            primaryExplanation: $isCurrent
                ? 'This append-only decision row is the current accepted-risk decision.'
                : 'This append-only decision row remains in history, but a newer decision is now current.',
            diagnosticLabel: null,
            reason: null,
            nextActionLabel: 'No action needed',
            nextActionUrl: null,
            relatedRunId: null,
            relatedArtifactUrl: null,
            includePublicationDimension: false,
            displayReference: $this->artifactDisplayReference('Accepted-risk decision', $decision),
            integrityAnchor: $decision->decided_at?->toIso8601String(),
            lifecycleState: $lifecycleState,
            retentionState: 'retained',
        );
    }

    /**
     * @return array{isMissing: bool, isPartial: bool, isStale: bool}
     */
    private function evidenceTrustBurden(?EvidenceSnapshot $snapshot): array
    {
        if (! $snapshot instanceof EvidenceSnapshot) {
            return [
                'isMissing' => false,
                'isPartial' => false,
                'isStale' => false,
            ];
        }

        $summary = is_array($snapshot->summary) ? $snapshot->summary : [];
        $completeness = $snapshot->completenessState();
        $staleDimensions = (int) ($summary['stale_dimensions'] ?? 0);

        return [
            'isMissing' => $completeness === EvidenceCompletenessState::Missing,
            'isPartial' => $completeness === EvidenceCompletenessState::Partial,
            'isStale' => $completeness === EvidenceCompletenessState::Stale || $staleDimensions > 0,
        ];
    }

    public function forOperationRun(OperationRun $run): ArtifactTruthEnvelope
    {
        return $this->resolveEnvelope(
            record: $run,
            variant: 'operation_run',
            resolver: fn (): ArtifactTruthEnvelope => $this->buildOperationRunEnvelope($run),
        );
    }

    public function forOperationRunFresh(OperationRun $run): ArtifactTruthEnvelope
    {
        return $this->resolveEnvelope(
            record: $run,
            variant: 'operation_run',
            resolver: fn (): ArtifactTruthEnvelope => $this->buildOperationRunEnvelope($run),
            fresh: true,
        );
    }

    private function buildOperationRunEnvelope(OperationRun $run): ArtifactTruthEnvelope
    {
        $artifact = $this->resolveArtifactForRun($run);
        $reason = $this->reasonPresenter->forOperationRun($run, 'run_detail');

        if ($artifact !== null) {
            $artifactEnvelope = $this->for($artifact);

            if ($artifactEnvelope instanceof ArtifactTruthEnvelope) {
                $diagnosticParts = array_values(array_filter([
                    BadgeCatalog::spec(BadgeDomain::OperationRunOutcome, $run->outcome)->label !== 'Unknown'
                        ? BadgeCatalog::spec(BadgeDomain::OperationRunOutcome, $run->outcome)->label
                        : null,
                    $artifactEnvelope->diagnosticLabel,
                ]));

                return $this->makeEnvelope(
                    artifactFamily: 'artifact_run',
                    artifactKey: 'artifact_run:'.$run->getKey(),
                    workspaceId: (int) $run->workspace_id,
                    tenantId: $run->managed_environment_id !== null ? (int) $run->managed_environment_id : null,
                    executionOutcome: $run->outcome !== null ? (string) $run->outcome : null,
                    artifactExistence: $artifactEnvelope->artifactExistence,
                    contentState: $artifactEnvelope->contentState,
                    freshnessState: $artifactEnvelope->freshnessState,
                    publicationReadiness: $artifactEnvelope->publicationReadiness,
                    supportState: $artifactEnvelope->supportState,
                    actionability: $artifactEnvelope->actionability,
                    primaryDomain: $artifactEnvelope->primaryDimension()?->badgeDomain ?? BadgeDomain::GovernanceArtifactExistence,
                    primaryState: $artifactEnvelope->primaryDimension()?->badgeState ?? $artifactEnvelope->artifactExistence,
                    primaryExplanation: $artifactEnvelope->primaryExplanation ?? $reason?->shortExplanation ?? 'The operation finished, but the related artifact needs review.',
                    diagnosticLabel: $diagnosticParts === [] ? null : implode(' · ', $diagnosticParts),
                    reason: $artifactEnvelope->reason,
                    nextActionLabel: $artifactEnvelope->nextActionLabel,
                    nextActionUrl: $artifactEnvelope->relatedArtifactUrl ?? $artifactEnvelope->nextActionUrl,
                    relatedRunId: (int) $run->getKey(),
                    relatedArtifactUrl: $artifactEnvelope->relatedArtifactUrl,
                    includePublicationDimension: $artifactEnvelope->publicationReadiness !== null,
                    countDescriptors: array_merge(
                        $artifactEnvelope->operatorExplanation?->countDescriptors ?? [],
                        $this->runCountDescriptors($run),
                    ),
                    displayReference: $artifactEnvelope->displayReference,
                    integrityAnchor: $artifactEnvelope->integrityAnchor,
                    lifecycleState: $artifactEnvelope->lifecycleState,
                    retentionState: $artifactEnvelope->retentionState,
                );
            }
        }

        $artifactExistence = match ((string) $run->status) {
            OperationRunStatus::Queued->value, OperationRunStatus::Running->value => 'not_created',
            default => 'not_created',
        };
        $contentState = in_array((string) $run->outcome, [OperationRunOutcome::Blocked->value, OperationRunOutcome::Failed->value], true)
            ? 'missing_input'
            : 'empty';
        $actionability = in_array((string) $run->outcome, [OperationRunOutcome::Blocked->value, OperationRunOutcome::Failed->value], true)
            ? 'required'
            : 'optional';
        $primaryState = in_array((string) $run->outcome, [OperationRunOutcome::Blocked->value, OperationRunOutcome::Failed->value], true)
            ? 'created_but_not_usable'
            : 'not_created';

        return $this->makeEnvelope(
            artifactFamily: 'artifact_run',
            artifactKey: 'artifact_run:'.$run->getKey(),
            workspaceId: (int) $run->workspace_id,
            tenantId: $run->managed_environment_id !== null ? (int) $run->managed_environment_id : null,
            executionOutcome: $run->outcome !== null ? (string) $run->outcome : null,
            artifactExistence: $artifactExistence,
            contentState: $contentState,
            freshnessState: 'unknown',
            publicationReadiness: OperationCatalog::governanceArtifactFamily((string) $run->type) === 'review_pack'
                || OperationCatalog::governanceArtifactFamily((string) $run->type) === 'environment_review'
                ? 'blocked'
                : null,
            supportState: 'normal',
            actionability: $actionability,
            primaryDomain: BadgeDomain::GovernanceArtifactExistence,
            primaryState: $primaryState,
            primaryExplanation: $reason?->shortExplanation ?? match ((string) $run->status) {
                OperationRunStatus::Queued->value, OperationRunStatus::Running->value => 'The artifact-producing operation is still in progress, so no artifact is available yet.',
                default => 'The operation finished without a usable artifact result.',
            },
            diagnosticLabel: BadgeCatalog::spec(BadgeDomain::OperationRunOutcome, $run->outcome)->label,
            reason: ArtifactTruthCause::fromReasonResolutionEnvelope($reason, ReasonPresenter::GOVERNANCE_ARTIFACT_TRUTH_ARTIFACT),
            nextActionLabel: $reason?->firstNextStep()?->label
                ?? ($actionability === 'required'
                    ? 'Inspect the blocked run details before retrying'
                    : 'Wait for the artifact-producing operation to finish'),
            nextActionUrl: null,
            relatedRunId: (int) $run->getKey(),
            relatedArtifactUrl: null,
            includePublicationDimension: OperationCatalog::governanceArtifactFamily((string) $run->type) === 'review_pack'
                || OperationCatalog::governanceArtifactFamily((string) $run->type) === 'environment_review',
            countDescriptors: $this->runCountDescriptors($run),
        );
    }

    private function resolveArtifactForRun(OperationRun $run): BaselineSnapshot|EvidenceSnapshot|EnvironmentReview|ReviewPack|null
    {
        return match (OperationCatalog::governanceArtifactFamily((string) $run->type)) {
            'baseline_snapshot' => $run->relatedArtifactId() !== null
                ? BaselineSnapshot::query()->with('baselineProfile')->find($run->relatedArtifactId())
                : null,
            'evidence_snapshot' => EvidenceSnapshot::query()->with('tenant')->where('operation_run_id', (int) $run->getKey())->latest('id')->first(),
            'environment_review' => EnvironmentReview::query()->with(['tenant', 'currentExportReviewPack'])->where('operation_run_id', (int) $run->getKey())->latest('id')->first(),
            'review_pack' => ReviewPack::query()->with(['tenant', 'environmentReview'])->where('operation_run_id', (int) $run->getKey())->latest('id')->first(),
            default => null,
        };
    }

    private function resolveEnvelope(
        Model $record,
        string $variant,
        callable $resolver,
        bool $fresh = false,
    ): ArtifactTruthEnvelope {
        $key = DerivedStateKey::fromModel(DerivedStateFamily::ArtifactTruth, $record, $variant);

        /** @var ArtifactTruthEnvelope $envelope */
        $envelope = $fresh
            ? $this->derivedStateStore->resolveFresh(
                $key,
                $resolver,
                DerivedStateFamily::ArtifactTruth->defaultFreshnessPolicy(),
                DerivedStateFamily::ArtifactTruth->allowsNegativeResultCache(),
            )
            : $this->derivedStateStore->resolve(
                $key,
                $resolver,
                DerivedStateFamily::ArtifactTruth->defaultFreshnessPolicy(),
                DerivedStateFamily::ArtifactTruth->allowsNegativeResultCache(),
            );

        return $envelope;
    }

    private function contentExplanation(string $contentState): string
    {
        return match ($contentState) {
            'partial' => 'The artifact exists, but the captured content is incomplete for the primary operator task.',
            'missing_input' => 'The artifact is blocked by missing upstream inputs or failed capture prerequisites.',
            'metadata_only' => 'Only metadata was captured for this artifact. Use diagnostics for context, not as the primary truth signal.',
            'reference_only' => 'Only reference-level placeholders were captured for this artifact.',
            'empty' => 'The artifact row exists, but it does not contain usable captured content.',
            'unsupported' => 'Structured support is limited for this artifact family, so the current rendering should be treated as diagnostic only.',
            default => 'The artifact content is available for the intended workflow.',
        };
    }

    /**
     * @param  array<string, int>  $reasons
     */
    private function firstReasonCode(array $reasons): ?string
    {
        foreach ($reasons as $reason => $count) {
            if ((int) $count > 0 && is_string($reason) && trim($reason) !== '') {
                return trim($reason);
            }
        }

        return null;
    }

    private function nextActionLabel(
        string $actionability,
        ?ReasonResolutionEnvelope $reason,
        ?string $fallback = null,
    ): ?string {
        if ($actionability === 'none') {
            return 'No action needed';
        }

        if (is_string($fallback) && trim($fallback) !== '') {
            return $fallback;
        }

        if ($reason instanceof ReasonResolutionEnvelope && $reason->firstNextStep() !== null) {
            return $reason->firstNextStep()?->label;
        }

        return null;
    }

    private function makeEnvelope(
        string $artifactFamily,
        string $artifactKey,
        int $workspaceId,
        ?int $tenantId,
        ?string $executionOutcome,
        string $artifactExistence,
        string $contentState,
        string $freshnessState,
        ?string $publicationReadiness,
        string $supportState,
        string $actionability,
        BadgeDomain $primaryDomain,
        string $primaryState,
        ?string $primaryExplanation,
        ?string $diagnosticLabel,
        ?ArtifactTruthCause $reason,
        ?string $nextActionLabel,
        ?string $nextActionUrl,
        ?int $relatedRunId,
        ?string $relatedArtifactUrl,
        bool $includePublicationDimension,
        array $countDescriptors = [],
        ?string $displayReference = null,
        ?string $integrityAnchor = null,
        ?string $lifecycleState = null,
        ?string $retentionState = null,
    ): ArtifactTruthEnvelope {
        $primarySpec = BadgeCatalog::spec($primaryDomain, $primaryState);
        $dimensions = [
            $this->dimension(BadgeDomain::GovernanceArtifactExistence, $artifactExistence, 'artifact_existence', $primaryDomain === BadgeDomain::GovernanceArtifactExistence ? 'primary' : 'diagnostic'),
            $this->dimension(BadgeDomain::GovernanceArtifactContent, $contentState, 'content_fidelity', $primaryDomain === BadgeDomain::GovernanceArtifactContent ? 'primary' : 'diagnostic'),
            $this->dimension(BadgeDomain::GovernanceArtifactFreshness, $freshnessState, 'data_freshness', $primaryDomain === BadgeDomain::GovernanceArtifactFreshness ? 'primary' : 'diagnostic'),
        ];

        if ($lifecycleState !== null) {
            $dimensions[] = $this->dimension(
                BadgeDomain::GovernanceArtifactLifecycle,
                $lifecycleState,
                'artifact_lifecycle',
                $primaryDomain === BadgeDomain::GovernanceArtifactLifecycle ? 'primary' : 'diagnostic',
            );
        }

        if ($retentionState !== null) {
            $dimensions[] = $this->dimension(
                BadgeDomain::GovernanceArtifactRetention,
                $retentionState,
                'retention_state',
                $primaryDomain === BadgeDomain::GovernanceArtifactRetention ? 'primary' : 'diagnostic',
            );
        }

        $dimensions[] = $this->dimension(BadgeDomain::GovernanceArtifactActionability, $actionability, 'operator_actionability', 'diagnostic');

        if ($includePublicationDimension && $publicationReadiness !== null) {
            $dimensions[] = $this->dimension(
                BadgeDomain::GovernanceArtifactPublicationReadiness,
                $publicationReadiness,
                'publication_readiness',
                $primaryDomain === BadgeDomain::GovernanceArtifactPublicationReadiness ? 'primary' : 'diagnostic',
            );
        }

        if ($executionOutcome !== null && trim($executionOutcome) !== '') {
            $dimensions[] = $this->dimension(BadgeDomain::OperationRunOutcome, $executionOutcome, 'execution_outcome', 'diagnostic');
        }

        if ($supportState === 'limited_support') {
            $dimensions[] = new ArtifactTruthDimension(
                axis: 'support_maturity',
                state: 'limited_support',
                label: 'Support limited',
                classification: 'diagnostic',
                badgeDomain: BadgeDomain::GovernanceArtifactContent,
                badgeState: 'unsupported',
            );
        }

        $draftEnvelope = new ArtifactTruthEnvelope(
            artifactFamily: $artifactFamily,
            artifactKey: $artifactKey,
            workspaceId: $workspaceId,
            tenantId: $tenantId,
            executionOutcome: $executionOutcome,
            artifactExistence: $artifactExistence,
            contentState: $contentState,
            freshnessState: $freshnessState,
            publicationReadiness: $publicationReadiness,
            supportState: $supportState,
            actionability: $actionability,
            primaryLabel: $primarySpec->label,
            primaryExplanation: $primaryExplanation,
            diagnosticLabel: $diagnosticLabel,
            nextActionLabel: $nextActionLabel,
            nextActionUrl: $nextActionUrl,
            relatedRunId: $relatedRunId,
            relatedArtifactUrl: $relatedArtifactUrl,
            dimensions: array_values($dimensions),
            reason: $reason,
            displayReference: $displayReference,
            integrityAnchor: $integrityAnchor,
            lifecycleState: $lifecycleState,
            retentionState: $retentionState,
        );

        return new ArtifactTruthEnvelope(
            artifactFamily: $draftEnvelope->artifactFamily,
            artifactKey: $draftEnvelope->artifactKey,
            workspaceId: $draftEnvelope->workspaceId,
            tenantId: $draftEnvelope->tenantId,
            executionOutcome: $draftEnvelope->executionOutcome,
            artifactExistence: $draftEnvelope->artifactExistence,
            contentState: $draftEnvelope->contentState,
            freshnessState: $draftEnvelope->freshnessState,
            publicationReadiness: $draftEnvelope->publicationReadiness,
            supportState: $draftEnvelope->supportState,
            actionability: $draftEnvelope->actionability,
            primaryLabel: $draftEnvelope->primaryLabel,
            primaryExplanation: $draftEnvelope->primaryExplanation,
            diagnosticLabel: $draftEnvelope->diagnosticLabel,
            nextActionLabel: $draftEnvelope->nextActionLabel,
            nextActionUrl: $draftEnvelope->nextActionUrl,
            relatedRunId: $draftEnvelope->relatedRunId,
            relatedArtifactUrl: $draftEnvelope->relatedArtifactUrl,
            dimensions: $draftEnvelope->dimensions,
            reason: $draftEnvelope->reason,
            operatorExplanation: $this->operatorExplanationBuilder->fromArtifactTruthEnvelope($draftEnvelope, $countDescriptors),
            displayReference: $draftEnvelope->displayReference,
            integrityAnchor: $draftEnvelope->integrityAnchor,
            lifecycleState: $draftEnvelope->lifecycleState,
            retentionState: $draftEnvelope->retentionState,
        );
    }

    private function dimension(
        BadgeDomain $domain,
        string $state,
        string $axis,
        string $classification,
    ): ArtifactTruthDimension {
        return new ArtifactTruthDimension(
            axis: $axis,
            state: $state,
            label: BadgeCatalog::spec($domain, $state)->label,
            classification: $classification,
            badgeDomain: $domain,
            badgeState: $state,
        );
    }

    private function panelSafeTenantArtifactUrl(callable $resolver): ?string
    {
        return Filament::getCurrentPanel()?->getId() === 'system'
            ? null
            : $resolver();
    }

    private function resolveCompressionContext(
        ArtifactTruthEnvelope $truth,
        SurfaceCompressionContext|string|null $context,
    ): SurfaceCompressionContext {
        if ($context instanceof SurfaceCompressionContext) {
            return $context;
        }

        if (is_string($context) && trim($context) !== '') {
            return SurfaceCompressionContext::fromSurfaceFamily($context);
        }

        return SurfaceCompressionContext::defaultForArtifactFamily($truth->artifactFamily);
    }

    private function buildCompressedOutcome(
        ArtifactTruthEnvelope $truth,
        SurfaceCompressionContext $context,
    ): CompressedGovernanceOutcome {
        $summaryInputs = $this->operatorExplanationBuilder->compressionSummaryInputs($truth);

        return new CompressedGovernanceOutcome(
            surfaceFamily: $context->surfaceFamily,
            decisionDirection: $this->decisionDirection($truth, $context),
            primaryLabel: $truth->primaryLabel,
            primaryReason: $summaryInputs['primaryReason'],
            nextActionText: $summaryInputs['nextActionText'],
            primaryBadge: $truth->primaryBadgeSpec(),
            secondaryFacts: $this->secondaryFacts($truth, $context),
            diagnosticsAvailable: $summaryInputs['diagnosticsAvailable'],
            diagnosticsSummary: $summaryInputs['diagnosticsSummary'],
        );
    }

    private function decisionDirection(
        ArtifactTruthEnvelope $truth,
        SurfaceCompressionContext $context,
    ): string {
        if ($truth->artifactExistence === 'historical_only') {
            return 'historical_only';
        }

        if ($context->prioritizesPublication() && $truth->publicationReadiness !== null) {
            return match ($truth->publicationReadiness) {
                'publishable' => 'publishable',
                'blocked' => 'blocked',
                'internal_only' => 'internal_only',
                default => 'follow_up_needed',
            };
        }

        if (in_array($truth->artifactExistence, ['not_created', 'created_but_not_usable'], true)) {
            return 'blocked';
        }

        if ($truth->contentState === 'missing_input') {
            return 'blocked';
        }

        if ($truth->freshnessState === 'stale') {
            return 'stale';
        }

        if (in_array($truth->contentState, ['partial', 'empty', 'reference_only', 'unsupported'], true)) {
            return 'follow_up_needed';
        }

        return 'usable';
    }

    /**
     * @return list<array{label: string, value: string, badge: ?\App\Support\Badges\BadgeSpec}>
     */
    private function secondaryFacts(
        ArtifactTruthEnvelope $truth,
        SurfaceCompressionContext $context,
    ): array {
        $facts = [];

        foreach ($context->secondaryDimensions as $axis) {
            $fact = match ($axis) {
                'artifact_existence' => $this->secondaryDimensionFact(
                    label: 'Record state',
                    domain: BadgeDomain::GovernanceArtifactExistence,
                    state: $truth->artifactExistence,
                    skipWhenState: 'created',
                ),
                'content_fidelity' => $this->secondaryDimensionFact(
                    label: 'Coverage',
                    domain: BadgeDomain::GovernanceArtifactContent,
                    state: $truth->contentState,
                    skipWhenState: 'trusted',
                ),
                'data_freshness' => $this->secondaryDimensionFact(
                    label: 'Freshness',
                    domain: BadgeDomain::GovernanceArtifactFreshness,
                    state: $truth->freshnessState,
                    skipWhenState: 'current',
                ),
                'artifact_lifecycle' => $truth->lifecycleState !== null
                    ? $this->secondaryDimensionFact(
                        label: 'Lifecycle',
                        domain: BadgeDomain::GovernanceArtifactLifecycle,
                        state: $truth->lifecycleState,
                        skipWhenState: 'current',
                    )
                    : null,
                'publication_readiness' => $truth->publicationReadiness !== null
                    ? $this->secondaryDimensionFact(
                        label: 'Publication',
                        domain: BadgeDomain::GovernanceArtifactPublicationReadiness,
                        state: $truth->publicationReadiness,
                        skipWhenState: 'publishable',
                    )
                    : null,
                'retention_state' => $truth->retentionState !== null
                    ? $this->secondaryDimensionFact(
                        label: 'Retention',
                        domain: BadgeDomain::GovernanceArtifactRetention,
                        state: $truth->retentionState,
                        skipWhenState: 'retained',
                    )
                    : null,
                'operator_actionability' => $truth->actionability !== 'none'
                    ? $this->secondaryDimensionFact(
                        label: 'Actionability',
                        domain: BadgeDomain::GovernanceArtifactActionability,
                        state: $truth->actionability,
                    )
                    : null,
                default => null,
            };

            if ($fact === null) {
                continue;
            }

            $facts[] = $fact;
        }

        if ($truth->supportState === 'limited_support') {
            $facts[] = [
                'label' => 'Support',
                'value' => 'Limited support',
                'badge' => BadgeCatalog::spec(BadgeDomain::GovernanceArtifactContent, 'unsupported'),
            ];
        }

        return array_slice($facts, 0, 3);
    }

    private function artifactDisplayReference(string $label, Model $record): string
    {
        return sprintf('%s #%d', $label, $record->getKey());
    }

    private function evidenceLifecycleState(EvidenceSnapshot $snapshot, string $artifactExistence): string
    {
        return match (true) {
            (string) $snapshot->status === 'superseded' => 'superseded',
            $artifactExistence === 'historical_only' => 'historical',
            default => 'current',
        };
    }

    private function evidenceRetentionState(EvidenceSnapshot $snapshot): string
    {
        return match (true) {
            (string) $snapshot->status === 'expired' => 'expired_direct_access',
            $snapshot->expires_at !== null && $snapshot->expires_at->isPast() => 'expired_direct_access',
            default => 'retained',
        };
    }

    private function reviewPackLifecycleState(ReviewPack $pack): string
    {
        if ((string) $pack->status === ReviewPackStatus::Expired->value) {
            return 'historical';
        }

        if ($pack->environmentReview instanceof EnvironmentReview && $pack->environmentReview->current_export_review_pack_id !== null) {
            return $pack->environmentReview->current_export_review_pack_id === (int) $pack->getKey()
                ? 'current'
                : 'superseded';
        }

        return 'current';
    }

    private function reviewPackRetentionState(ReviewPack $pack): string
    {
        return match (true) {
            (string) $pack->status === ReviewPackStatus::Expired->value => 'expired_direct_access',
            $pack->expires_at !== null && $pack->expires_at->isPast() => 'expired_direct_access',
            default => 'retained',
        };
    }

    private function storedReportReferenceLabel(StoredReport $report): string
    {
        return Str::of(str_replace('.', ' ', $report->report_type))
            ->replace('_', ' ')
            ->headline()
            ->append(' report')
            ->toString();
    }

    /**
     * @return array{label: string, value: string, badge: ?\App\Support\Badges\BadgeSpec}|null
     */
    private function secondaryDimensionFact(
        string $label,
        BadgeDomain $domain,
        string $state,
        ?string $skipWhenState = null,
    ): ?array {
        if ($skipWhenState !== null && $state === $skipWhenState) {
            return null;
        }

        $spec = BadgeCatalog::spec($domain, $state);

        if ($spec->label === 'Unknown') {
            return null;
        }

        return [
            'label' => $label,
            'value' => $spec->label,
            'badge' => $spec,
        ];
    }

    /**
     * @return array<int, CountDescriptor>
     */
    private function runCountDescriptors(OperationRun $run): array
    {
        $descriptors = [];

        foreach (SummaryCountsNormalizer::normalize(is_array($run->summary_counts) ? $run->summary_counts : []) as $key => $value) {
            $role = match (true) {
                in_array($key, ['total', 'processed'], true) => CountDescriptor::ROLE_EXECUTION,
                str_contains($key, 'failed') || str_contains($key, 'warning') || str_contains($key, 'blocked') => CountDescriptor::ROLE_RELIABILITY_SIGNAL,
                default => CountDescriptor::ROLE_EVALUATION_OUTPUT,
            };

            $descriptors[] = new CountDescriptor(
                label: SummaryCountsNormalizer::label($key),
                value: (int) $value,
                role: $role,
                visibilityTier: in_array($key, ['total', 'processed'], true)
                    ? CountDescriptor::VISIBILITY_PRIMARY
                    : CountDescriptor::VISIBILITY_DIAGNOSTIC,
            );
        }

        return $descriptors;
    }
}
