<?php

declare(strict_types=1);

namespace App\Filament\System\Pages\Directory\Concerns;

use App\Support\Badges\BadgeDomain;
use App\Support\Badges\BadgeRenderer;
use App\Support\CustomerHealth\CustomerHealthDimensionCatalog;
use App\Support\SystemConsole\SystemConsoleWindow;

trait BuildsCustomerHealthDecisionData
{
    /**
     * @param  array{
     *     overall_level: string,
     *     dimensions: array<string, array{label: string, level: string, windowed: bool}>,
     *     dominant_dimension_keys: list<string>
     * }  $summary
     * @return array{
     *     overall: array{label: string, color: string, icon: string|null},
     *     reason: string,
     *     impact: string,
     *     recommended_action: string,
     *     dominant_dimensions: list<array{label: string, color: string, icon: string|null}>,
     *     window_label: string
     * }
     */
    protected function buildCustomerHealthDecision(array $summary, SystemConsoleWindow $window, string $surface): array
    {
        $overallBadge = BadgeRenderer::spec(BadgeDomain::SystemHealth, $summary['overall_level']);

        $dominantDimensions = collect($summary['dominant_dimension_keys'])
            ->map(function (string $dimensionKey) use ($summary): ?array {
                $dimension = $summary['dimensions'][$dimensionKey] ?? null;

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

                $badge = BadgeRenderer::spec(BadgeDomain::SystemHealth, $dimension['level']);

                return [
                    'label' => $dimension['label'],
                    'color' => $badge->color,
                    'icon' => $badge->icon,
                ];
            })
            ->filter()
            ->take(2)
            ->values()
            ->all();

        $dominantLabels = array_map(static fn (array $dimension): string => $dimension['label'], $dominantDimensions);
        $primaryDimension = $summary['dominant_dimension_keys'][0] ?? null;

        return [
            'overall' => [
                'label' => $overallBadge->label,
                'color' => $overallBadge->color,
                'icon' => $overallBadge->icon,
            ],
            'reason' => $this->customerHealthReason($dominantLabels),
            'impact' => $this->customerHealthImpact($summary['overall_level'], $primaryDimension),
            'recommended_action' => $this->customerHealthRecommendedAction($summary['overall_level'], $primaryDimension, $surface),
            'dominant_dimensions' => $dominantDimensions,
            'window_label' => SystemConsoleWindow::options()[$window->value] ?? 'Last 24 hours',
        ];
    }

    /**
     * @param  list<string>  $dominantLabels
     */
    protected function customerHealthReason(array $dominantLabels): string
    {
        if ($dominantLabels === []) {
            return 'No active health drivers are pressuring this workspace right now.';
        }

        $labelPrefix = count($dominantLabels) === 1 ? 'Top driver' : 'Top drivers';

        return $labelPrefix.': '.implode(', ', $dominantLabels);
    }

    protected function customerHealthImpact(string $overallLevel, ?string $primaryDimension): string
    {
        if ($overallLevel === 'ok') {
            return 'Tracked onboarding, provider, operational, governance, review-pack, and engagement signals are currently stable.';
        }

        if ($overallLevel === 'unknown') {
            return 'Some required health truth is missing or stale, so this workspace cannot be treated as healthy yet.';
        }

        return match ($primaryDimension) {
            CustomerHealthDimensionCatalog::ONBOARDING_READINESS => $overallLevel === 'critical'
                ? 'Onboarding readiness is blocked, so this workspace cannot be treated as operationally ready.'
                : 'Onboarding readiness still needs follow-up before this workspace can be treated as fully stable.',
            CustomerHealthDimensionCatalog::PROVIDER_CONNECTION_HEALTH => $overallLevel === 'critical'
                ? 'Default provider consent or verification is blocking reliable tenant management.'
                : 'Provider connectivity has degraded and may impact reliable tenant management.',
            CustomerHealthDimensionCatalog::OPERATIONAL_STABILITY => $overallLevel === 'critical'
                ? 'Failed or stuck operations are actively putting delivery at risk.'
                : 'Recent operational noise is starting to erode delivery confidence.',
            CustomerHealthDimensionCatalog::GOVERNANCE_PRESSURE => $overallLevel === 'critical'
                ? 'High-severity or expired governance pressure needs immediate review.'
                : 'Governance pressure is active and should be reviewed before it escalates.',
            CustomerHealthDimensionCatalog::REVIEW_PACK_READINESS => $overallLevel === 'critical'
                ? 'Recent review-pack work is unusable or expired, so review readiness is blocked.'
                : 'Review-pack readiness is incomplete, so recent review evidence may not be usable yet.',
            CustomerHealthDimensionCatalog::ENGAGEMENT_FRESHNESS => $overallLevel === 'critical'
                ? 'Recent product activity is missing, which suggests active usage may be deteriorating.'
                : 'Recent product activity is thinning out and may indicate adoption drift.',
            default => $overallLevel === 'critical'
                ? 'This workspace needs immediate operator follow-up.'
                : 'This workspace needs follow-up soon to prevent further drift.',
        };
    }

    protected function customerHealthRecommendedAction(string $overallLevel, ?string $primaryDimension, string $surface): string
    {
        if ($overallLevel === 'ok') {
            return 'Continue normal monitoring from the system dashboard.';
        }

        return match ($primaryDimension) {
            CustomerHealthDimensionCatalog::ONBOARDING_READINESS => $surface === 'tenant'
                ? 'Confirm the tenant onboarding state with the responsible tenant admin and clear the blocking step.'
                : 'Open the affected tenant below and confirm which onboarding step is blocked.',
            CustomerHealthDimensionCatalog::PROVIDER_CONNECTION_HEALTH => $surface === 'tenant'
                ? 'Review connectivity signals below and confirm the default provider consent and verification state.'
                : 'Open the affected tenant below and review the default provider connection state.',
            CustomerHealthDimensionCatalog::OPERATIONAL_STABILITY => 'Review recent operations below and triage failed or stuck runs first.',
            CustomerHealthDimensionCatalog::GOVERNANCE_PRESSURE => $surface === 'tenant'
                ? 'Review governance findings or exception pressure for this tenant before proceeding.'
                : 'Open the affected tenant below and review governance findings or exceptions.',
            CustomerHealthDimensionCatalog::REVIEW_PACK_READINESS => 'Check recent review-pack activity and confirm that a usable pack exists for the current window.',
            CustomerHealthDimensionCatalog::ENGAGEMENT_FRESHNESS => $surface === 'tenant'
                ? 'Confirm whether missing recent product activity is expected for this tenant.'
                : 'Confirm whether missing recent product activity is expected across this workspace.',
            default => 'Review the diagnostics below to confirm which source truth needs operator follow-up.',
        };
    }
}