<?php

declare(strict_types=1);

namespace App\Filament\Pages\Operations;

use App\Filament\Resources\OperationRunResource;
use App\Models\ManagedEnvironment;
use App\Models\OperationRun;
use App\Models\SupportRequest;
use App\Models\User;
use App\Services\Audit\WorkspaceAuditLogger;
use App\Services\Auth\CapabilityResolver;
use App\Services\Auth\WorkspaceCapabilityResolver;
use App\Services\Baselines\BaselineEvidenceCaptureResumeService;
use App\Services\Tenants\TenantOperabilityService;
use App\Support\Auth\Capabilities;
use App\Support\ManagedEnvironmentLinks;
use App\Support\Navigation\CanonicalNavigationContext;
use App\Support\Navigation\RelatedNavigationResolver;
use App\Support\OperateHub\OperateHubShell;
use App\Support\OperationCatalog;
use App\Support\OperationRunLinks;
use App\Support\OperationRunType;
use App\Support\OpsUx\OperationUxPresenter;
use App\Support\OpsUx\OpsUxBrowserEvents;
use App\Support\OpsUx\RunDetailPolling;
use App\Support\ProductTelemetry\ProductTelemetryRecorder;
use App\Support\ProductTelemetry\ProductUsageEventCatalog;
use App\Support\Rbac\UiEnforcement;
use App\Support\ReasonTranslation\ReasonPresenter;
use App\Support\RedactionIntegrity;
use App\Support\RestoreSafety\RestoreSafetyCopy;
use App\Support\SupportDiagnostics\SupportDiagnosticBundleBuilder;
use App\Support\SupportRequests\ExternalSupportDeskHandoffService;
use App\Support\SupportRequests\SupportRequestSubmissionService;
use App\Support\Tenants\ReferencedTenantLifecyclePresentation;
use App\Support\Tenants\TenantInteractionLane;
use App\Support\Tenants\TenantOperabilityQuestion;
use App\Support\Ui\ActionSurface\ActionSurfaceDeclaration;
use App\Support\Ui\ActionSurface\ActionSurfaceDefaults;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
use App\Support\Ui\OperatorExplanation\OperatorExplanationPattern;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\EmbeddedSchema;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Contracts\View\View;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Str;

class TenantlessOperationRunViewer extends Page
{
    use AuthorizesRequests;

    protected static bool $shouldRegisterNavigation = false;

    protected static bool $isDiscovered = false;

    protected static ?string $title = 'Operation';

    protected string $view = 'filament.pages.operations.tenantless-operation-run-viewer';

