<?php

declare(strict_types=1);

require_once dirname(__DIR__) . '/app/bootstrap.php';

use App\Repositories\ExecutiveActionRepository;
use App\Repositories\ExecutiveActionReviewRepository;

$hospital = strtolower(trim((string)($_GET['hospital'] ?? 'njch'))) ?: 'njch';
$days = (int)($_GET['days'] ?? 30);
$days = max(7, min(90, $days));

header('Content-Type: text/plain; charset=utf-8');

echo "Executive Review Dashboard Analytics Purity QA\n";
echo "Phase: 10.6.5.1 — Production Analytics Purity & QA Activity Exclusion Hotfix\n";
echo "Hospital: " . strtoupper($hospital) . "\n";
echo "Analytics window: " . $days . " days\n";
echo "Write operations: NONE\n\n";

try {
    $center = (new ExecutiveActionRepository($hospital))->center();
    $repo = new ExecutiveActionReviewRepository($hospital);
    $op = is_array($center['operational'] ?? null) ? $center['operational'] : [];
    $operationalDate = (string)($op['operational_date'] ?? date('Y-m-d'));
    $actions = is_array($center['actions'] ?? null) ? $center['actions'] : [];

    // Default production analytics must exclude automated QA actors.
    $production = $repo->managementDashboard($actions, $operationalDate, $days, false);
    // Technical proof view includes every immutable audit row, including QA evidence.
    $technicalBefore = $repo->managementDashboard($actions, $operationalDate, $days, true);
    $technicalAfter = $repo->managementDashboard($actions, $operationalDate, $days, true);

    $prodWindow = is_array($production['window'] ?? null) ? $production['window'] : [];
    $prodPurity = is_array($production['purity'] ?? null) ? $production['purity'] : [];
    $prodReviewers = is_array($production['reviewers'] ?? null) ? $production['reviewers'] : [];
    $prodRecent = is_array($production['recent_activity'] ?? null) ? $production['recent_activity'] : [];
    $prodTop = is_array($production['top_actions'] ?? null) ? $production['top_actions'] : [];
    $techWindow = is_array($technicalBefore['window'] ?? null) ? $technicalBefore['window'] : [];
    $techPurity = is_array($technicalBefore['purity'] ?? null) ? $technicalBefore['purity'] : [];

    $isQaActor = static function (string $actor): bool {
        $actor = strtolower(trim($actor));
        if ($actor === '') { return false; }
        if (preg_match('/^phase[0-9]+(?:_[0-9]+)*(?:_[a-z0-9]+)*_qa(?:_[a-z0-9]+)*$/i', $actor) === 1) { return true; }
        if (preg_match('/^qa(?:[_\-.][a-z0-9]+)*$/i', $actor) === 1) { return true; }
        if (preg_match('/^(?:e[0-9]+_)?h[0-9_]+_qa(?:_[a-z0-9]+)*$/i', $actor) === 1) { return true; }
        $configured = trim((string)env('EXEC_ACTION_REVIEW_QA_ACTORS', ''));
        if ($configured !== '') {
            foreach (preg_split('/[,;\r\n]+/', $configured) ?: [] as $pattern) {
                $pattern = strtolower(trim((string)$pattern));
                if ($pattern === '') { continue; }
                $quoted = preg_quote($pattern, '/');
                $regex = '/^' . str_replace('\\*', '.*', $quoted) . '$/i';
                if (preg_match($regex, $actor) === 1) { return true; }
            }
        }
        return false;
    };

    $reviewersClean = true;
    foreach ($prodReviewers as $row) {
        if (is_array($row) && $isQaActor((string)($row['reviewer'] ?? ''))) { $reviewersClean = false; break; }
    }
    $recentClean = true;
    foreach ($prodRecent as $row) {
        if (is_array($row) && $isQaActor((string)($row['changed_by'] ?? ''))) { $recentClean = false; break; }
    }

    $rawBefore = (int)($techPurity['raw_audit_count'] ?? 0);
    $rawAfter = (int)($technicalAfter['purity']['raw_audit_count'] ?? -1);
    $productionCount = (int)($prodPurity['management_audit_count'] ?? -1);
    $qaDetected = (int)($prodPurity['qa_rows_detected'] ?? 0);
    $excluded = (int)($prodPurity['excluded_qa_count'] ?? 0);
    $technicalCount = (int)($techPurity['management_audit_count'] ?? -1);
    $expectedProductionCount = max(0, $rawBefore - $qaDetected);

    $pass = static function (bool $ok, string $label, string $detail = ''): void {
        echo ($ok ? '[PASS] ' : '[FAIL] ') . str_pad($label, 44) . ($detail !== '' ? ' | ' . $detail : '') . "\n";
    };

    echo "QA Gates:\n";
    $pass((string)($production['phase'] ?? '') === '10.6.5.1', 'analytics_phase', (string)($production['phase'] ?? '-'));
    $pass(empty($prodPurity['include_qa_activity']), 'production_mode_default', (string)($prodPurity['mode'] ?? '-'));
    $pass(!empty($techPurity['include_qa_activity']), 'technical_include_qa_mode_available', (string)($techPurity['mode'] ?? '-'));
    $pass($productionCount === $expectedProductionCount, 'management_count_excludes_qa', $productionCount . ' = ' . $rawBefore . ' raw - ' . $qaDetected . ' QA');
    $pass($excluded === $qaDetected, 'qa_rows_excluded_by_default', $excluded . ' excluded');
    $pass($technicalCount === $rawBefore, 'technical_mode_preserves_full_evidence', $technicalCount . ' / ' . $rawBefore);
    $pass($rawBefore === $rawAfter, 'raw_audit_rows_preserved_no_delete', $rawBefore . ' before / ' . $rawAfter . ' after');
    $pass((int)($prodPurity['rows_deleted'] ?? -1) === 0, 'repository_declares_zero_row_deletion', '0 rows deleted');
    $pass($reviewersClean, 'qa_actors_absent_from_reviewer_activity', count($prodReviewers) . ' production reviewers');
    $pass($recentClean, 'qa_actors_absent_from_recent_activity', count($prodRecent) . ' production events shown');
    $pass((int)($prodWindow['active_reviewers'] ?? -1) === count($prodReviewers), 'active_reviewer_kpi_matches_filtered_rows', (string)($prodWindow['active_reviewers'] ?? 0));
    $pass((int)($prodWindow['audit_count'] ?? -1) === $productionCount, 'audit_kpi_matches_filtered_rows', (string)($prodWindow['audit_count'] ?? 0));
    $pass(is_array($prodTop), 'top_actions_built_from_filtered_rows', (string)count($prodTop));
    $pass(isset($prodWindow['activity_7d'], $prodWindow['velocity_trend_percent']), 'velocity_uses_filtered_rows', '7d=' . (string)($prodWindow['activity_7d'] ?? 0));
    $pass((string)($prodPurity['filter_version'] ?? '') === '10.6.5.1', 'purity_filter_version', (string)($prodPurity['filter_version'] ?? '-'));

    $dashboardFile = dirname(__DIR__) . '/app/Views/action_center/dashboard.php';
    $controllerFile = dirname(__DIR__) . '/app/Controllers/ActionCenterController.php';
    $repositoryFile = dirname(__DIR__) . '/app/Repositories/ExecutiveActionReviewRepository.php';
    $cssFile = __DIR__ . '/assets/css/action-center.css';
    $dashboardSource = is_file($dashboardFile) ? (string)file_get_contents($dashboardFile) : '';
    $controllerSource = is_file($controllerFile) ? (string)file_get_contents($controllerFile) : '';
    $repositorySource = is_file($repositoryFile) ? (string)file_get_contents($repositoryFile) : '';
    $cssSource = is_file($cssFile) ? (string)file_get_contents($cssFile) : '';
    $pass(strpos($dashboardSource, 'Include QA activity') !== false && strpos($dashboardSource, 'review-analytics-purity-banner') !== false, 'dashboard_purity_controls_integrated', 'toggle + purity banner');
    $pass(strpos($controllerSource, "Request::get('include_qa'" ) !== false, 'controller_include_qa_switch_integrated', 'include_qa query switch');
    $pass(strpos($repositorySource, 'EXEC_ACTION_REVIEW_QA_ACTORS') !== false, 'configurable_qa_actor_patterns_supported', 'EXEC_ACTION_REVIEW_QA_ACTORS');
    $pass(strpos($cssSource, 'Phase 10.6.5.1 — Production Analytics Purity') !== false, 'purity_ui_css_integrated', 'action-center.css');

    echo "\nPurity Summary:\n";
    echo "operational_day          | " . $operationalDate . "\n";
    echo "mode_default             | " . (string)($prodPurity['mode'] ?? '-') . "\n";
    echo "raw_audit_rows           | " . $rawBefore . "\n";
    echo "qa_rows_detected         | " . $qaDetected . "\n";
    echo "management_audit_rows    | " . $productionCount . "\n";
    echo "excluded_qa_rows         | " . $excluded . "\n";
    echo "production_reviewers     | " . (string)($prodWindow['active_reviewers'] ?? 0) . "\n";
    echo "technical_reviewers      | " . (string)($techWindow['active_reviewers'] ?? 0) . "\n";
    echo "production_activity_7d   | " . (string)($prodWindow['activity_7d'] ?? 0) . "\n";
    echo "technical_activity_7d    | " . (string)($techWindow['activity_7d'] ?? 0) . "\n";
    echo "qa_actors_detected       | " . implode(', ', (array)($prodPurity['qa_actors_detected'] ?? [])) . "\n";
    echo "rows_deleted             | 0\n";

    echo "\nDashboard URLs:\n";
    echo "Production view (default): index.php?page=action-review-dashboard&lang=en&days=" . $days . "\n";
    echo "Technical view with QA:   index.php?page=action-review-dashboard&lang=en&days=" . $days . "&include_qa=1\n";
    echo "\nQA is read-only. Oracle review rows and audit evidence are never deleted or modified.\n";
} catch (Throwable $e) {
    http_response_code(500);
    echo "ERROR: " . $e->getMessage() . "\n";
}
