<?php

declare(strict_types=1);

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

use App\Repositories\LeadershipHuddleRepository;

$hospital = strtolower(trim((string)($_GET['hospital'] ?? 'njch'))) ?: 'njch';
header('Content-Type: text/plain; charset=utf-8');

echo "Leadership Huddle Purpose & Executive UX QA\n";
echo "Phase: 10.7.2 - Executive Leadership Typography & Readability Upgrade\n";
echo "Hospital: " . strtoupper($hospital) . "\n";
echo "Write operations: NONE\n\n";

try {
    $report = (new LeadershipHuddleRepository($hospital))->report();
    $center = is_array($report['center'] ?? null) ? $report['center'] : [];
    $actions = is_array($center['actions'] ?? null) ? $center['actions'] : [];
    $changes = is_array($report['meaningful_changes'] ?? null) ? $report['meaningful_changes'] : [];
    $agenda = is_array($report['decision_agenda'] ?? null) ? $report['decision_agenda'] : [];
    $commitmentRoot = is_array($report['open_commitments'] ?? null) ? $report['open_commitments'] : [];
    $commitments = is_array($commitmentRoot['rows'] ?? null) ? $commitmentRoot['rows'] : [];
    $decisions = is_array($report['documented_decisions'] ?? null) ? $report['documented_decisions'] : [];
    $owners = is_array($report['owner_accountability'] ?? null) ? $report['owner_accountability'] : [];
    $meeting = is_array($report['meeting_status'] ?? null) ? $report['meeting_status'] : [];
    $governance = is_array($report['governance'] ?? null) ? $report['governance'] : [];
    $sources = is_array($report['data_sources'] ?? null) ? $report['data_sources'] : [];
    $purposeQuestions = is_array($report['purpose_questions'] ?? null) ? $report['purpose_questions'] : [];

    $passCount = 0;
    $failCount = 0;
    $pass = static function (bool $ok, string $label, string $detail = '') use (&$passCount, &$failCount): void {
        if ($ok) { $passCount++; } else { $failCount++; }
        echo ($ok ? '[PASS] ' : '[FAIL] ') . str_pad($label, 48) . ($detail !== '' ? ' | ' . $detail : '') . "\n";
    };

    $materialOnly = true;
    foreach ($changes as $change) {
        if (!is_array($change) || empty($change['material'])) { $materialOnly = false; break; }
    }

    $agendaComplete = true;
    $agendaUnresolved = true;
    foreach ($agenda as $item) {
        if (!is_array($item)) { $agendaComplete = false; $agendaUnresolved = false; break; }
        if (trim((string)($item['why'] ?? '')) === '' || trim((string)($item['decision_required'] ?? '')) === '') { $agendaComplete = false; }
        if (strtolower((string)($item['accountability_status'] ?? '')) === 'resolved') { $agendaUnresolved = false; }
    }

    $decisionsClean = true;
    foreach ($decisions as $row) {
        if (!is_array($row)) { continue; }
        $actor = strtolower(trim((string)($row['by'] ?? '')));
        $note = strtolower(trim((string)($row['decision'] ?? '')));
        $qaActor = (strpos($actor, 'phase10_') === 0 && strpos($actor, '_qa') !== false)
            || strpos($actor, 'qa_') === 0
            || substr($actor, -3) === '_qa';
        $placeholder = in_array($note, ['test', 'testing', 'test note', 'demo', 'ok', 'n/a', 'na', '-'], true);
        if ($qaActor || $placeholder) { $decisionsClean = false; break; }
    }

    $repoFile = dirname(__DIR__) . '/app/Repositories/LeadershipHuddleRepository.php';
    $controllerFile = dirname(__DIR__) . '/app/Controllers/ActionCenterController.php';
    $viewFile = dirname(__DIR__) . '/app/Views/leadership_huddle/index.php';
    $layoutFile = dirname(__DIR__) . '/app/Views/layouts/main.php';
    $routeFile = __DIR__ . '/index.php';
    $cssFile = __DIR__ . '/assets/css/leadership-huddle.css';

    $repoSource = is_file($repoFile) ? (string)file_get_contents($repoFile) : '';
    $controllerSource = is_file($controllerFile) ? (string)file_get_contents($controllerFile) : '';
    $viewSource = is_file($viewFile) ? (string)file_get_contents($viewFile) : '';
    $layoutSource = is_file($layoutFile) ? (string)file_get_contents($layoutFile) : '';
    $routeSource = is_file($routeFile) ? (string)file_get_contents($routeFile) : '';
    $cssSource = is_file($cssFile) ? (string)file_get_contents($cssFile) : '';

    $readOnly = strpos($repoSource, 'Database::execute') === false
        && stripos($repoSource, 'DELETE FROM') === false
        && stripos($repoSource, 'UPDATE DASH_') === false
        && stripos($repoSource, 'INSERT INTO') === false;

    $sixQuestionMarkers = [
        'What changed since yesterday?',
        "Today's decision agenda",
        'What is overdue?',
        'Who owns what?',
        'What was decided today?',
        'What happens next?',
    ];
    $sixQuestionsInView = true;
    foreach ($sixQuestionMarkers as $marker) {
        if (stripos($viewSource, $marker) === false) { $sixQuestionsInView = false; break; }
    }

    echo "QA Gates:\n";
    $pass(in_array((string)($report['phase'] ?? ''), ['10.7.1', '10.7.2'], true), 'report_phase', (string)($report['phase'] ?? '-'));
    $pass((string)($report['purpose'] ?? '') === 'decision_agenda_and_commitments', 'purpose_is_decision_focused', (string)($report['purpose'] ?? '-'));
    $pass(count($purposeQuestions) === 6, 'six_executive_questions_declared', (string)count($purposeQuestions));
    $pass(!empty($report['summary_available']), 'summary_available', !empty($report['summary_available']) ? 'YES' : 'NO');
    $pass((string)($report['operational_date'] ?? '') !== '', 'operational_day_available', (string)($report['operational_date'] ?? '-'));
    $pass(count($changes) <= 4 && $materialOnly, 'meaningful_changes_only', (string)count($changes) . ' material changes');
    $pass(count($agenda) <= 4, 'decision_agenda_is_executive_shortlist', (string)count($agenda) . ' items');
    $pass($agendaComplete, 'decision_agenda_has_why_and_decision', 'why now + decision required');
    $pass($agendaUnresolved, 'decision_agenda_excludes_resolved', 'unresolved only');
    $pass(is_array($commitmentRoot) && array_key_exists('total', $commitmentRoot) && count($commitments) <= 5, 'open_commitments_shortlist_ready', (string)count($commitments) . ' visible');
    $pass(is_array($owners), 'owner_accountability_ready', (string)count($owners) . ' owner rows');
    $pass($decisionsClean, 'documented_decisions_are_production_clean', (string)count($decisions) . ' decisions');
    $pass((int)($meeting['decision_count'] ?? -1) === count($agenda), 'meeting_decision_count_matches_agenda', (string)count($agenda));
    $pass((int)($meeting['overdue'] ?? -1) === (int)($governance['overdue'] ?? -2), 'meeting_overdue_matches_governance', (string)($meeting['overdue'] ?? '-'));
    $pass((int)($meeting['unassigned'] ?? -1) === (int)($governance['unassigned'] ?? -2), 'meeting_ownership_gap_matches_governance', (string)($meeting['unassigned'] ?? '-'));
    $pass((string)($sources['review_storage'] ?? '') === 'oracle', 'review_storage_is_oracle', (string)($sources['review_storage'] ?? '-'));
    $pass((string)($sources['governance_storage'] ?? '') === 'oracle', 'governance_storage_is_oracle', (string)($sources['governance_storage'] ?? '-'));
    $pass($readOnly, 'huddle_repository_is_read_only', 'no insert/update/delete path');
    $pass(strpos($viewSource, 'huddle-kpi-grid') === false && strpos($viewSource, "['headline_kpis']") === false, 'duplicate_kpi_wall_removed_from_view', 'main dashboard keeps routine KPI wall');
    $pass($sixQuestionsInView, 'six_question_ux_present_in_view', 'change + decision + overdue + owner + decided + next');
    $pass(strpos($cssSource, '.huddle2-primary-grid{display:grid;grid-template-columns:minmax(0,1.35fr) minmax(320px,.65fr);gap:14px;align-items:start}') !== false, 'primary_grid_does_not_force_equal_height_whitespace', 'align-items:start');
    $pass(strpos($viewSource, 'not a repeat of the main dashboard') !== false, 'purpose_difference_is_explicit', 'decision agenda != KPI dashboard');
    $pass((strpos($cssSource, 'Phase 10.7.1') !== false || strpos($cssSource, 'Phase 10.7.2') !== false) && strpos($cssSource, '@media print') !== false, 'executive_redesign_css_and_print_ready', 'responsive + print');
    $pass(strpos($layoutSource, 'phase10-7-2-executive-leadership-readability') !== false, 'css_cache_buster_updated', '10.7.2 asset version');
    $pass(strpos($layoutSource, 'Phase 10.7.2') !== false, 'top_header_phase_updated', 'Executive Leadership Readability');
    $pass(strpos($controllerSource, 'leadershipHuddle()') !== false, 'controller_huddle_method_integrated', 'leadershipHuddle()');
    $pass(strpos($routeSource, "case 'leadership-huddle'") !== false, 'huddle_route_integrated', 'index.php?page=leadership-huddle');

    echo "\nExecutive Huddle Summary:\n";
    echo "operational_day       | " . (string)($report['operational_date'] ?? '-') . "\n";
    echo "meeting_state         | " . (string)($meeting['state'] ?? '-') . "\n";
    echo "meaningful_changes    | " . count($changes) . "\n";
    echo "decision_agenda       | " . count($agenda) . "\n";
    echo "open_commitments      | " . (string)($commitmentRoot['total'] ?? count($commitments)) . "\n";
    echo "documented_decisions  | " . count($decisions) . "\n";
    echo "overdue               | " . (string)($meeting['overdue'] ?? 0) . "\n";
    echo "follow_up_due         | " . (string)($meeting['follow_up_due'] ?? 0) . "\n";
    echo "ownership_gaps        | " . (string)($meeting['unassigned'] ?? 0) . "\n";
    echo "write_operations       | 0\n";

    echo "\nPurpose difference:\n";
    echo "Main dashboard         | What is happening now?\n";
    echo "Leadership huddle      | What changed, what needs a decision, who owns what, and what happens next?\n";

    echo "\nReport URL:\n";
    echo "index.php?page=leadership-huddle&lang=en\n";
    echo "\nQA result: " . ($failCount === 0 ? 'PASS' : 'FAIL') . "\n";
    echo "PASS gates: " . $passCount . "\n";
    echo "FAIL gates: " . $failCount . "\n";
    echo "QA is read-only. No review, governance, Oracle or audit row is modified.\n";
} catch (Throwable $e) {
    http_response_code(500);
    echo "ERROR: " . $e->getMessage() . "\n";
}
