<?php

declare(strict_types=1);

namespace App\Repositories;

use App\Services\ExecutiveAlertRuleEngine;
use Throwable;

final class ExecutiveActionRepository
{
    /** @var string */
    private $hospitalCode;

    public function __construct(string $hospitalCode)
    {
        $this->hospitalCode = strtolower(trim($hospitalCode)) ?: 'njch';
    }

    /** @return array<string,mixed> */
    public function center(): array
    {
        $summary = null;
        $error = null;

        try {
            $summary = (new ExecutiveSummaryRepository($this->hospitalCode))->latestForToday();
        } catch (Throwable $e) {
            $error = $e->getMessage();
            $this->log('summary-read', $e);
        }

        $rows = is_array($summary['rows'] ?? null) ? $summary['rows'] : [];
        $operational = is_array($summary['operational'] ?? null) ? $summary['operational'] : [];
        $lastUpdated = (string)($summary['last_updated'] ?? '');
        $isStale = !empty($summary['is_stale']);

        $m = [
            'opd' => $this->value($rows, 'opd'),
            'er' => $this->value($rows, 'er'),
            'admissions' => $this->value($rows, 'admissions'),
            'discharges' => $this->value($rows, 'discharges'),
            'scheduled_operations' => $this->value($rows, 'scheduled_operations'),
            'performed_operations' => $this->value($rows, 'performed_operations'),
            'today_total' => $this->value($rows, 'today_total'),
            'month_total' => $this->value($rows, 'month_total'),
            'cash' => $this->value($rows, 'cash'),
            'insurance' => $this->value($rows, 'insurance'),
            'moh' => $this->value($rows, 'moh'),
            'net' => $this->value($rows, 'net'),
            'total_beds' => $this->value($rows, 'total_beds'),
            'occupied_beds' => $this->value($rows, 'occupied_beds'),
            'available_beds' => $this->value($rows, 'available_beds'),
            'occupancy_rate' => $this->value($rows, 'occupancy_rate'),
            'blocked_beds' => $this->value($rows, 'blocked_beds'),
            'active_doctors' => $this->value($rows, 'active_doctors'),
            'expected_discharges' => $this->value($rows, 'expected_discharges'),
            'unit_icu' => $this->value($rows, 'unit_icu'),
            'unit_medical' => $this->value($rows, 'unit_medical'),
            'unit_surgical' => $this->value($rows, 'unit_surgical'),
        ];

        $engine = new ExecutiveAlertRuleEngine($this->hospitalCode);
        $actions = $engine->evaluate($rows, $m, $summary !== null, $isStale, $error, $operational);
        $operationalDate = (string)($operational['operational_date'] ?? date('Y-m-d'));
        $reviewRepo = new ExecutiveActionReviewRepository($this->hospitalCode);
        $actions = $reviewRepo->applyToActions($actions, $operationalDate);
        $reviewSummary = $reviewRepo->summary($actions);
        $reviewManagement = $reviewRepo->managementSummary($actions, $operationalDate);

        $governanceRepo = new ExecutiveActionGovernanceRepository($this->hospitalCode);
        $actions = $governanceRepo->applyToActions($actions, $operationalDate);
        $governanceSummary = $governanceRepo->managementSummary($actions, $operationalDate);
        $counts = ['critical' => 0, 'watch' => 0, 'routine' => 0, 'opportunity' => 0];
        foreach ($actions as $a) {
            $sev = (string)($a['severity'] ?? 'routine');
            if (isset($counts[$sev])) { $counts[$sev]++; }
        }

        return [
            'mode' => 'action-center',
            'hospital_code' => strtoupper($this->hospitalCode),
            'summary_available' => $summary !== null,
            'summary_error' => $error,
            'is_stale' => $isStale,
            'last_updated' => $lastUpdated,
            'operational' => $operational,
            'metrics' => $m,
            'actions' => $actions,
            'counts' => $counts,
            'system' => $this->systemStatus($summary !== null, $isStale, $actions),
            'quick_tools' => $this->quickTools(),
            'review_workflow' => [
                'enabled' => true,
                'version' => 'Phase 10.6.6',
                'counts' => $reviewSummary,
                'management' => $reviewManagement,
                'storage' => $reviewRepo->storageMode(),
                'audit_trail' => true,
                'history_scope' => 'all_operational_days',
                'filters' => ['all', 'open', 'reviewed', 'deferred', 'critical'],
                'transition_matrix' => [
                    'open' => $reviewRepo->allowedTransitions('open'),
                    'reviewed' => $reviewRepo->allowedTransitions('reviewed'),
                    'deferred' => $reviewRepo->allowedTransitions('deferred'),
                ],
            ],
            'governance' => [
                'enabled' => true,
                'version' => 'Phase 10.6.6',
                'storage' => $governanceRepo->storageMode(),
                'summary' => $governanceSummary,
                'audit_trail' => true,
                'ownership_persists_across_days' => true,
                'accountability_states' => ['unassigned', 'assigned', 'due_soon', 'follow_up_due', 'overdue', 'escalated', 'resolved'],
                'escalation_levels' => ['none', 'watch', 'high', 'critical'],
            ],
            'engine' => [
                'version' => 'Phase 10.6.6',
                'name' => 'Executive Governance & Accountability Engine',
                'thresholds' => $engine->thresholds(),
                'revenue_calibration' => $engine->revenuePaceCalibration([
                    'today_total' => $m['today_total'],
                    'month_total' => $m['month_total'],
                    'patient_flow' => (float)($m['opd'] ?: 0) + (float)($m['er'] ?: 0) + (float)($m['admissions'] ?: 0),
                ], $operational),
            ],
        ];
    }