    public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
    {
        return ActionSurfaceDeclaration::forPage(ActionSurfaceProfile::RunLog)
            ->withDefaults(new ActionSurfaceDefaults(
                moreGroupLabel: 'More',
                exportIsDefaultBulkActionForReadOnly: false,
            ))
            ->exempt(ActionSurfaceSlot::ListHeader, 'Canonical tenantless run viewing is a detail-only page and does not render list header actions.')
            ->exempt(ActionSurfaceSlot::InspectAffordance, 'The tenantless run viewer is itself the canonical detail destination for a selected operation run.')
            ->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'Detail viewing does not expose bulk actions.')
            ->exempt(ActionSurfaceSlot::ListEmptyState, 'The page renders a selected run detail instead of a list empty state.')
            ->satisfy(ActionSurfaceSlot::DetailHeader, 'Header keeps scope context, back navigation, refresh, related links, and resumable capture actions when applicable.');
    }

    public OperationRun $run;

    public function getTitle(): string|Htmlable
    {
        return OperationRunLinks::identifier($this->run);
    }

    /**
     * @var array<string, mixed>|null
     */
    public ?array $navigationContextPayload = null;

    /**
     * @var list<string>
     */
    public array $supportDiagnosticsAuditKeys = [];

    /**
     * @return array<Action|ActionGroup>
     */
    protected function getHeaderActions(): array
    {
        $operateHubShell = app(OperateHubShell::class);
        $navigationContext = $this->navigationContext();
        $activeEnvironment = $operateHubShell->activeEntitledTenant(request());
        $runTenantId = isset($this->run) ? (int) ($this->run->managed_environment_id ?? 0) : 0;

        $actions = [
            Action::make('operate_hub_scope_run_detail')
                ->label($operateHubShell->scopeLabel(request()))
                ->color('gray')
                ->disabled(),
        ];

        if ($navigationContext?->backLinkLabel !== null && $navigationContext->backLinkUrl !== null) {
            $actions[] = Action::make('operate_hub_back_to_origin_run_detail')
                ->label($navigationContext->backLinkLabel)
                ->color('gray')
                ->url($navigationContext->backLinkUrl);
        } elseif ($activeEnvironment instanceof ManagedEnvironment && (int) $activeEnvironment->getKey() === $runTenantId) {
            $actions[] = Action::make('operate_hub_back_to_tenant_run_detail')
                ->label('← Back to '.$activeEnvironment->name)
                ->color('gray')
                ->url(ManagedEnvironmentLinks::viewUrl($activeEnvironment));
        } else {
            $actions[] = Action::make('operate_hub_back_to_operations')
                ->label('Back to Operations')
                ->color('gray')
                ->url(fn (): string => OperationRunLinks::index());
        }

        if ($activeEnvironment instanceof ManagedEnvironment) {
            $actions[] = Action::make('operate_hub_show_all_operations')
                ->label('Show all operations')
                ->color('gray')
                ->url(fn (): string => OperationRunLinks::index());
        }

        $actions[] = Action::make('refresh')
            ->label('Refresh')
            ->icon('heroicon-o-arrow-path')
            ->color('primary')
            ->url(fn (): string => isset($this->run)
                ? OperationRunLinks::tenantlessView($this->run, $navigationContext)
                : OperationRunLinks::index());

        if (! isset($this->run)) {
            return $actions;
        }

        $related = $this->relatedLinks();

        $relatedActions = [];

        foreach ($related as $label => $url) {
            $relatedActions[] = Action::make(Str::slug((string) $label, '_'))
                ->label((string) $label)
                ->url((string) $url)
                ->openUrlInNewTab();
        }

        if ($relatedActions !== []) {
            $actions[] = ActionGroup::make($relatedActions)
                ->label('Open')
                ->icon('heroicon-o-arrow-top-right-on-square')
                ->color('gray');
        }

        $actions[] = ActionGroup::make([
            $this->openSupportDiagnosticsAction(),
            $this->requestSupportAction(),
        ])
            ->label('More')
            ->icon('heroicon-o-ellipsis-horizontal')
            ->color('gray');

        $actions[] = $this->resumeCaptureAction();

        return $actions;
    }

    /**
     * @return array{
     *     scope_label: string,
     *     scope_body: string,
     *     navigation_label: string,
     *     navigation_body: string,
     *     utility_body: string,
     *     related_body: string,
     *     follow_up_body: string,
     *     follow_up_label: ?string
     * }
     */
    public function monitoringDetailSummary(): array
    {
        $operateHubShell = app(OperateHubShell::class);
        $navigationContext = $this->navigationContext();
        $activeEnvironment = $operateHubShell->activeEntitledTenant(request());
        $runTenantId = isset($this->run) ? (int) ($this->run->managed_environment_id ?? 0) : 0;

        $navigationLabel = 'Back to Operations';
        $navigationBody = 'Return to the operations landing when this review is complete.';

        if ($navigationContext?->backLinkLabel !== null && $navigationContext->backLinkUrl !== null) {
            $navigationLabel = $navigationContext->backLinkLabel;
            $navigationBody = 'Return to the originating surface while keeping refresh and follow-up work separate from navigation.';
        } elseif ($activeEnvironment instanceof ManagedEnvironment && (int) $activeEnvironment->getKey() === $runTenantId) {
            $navigationLabel = 'Back to '.$activeEnvironment->name;
            $navigationBody = 'Return to the active tenant dashboard, then widen back to the workspace view only when you need broader monitoring context.';
        }

        $relatedLabels = array_values(array_keys($this->relatedLinks()));
        $relatedBody = $relatedLabels === []
            ? 'Open keeps secondary drilldowns grouped under one control when downstream context exists.'
            : 'Open keeps secondary drilldowns grouped under one control: '.implode(', ', $relatedLabels).'.';

        $followUpLabel = $this->canResumeCapture() ? 'Resume capture' : null;

        return [
            'scope_label' => $operateHubShell->scopeLabel(request()),
            'scope_body' => 'The current workspace or tenant scope remains visible without behaving like a primary task action.',
            'navigation_label' => $navigationLabel,
            'navigation_body' => $navigationBody,
            'utility_body' => 'Refresh keeps the current run state accurate without changing scope.',
            'related_body' => $relatedBody,
            'follow_up_body' => $followUpLabel !== null
                ? 'Resume capture only appears when this run supports additional evidence collection.'
                : 'No run-specific follow-up is currently available.',
            'follow_up_label' => $followUpLabel,
        ];
    }

    private function openSupportDiagnosticsAction(): Action
    {
        $action = Action::make('openSupportDiagnostics')
            ->label('Open support diagnostics')
            ->icon('heroicon-o-lifebuoy')
            ->color('gray')
            ->record($this->run)
            ->modal()
            ->slideOver()
            ->stickyModalHeader()
            ->modalHeading('Support diagnostics')
            ->modalDescription('Redacted operation context from existing records.')
            ->modalSubmitAction(false)
            ->modalCancelAction(fn (Action $action): Action => $action->label('Close'))
            ->mountUsing(function (): void {
                $this->auditOperationSupportDiagnosticsOpen();
            })
            ->modalContent(fn (): View => view('filament.modals.support-diagnostic-bundle', [
                'bundle' => $this->operationRunSupportDiagnosticBundle(),
            ]));

        return UiEnforcement::forAction($action)
            ->requireCapability(Capabilities::SUPPORT_DIAGNOSTICS_VIEW)
            ->apply();
    }

    public function authorizeOperationRunSupportRequest(): void
    {
        $this->resolveRunTenantForCapability(Capabilities::SUPPORT_REQUESTS_CREATE);
    }

    private function requestSupportAction(): Action
    {
        $action = Action::make('requestSupport')
            ->label(__('localization.dashboard.request_support'))
            ->icon('heroicon-o-paper-airplane')
            ->record($this->run)
            ->slideOver()
            ->stickyModalHeader()
            ->modalHeading(__('localization.dashboard.support_request_heading'))
            ->modalDescription(__('localization.dashboard.support_request_run_description'))
            ->modalSubmitActionLabel(__('localization.dashboard.submit_request'))
            ->form([
                Placeholder::make('primary_context')
                    ->label(__('localization.dashboard.primary_context'))
                    ->content(fn (): string => OperationRunLinks::identifier($this->run))
                    ->columnSpanFull(),
                Placeholder::make('included_context')
                    ->label(__('localization.dashboard.included_context'))
                    ->content(fn (): string => $this->operationSupportRequestAttachmentSummary())
                    ->columnSpanFull(),
                Placeholder::make('latest_external_handoff')
                    ->label(__('localization.dashboard.latest_external_handoff'))
                    ->content(fn (): string => $this->operationLatestSupportRequestHandoffSummary())
                    ->columnSpanFull(),
                Select::make('external_handoff_mode')
                    ->label(__('localization.dashboard.external_handoff_mode'))
                    ->options(fn (): array => $this->supportHandoffModeOptions())
                    ->default(SupportRequest::EXTERNAL_HANDOFF_MODE_INTERNAL_ONLY)
                    ->helperText(fn (): string => $this->supportDeskTargetAvailable()
                        ? __('localization.dashboard.external_handoff_mode_helper_available')
                        : __('localization.dashboard.external_handoff_mode_helper_unavailable'))
                    ->required()
                    ->live()
                    ->native(false),
                Placeholder::make('handoff_mutation_scope')
                    ->label(__('localization.dashboard.handoff_mutation_scope'))
                    ->content(fn (Get $get): string => $this->externalHandoffMutationScope($get('external_handoff_mode')))
                    ->columnSpanFull(),
                TextInput::make('external_ticket_reference')
                    ->label(__('localization.dashboard.external_ticket_reference'))
                    ->helperText(__('localization.dashboard.external_ticket_reference_helper'))
                    ->required(fn (Get $get): bool => $get('external_handoff_mode') === SupportRequest::EXTERNAL_HANDOFF_MODE_LINK_EXISTING_TICKET)
                    ->visible(fn (Get $get): bool => $this->supportDeskTargetAvailable()
                        && $get('external_handoff_mode') === SupportRequest::EXTERNAL_HANDOFF_MODE_LINK_EXISTING_TICKET),
                TextInput::make('external_ticket_url')
                    ->label(__('localization.dashboard.external_ticket_url'))
                    ->helperText(__('localization.dashboard.external_ticket_url_helper'))
                    ->url()
                    ->visible(fn (Get $get): bool => $this->supportDeskTargetAvailable()
                        && $get('external_handoff_mode') === SupportRequest::EXTERNAL_HANDOFF_MODE_LINK_EXISTING_TICKET)
                    ->columnSpanFull(),
                Select::make('severity')
                    ->label(__('localization.dashboard.severity'))
                    ->options(SupportRequest::severityOptions())
                    ->default(SupportRequest::SEVERITY_NORMAL)
                    ->required()
                    ->native(false),
                TextInput::make('summary')
                    ->label(__('localization.dashboard.summary'))
                    ->required()
                    ->columnSpanFull(),
                Textarea::make('reproduction_notes')
                    ->label(__('localization.dashboard.reproduction_notes'))
                    ->rows(4)
                    ->columnSpanFull(),
                TextInput::make('contact_name')
                    ->label(__('localization.dashboard.contact_name'))
                    ->default(fn (): ?string => $this->resolveViewerActor()->name),
                TextInput::make('contact_email')
                    ->label(__('localization.dashboard.contact_email'))
                    ->email()
                    ->default(fn (): ?string => $this->resolveViewerActor()->email),
            ])
            ->action(function (array $data): void {
                $actor = $this->resolveViewerActor();

                $supportRequest = app(SupportRequestSubmissionService::class)->submitForOperationRun($this->run, $actor, $data);

                Notification::make()
                    ->title(__('localization.dashboard.support_request_submitted'))
                    ->body($this->supportRequestNotificationBody($supportRequest))
                    ->when(
                        $supportRequest->hasExternalHandoffFailure(),
                        fn (Notification $notification): Notification => $notification->warning(),
                        fn (Notification $notification): Notification => $notification->success(),
                    )
                    ->when(
                        $supportRequest->external_ticket_url !== null,
                        fn (Notification $notification): Notification => $notification->actions([
                            Action::make('openExternalTicket')
                                ->label(__('localization.dashboard.open_external_ticket'))
                                ->url((string) $supportRequest->external_ticket_url, shouldOpenInNewTab: true),
                        ]),
                    )
                    ->send();
            });

        return UiEnforcement::forAction($action)
            ->requireCapability(Capabilities::SUPPORT_REQUESTS_CREATE)
            ->apply();
    }

    /**
     * @return array<string, mixed>
     */
    public function operationRunSupportDiagnosticBundle(): array
    {
        $user = $this->resolveViewerActor();
        $tenant = $this->resolveRunTenantForCapability(Capabilities::SUPPORT_DIAGNOSTICS_VIEW);

        return app(SupportDiagnosticBundleBuilder::class)->forOperationRun($this->run, $user);
    }

    private function auditOperationSupportDiagnosticsOpen(): void
    {
        $user = $this->resolveViewerActor();
        $tenant = $this->resolveRunTenantForCapability(Capabilities::SUPPORT_DIAGNOSTICS_VIEW);

        $this->recordSupportDiagnosticsOpened(
            tenant: $tenant,
            bundle: $this->operationRunSupportDiagnosticBundle(),
            user: $user,
        );
    }

    private function supportDiagnosticsTenant(): ?ManagedEnvironment
    {
        if (! isset($this->run)) {
            return null;
        }

        $tenant = $this->run->tenant;

        if ($tenant instanceof ManagedEnvironment) {
            return $tenant;
        }

        return $this->run->loadMissing('tenant')->tenant;
    }

    private function resolveViewerActor(): User
    {
        $user = auth()->user();

        if (! $user instanceof User) {
            abort(403);
        }

        return $user;
    }

    private function resolveRunTenantForCapability(string $capability): ManagedEnvironment
    {
        $tenant = $this->supportDiagnosticsTenant();
        $user = $this->resolveViewerActor();

        if (! $tenant instanceof ManagedEnvironment) {
            abort(404);
        }

        $resolver = app(CapabilityResolver::class);

        if (! $resolver->isMember($user, $tenant)) {
            abort(404);
        }

        if (! $resolver->can($user, $tenant, $capability)) {
            abort(403);
        }

        return $tenant;
    }

    private function operationSupportRequestAttachmentSummary(): string
    {
        $tenant = $this->supportDiagnosticsTenant();
        $user = auth()->user();

        if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
            return 'Only canonical redacted run context will be attached.';
        }

        $resolver = app(CapabilityResolver::class);

        if (! $resolver->isMember($user, $tenant)) {
            return 'Only canonical redacted run context will be attached.';
        }

        return $resolver->can($user, $tenant, Capabilities::SUPPORT_DIAGNOSTICS_VIEW)
            ? 'A redacted diagnostic snapshot and the canonical run context will be attached.'
            : 'Only the canonical redacted run context will be attached because you cannot view support diagnostics.';
    }

    private function operationLatestSupportRequestHandoffSummary(): string
    {
        $user = $this->resolveViewerActor();

        $summary = app(SupportRequestSubmissionService::class)->latestOperationRunHandoffSummary($this->run, $user);

        return $this->formatLatestHandoffSummary($summary);
    }

    /**
     * @return array<string, string>
     */
    private function supportHandoffModeOptions(): array
    {
        if (! $this->supportDeskTargetAvailable()) {
            return [
                SupportRequest::EXTERNAL_HANDOFF_MODE_INTERNAL_ONLY => __('localization.dashboard.handoff_mode_internal_only'),
            ];
        }

        return [
            SupportRequest::EXTERNAL_HANDOFF_MODE_INTERNAL_ONLY => __('localization.dashboard.handoff_mode_internal_only'),
            SupportRequest::EXTERNAL_HANDOFF_MODE_CREATE_EXTERNAL_TICKET => __('localization.dashboard.handoff_mode_create_external_ticket'),
            SupportRequest::EXTERNAL_HANDOFF_MODE_LINK_EXISTING_TICKET => __('localization.dashboard.handoff_mode_link_existing_ticket'),
        ];
    }

    private function supportDeskTargetAvailable(): bool
    {
        return app(ExternalSupportDeskHandoffService::class)->targetIsConfigured();
    }

    private function externalHandoffMutationScope(mixed $mode): string
    {
        return match ($mode) {
            SupportRequest::EXTERNAL_HANDOFF_MODE_CREATE_EXTERNAL_TICKET => __('localization.dashboard.mutation_scope_external_create'),
            SupportRequest::EXTERNAL_HANDOFF_MODE_LINK_EXISTING_TICKET => __('localization.dashboard.mutation_scope_external_link'),
            default => __('localization.dashboard.mutation_scope_internal_only'),
        };
    }

    /**
     * @param  array<string, mixed>|null  $summary
     */
    private function formatLatestHandoffSummary(?array $summary): string
    {
        if ($summary === null) {
            return __('localization.dashboard.latest_external_handoff_none');
        }

        $internalReference = (string) $summary['internal_reference'];

        if (($summary['has_failure'] ?? false) === true) {
            return __('localization.dashboard.latest_external_handoff_failed', [
                'reference' => $internalReference,
                'failure' => (string) $summary['external_handoff_failure_summary'],
            ]);
        }

        if (($summary['has_external_link'] ?? false) === true) {
            return __('localization.dashboard.latest_external_handoff_linked', [
                'reference' => $internalReference,
                'external' => (string) $summary['external_ticket_reference'],
            ]);
        }

        return __('localization.dashboard.latest_external_handoff_internal_only', [
            'reference' => $internalReference,
        ]);
    }

    private function supportRequestNotificationBody(SupportRequest $supportRequest): string
    {
        return match ($supportRequest->externalHandoffOutcome()) {
            SupportRequest::HANDOFF_OUTCOME_EXTERNAL_TICKET_CREATED => __('localization.dashboard.support_request_submitted_created', [
                'reference' => $supportRequest->internal_reference,
                'external' => $supportRequest->external_ticket_reference,
            ]),
            SupportRequest::HANDOFF_OUTCOME_EXTERNAL_TICKET_LINKED => __('localization.dashboard.support_request_submitted_linked', [
                'reference' => $supportRequest->internal_reference,
                'external' => $supportRequest->external_ticket_reference,
            ]),
            SupportRequest::HANDOFF_OUTCOME_EXTERNAL_HANDOFF_FAILED => __('localization.dashboard.support_request_submitted_failed', [
                'reference' => $supportRequest->internal_reference,
                'failure' => $supportRequest->external_handoff_failure_summary,
            ]),
            default => __('localization.dashboard.support_request_submitted_internal_only', [
                'reference' => $supportRequest->internal_reference,
            ]),
        };
    }

    /**
     * @param  array<string, mixed>  $bundle
     */
    private function recordSupportDiagnosticsOpened(ManagedEnvironment $tenant, array $bundle, User $user): void
    {
        if (! isset($this->run)) {
            return;
        }

        $auditKey = 'operation:'.$this->run->getKey();

        if (in_array($auditKey, $this->supportDiagnosticsAuditKeys, true)) {
            return;
        }

        app(WorkspaceAuditLogger::class)->logSupportDiagnosticsOpened(
            tenant: $tenant,
            contextType: 'operation_run',
            bundle: $bundle,
            actor: $user,
            operationRun: $this->run,
        );

        app(ProductTelemetryRecorder::class)->record(
            eventName: ProductUsageEventCatalog::SUPPORT_DIAGNOSTICS_OPENED,
            workspaceId: (int) $tenant->workspace_id,
            tenantId: (int) $tenant->getKey(),
            userId: (int) $user->getKey(),
            subjectType: 'operation_run',
            subjectId: (int) $this->run->getKey(),
            metadata: [
                'source_surface' => 'operation_run_viewer',
                'operation_type' => (string) $this->run->type,
            ],
        );

        $this->supportDiagnosticsAuditKeys[] = $auditKey;
    }

    public function mount(OperationRun $run): void
    {
        $user = auth()->user();

        if (! $user instanceof User) {
            abort(403);
        }

        $this->authorize('view', $run);

        $this->run = $run->loadMissing(['workspace', 'tenant', 'user']);
        $this->navigationContextPayload = is_array(request()->query('nav')) ? request()->query('nav') : null;
    }

    public function infolist(Schema $schema): Schema
    {
        return OperationRunResource::infolist($schema);
    }

    public function defaultInfolist(Schema $schema): Schema
    {
        return $schema
            ->record($this->run)
            ->columns(2);
    }

    public function redactionIntegrityNote(): ?string
    {
        return isset($this->run) ? RedactionIntegrity::noteForRun($this->run) : null;
    }

    /**
     * @return array{tone: string, title: string, body: string}|null
     */
    public function blockedExecutionBanner(): ?array
    {
        if (! isset($this->run) || (string) $this->run->outcome !== 'blocked') {
            return null;
        }

        $reasonEnvelope = app(ReasonPresenter::class)->forOperationRun($this->run, 'detail');
        $body = 'This run was blocked before the artifact-producing work could finish. Review the summary below for the dominant blocker and next step.';

        if ($reasonEnvelope !== null) {
            $body = trim(sprintf(
                '%s %s %s',
                $body,
                rtrim($reasonEnvelope->operatorLabel, '.'),
                $reasonEnvelope->shortExplanation,
            ));
        }

        return [
            'tone' => 'amber',
            'title' => 'Blocked by prerequisite',
            'body' => $body,
        ];
    }

    /**
     * @return array{tone: string, title: string, body: string}|null
     */
    public function lifecycleBanner(): ?array
    {
        if (! isset($this->run)) {
            return null;
        }

        $attention = $this->lifecycleAttentionSummary();

        if ($attention === null) {
            return null;
        }

        $detail = $this->surfaceFailureDetail() ?? 'Lifecycle truth needs operator review.';

        return match ($this->run->freshnessState()->value) {
            'likely_stale' => [
                'tone' => 'amber',
                'title' => 'Likely stale operation',
                'body' => $detail,
            ],
            'reconciled_failed' => [
                'tone' => 'rose',
                'title' => 'Automatically reconciled',
                'body' => $detail,
            ],
            default => null,
        };
    }

    /**
     * @return array{tone: string, title: string, body: string, url: ?string, link_label: ?string}|null
     */
    public function restoreContinuationBanner(): ?array
    {
        if (! isset($this->run)) {
            return null;
        }

        $continuation = OperationRunResource::restoreContinuation($this->run);

        if (! is_array($continuation)) {
            return null;
        }

        $tone = ($continuation['follow_up_required'] ?? false) ? 'amber' : 'sky';
        $body = $continuation['summary'] ?? 'Restore continuation detail is unavailable.';
        $boundary = $continuation['recovery_claim_boundary'] ?? null;

        if (is_string($boundary) && $boundary !== '') {
            $body .= ' '.RestoreSafetyCopy::recoveryBoundary($boundary);
        }

        if (! ($continuation['link_available'] ?? false)) {
            $body .= ' Restore detail is not available from this session.';
        }

        return [
            'tone' => $tone,
            'title' => 'Restore continuation',
            'body' => $body,
            'url' => is_string($continuation['link_url'] ?? null) ? $continuation['link_url'] : null,
            'link_label' => ($continuation['link_available'] ?? false) ? 'Open restore run' : null,
        ];
    }

    /**
     * @return array{tone: string, title: string, body: string}|null
     */
    public function canonicalContextBanner(): ?array
    {
        if (! isset($this->run)) {
            return null;
        }

        $activeEnvironment = app(OperateHubShell::class)->activeEntitledTenant(request());
        $runTenant = $this->run->tenant;

        if (! $runTenant instanceof ManagedEnvironment) {
            return [
                'tone' => 'slate',
                'title' => 'Workspace-level operation',
                'body' => $activeEnvironment instanceof ManagedEnvironment
                    ? 'This canonical workspace view is not tied to the current environment context ('.$activeEnvironment->name.').'
                    : 'This canonical workspace view is not tied to any environment.',
            ];
        }

        $messages = ['Operation environment: '.$runTenant->name.'.'];
        $tone = 'sky';
        $title = null;

        if ($activeEnvironment instanceof ManagedEnvironment && ! $activeEnvironment->is($runTenant)) {
            $title = 'Current environment context differs from this operation';
            array_unshift($messages, 'Current environment context: '.$activeEnvironment->name.'.');
            $messages[] = 'This canonical workspace view remains valid without switching environment context.';
        }

        $referencedTenant = ReferencedTenantLifecyclePresentation::forOperationRun($runTenant);

        if ($selectorAvailabilityMessage = $referencedTenant->selectorAvailabilityMessage()) {
            $title ??= 'Operation environment is not available in the current environment selector';
            $tone = 'amber';
            $messages[] = $selectorAvailabilityMessage;

            if ($referencedTenant->contextNote !== null) {
                $messages[] = $referencedTenant->contextNote;
            }
        } elseif (! $activeEnvironment instanceof ManagedEnvironment) {
            $title ??= 'Canonical workspace view';
            $messages[] = 'No environment context is currently selected.';
        }

        if ($title === null) {
            return null;
        }

        return [
            'tone' => $tone,
            'title' => $title,
            'body' => implode(' ', $messages),
        ];
    }

    public function pollInterval(): ?string
    {
        if (! isset($this->run)) {
            return null;
        }

        if (filled($this->mountedActions ?? null)) {
            return null;
        }

        return RunDetailPolling::interval($this->run);
    }

    public function content(Schema $schema): Schema
    {
        return $schema->schema([
            EmbeddedSchema::make('infolist'),
        ]);
    }

    private function resumeCaptureAction(): Action
    {
        return Action::make('resumeCapture')
            ->label('Resume capture')
            ->icon('heroicon-o-forward')
            ->color('primary')
            ->requiresConfirmation()
            ->modalHeading('Resume capture')
            ->modalDescription('This will start a follow-up operation to capture remaining baseline evidence for this scope.')
            ->visible(fn (): bool => $this->canResumeCapture())
            ->action(function (): void {
                $user = auth()->user();

                if (! $user instanceof User) {
                    abort(403);
                }

                if (! isset($this->run)) {
                    Notification::make()
                        ->title('Operation not loaded')
                        ->danger()
                        ->send();

                    return;
                }

                $service = app(BaselineEvidenceCaptureResumeService::class);
                $result = $service->resume($this->run, $user);

                if (! ($result['ok'] ?? false)) {
                    $reason = is_string($result['reason_code'] ?? null) ? (string) $result['reason_code'] : 'unknown';

                    Notification::make()
                        ->title('Cannot resume capture')
                        ->body('Reason: '.str_replace('.', ' ', $reason))
                        ->danger()
                        ->send();

                    return;
                }

                $run = $result['run'] ?? null;

                if (! $run instanceof OperationRun) {
                    Notification::make()
                        ->title('Cannot resume capture')
                        ->body('Reason: missing operation')
                        ->danger()
                        ->send();

                    return;
                }

                $viewAction = Action::make('view_run')
                    ->label(OperationRunLinks::openLabel())
                    ->url(OperationRunLinks::tenantlessView($run));

                if (! $run->wasRecentlyCreated && in_array((string) $run->status, ['queued', 'running'], true)) {
                    OpsUxBrowserEvents::dispatchRunEnqueued($this);

                    OperationUxPresenter::alreadyQueuedToast((string) $run->type)
                        ->actions([$viewAction])
                        ->send();

                    return;
                }

                OpsUxBrowserEvents::dispatchRunEnqueued($this);

                OperationUxPresenter::queuedToast((string) $run->type)
                    ->actions([$viewAction])
                    ->send();
            });
    }

    private function navigationContext(): ?CanonicalNavigationContext
    {
        if (! is_array($this->navigationContextPayload)) {
            return CanonicalNavigationContext::fromRequest(request());
        }

        $request = request()->duplicate(query: ['nav' => $this->navigationContextPayload]);

        return CanonicalNavigationContext::fromRequest($request);
    }

    private function canResumeCapture(): bool
    {
        if (! isset($this->run)) {
            return false;
        }

        if ((string) $this->run->status !== 'completed') {
            return false;
        }

        $canonicalType = OperationCatalog::canonicalCode((string) $this->run->type);

        if (! in_array($canonicalType, [OperationRunType::BaselineCapture->value, OperationRunType::BaselineCompare->value], true)) {
            return false;
        }

        $context = is_array($this->run->context) ? $this->run->context : [];
        $tokenKey = $canonicalType === OperationRunType::BaselineCapture->value
            ? 'baseline_capture.resume_token'
            : 'baseline_compare.resume_token';
        $token = data_get($context, $tokenKey);

        if (! is_string($token) || trim($token) === '') {
            return false;
        }

        $user = auth()->user();

        if (! $user instanceof User) {
            return false;
        }

        $workspace = $this->run->workspace;

        if (! $workspace instanceof \App\Models\Workspace) {
            return false;
        }

        $resolver = app(WorkspaceCapabilityResolver::class);

        return $resolver->isMember($user, $workspace)
            && $resolver->can($user, $workspace, Capabilities::WORKSPACE_BASELINES_MANAGE);
    }

    private function relatedLinksTenant(): ?ManagedEnvironment
    {
        if (! isset($this->run)) {
            return null;
        }

        $user = auth()->user();
        $tenant = $this->run->tenant;

        if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
            return null;
        }

        if (! app(CapabilityResolver::class)->isMember($user, $tenant)) {
            return null;
        }

        return app(TenantOperabilityService::class)->outcomeFor(
            tenant: $tenant,
            question: TenantOperabilityQuestion::SelectorEligibility,
            actor: $user,
            workspaceId: (int) ($this->run->workspace_id ?? 0),
            lane: TenantInteractionLane::StandardActiveOperating,
        )->allowed ? $tenant : null;
    }

    private function governanceOperatorExplanation(): ?OperatorExplanationPattern
    {
        if (! isset($this->run) || ! $this->run->supportsOperatorExplanation()) {
            return null;
        }

        return OperationUxPresenter::governanceOperatorExplanation($this->run);
    }

    /**
     * @return array<string, string>
     */
    private function relatedLinks(bool $fresh = false): array
    {
        if (! isset($this->run)) {
            return [];
        }

        $resolver = app(RelatedNavigationResolver::class);

        $links = $fresh
            ? $resolver->operationLinksFresh($this->run, $this->relatedLinksTenant())
            : $resolver->operationLinks($this->run, $this->relatedLinksTenant());

        unset(
            $links[OperationRunLinks::collectionLabel()],
            $links[OperationRunLinks::openCollectionLabel()],
        );

        return $links;
    }

    private function lifecycleAttentionSummary(bool $fresh = false): ?string
    {
        if (! isset($this->run)) {
            return null;
        }

        return $fresh
            ? OperationUxPresenter::lifecycleAttentionSummaryFresh($this->run)
            : OperationUxPresenter::lifecycleAttentionSummary($this->run);
    }

    private function surfaceFailureDetail(bool $fresh = false): ?string
    {
        if (! isset($this->run)) {
            return null;
        }

        return $fresh
            ? OperationUxPresenter::surfaceFailureDetailFresh($this->run)
            : OperationUxPresenter::surfaceFailureDetail($this->run);
    }
}