    /** @param array<string,array<string,mixed>> $rows */
    private function value(array $rows, string $code)
    {
        $key = strtolower($code);
        if (!isset($rows[$key]) || !is_array($rows[$key])) { return null; }
        $v = $rows[$key]['kpi_value'] ?? null;
        if ($v === null || $v === '') { return null; }
        return (float)$v;
    }

    /** @param array<int,array<string,mixed>> $actions @return array<string,mixed> */
    private function systemStatus(bool $summaryAvailable, bool $isStale, array $actions): array
    {
        $critical = 0;
        $watch = 0;
        foreach ($actions as $a) {
            if (($a['severity'] ?? '') === 'critical') { $critical++; }
            if (($a['severity'] ?? '') === 'watch') { $watch++; }
        }

        if (!$summaryAvailable || $critical > 0) {
            return ['status' => 'ACTION REQUIRED', 'status_ar' => 'يتطلب إجراء', 'tone' => 'critical', 'text' => 'Critical executive actions need attention.', 'text_ar' => 'توجد إجراءات تنفيذية حرجة تحتاج انتباه.'];
        }
        if ($isStale || $watch > 0) {
            return ['status' => 'WATCH', 'status_ar' => 'متابعة', 'tone' => 'watch', 'text' => 'Some indicators require review.', 'text_ar' => 'بعض المؤشرات تحتاج مراجعة.'];
        }
        return ['status' => 'STABLE', 'status_ar' => 'مستقر', 'tone' => 'good', 'text' => 'No blocking executive actions.', 'text_ar' => 'لا توجد إجراءات تنفيذية مانعة.'];
    }

    /** @return array<int,array<string,string>> */
    private function quickTools(): array
    {
        return [
            ['label' => 'Dashboard', 'label_ar' => 'الداشبورد', 'type' => 'page', 'target' => 'dashboard', 'icon' => '▦'],
            ['label' => 'Daily Huddle', 'label_ar' => 'الاجتماع اليومي', 'type' => 'page', 'target' => 'leadership-huddle', 'icon' => '☷'],
            ['label' => 'Review Dashboard', 'label_ar' => 'لوحة المراجعات', 'type' => 'page', 'target' => 'action-review-dashboard', 'icon' => '◫'],
            ['label' => 'Governance Dashboard', 'label_ar' => 'لوحة الحوكمة والمتابعة', 'type' => 'page', 'target' => 'action-governance-dashboard', 'icon' => '◎'],
            ['label' => 'Alert Rules', 'label_ar' => 'قواعد التنبيه', 'type' => 'public', 'target' => 'executive-alert-rules-check.php?hospital=' . rawurlencode($this->hospitalCode), 'icon' => '⚑'],
            ['label' => 'Explainability', 'label_ar' => 'شرح التنبيهات', 'type' => 'public', 'target' => 'executive-alert-explainability-check.php?hospital=' . rawurlencode($this->hospitalCode), 'icon' => '☷'],
            ['label' => 'Review Workflow', 'label_ar' => 'سير المراجعة', 'type' => 'public', 'target' => 'executive-action-review-check.php?hospital=' . rawurlencode($this->hospitalCode), 'icon' => '☑'],
            ['label' => 'Review QA', 'label_ar' => 'فحص المراجعة', 'type' => 'public', 'target' => 'executive-action-review-workflow-qa.php?hospital=' . rawurlencode($this->hospitalCode), 'icon' => '✓'],
            ['label' => 'Review Management QA', 'label_ar' => 'فحص إدارة المراجعات', 'type' => 'public', 'target' => 'executive-action-review-management-qa.php?hospital=' . rawurlencode($this->hospitalCode), 'icon' => '◎'],
            ['label' => 'Refresh Status', 'label_ar' => 'حالة التحديث', 'type' => 'public', 'target' => 'executive-summary-refresh-status.php?hospital=' . rawurlencode($this->hospitalCode), 'icon' => '◷'],
            ['label' => 'Summary Check', 'label_ar' => 'فحص الملخص', 'type' => 'public', 'target' => 'executive-summary-check.php?hospital=' . rawurlencode($this->hospitalCode), 'icon' => '▤'],
            ['label' => 'Beds Mapping', 'label_ar' => 'خريطة الأسرة', 'type' => 'public', 'target' => 'beds-unit-mapping-check.php?hospital=' . rawurlencode($this->hospitalCode), 'icon' => '▱'],
            ['label' => 'Finance Check', 'label_ar' => 'فحص المالي', 'type' => 'public', 'target' => 'operational-finance-check.php?hospital=' . rawurlencode($this->hospitalCode), 'icon' => '◈'],
        ];
    }

    private function log(string $context, Throwable $e): void
    {
        $file = \storage_path('logs/app.log');
        $dir = dirname($file);
        if (!is_dir($dir)) { @mkdir($dir, 0775, true); }
        @file_put_contents($file, '[' . date('c') . '] ExecutiveActionRepository ' . $context . ': ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
    }
}
