<?php

declare(strict_types=1);

namespace App\Services;

use App\Repositories\InpatientDailyRevenueRuleSettingsRepository;
use PharData;
use Throwable;

final class InpatientDailyRevenueRulesQaService
{
    /** @return array<string,mixed> */
    public function run(): array
    {
        $checks = [];
        $add = static function (string $name, bool $ok, string $detail = '') use (&$checks): void {
            $checks[] = ['name' => $name, 'status' => $ok ? 'PASS' : 'FAIL', 'detail' => $detail];
        };

        $njch = (new InpatientDailyRevenueRuleSettingsRepository('njch'))->defaults();
        $mnh = (new InpatientDailyRevenueRuleSettingsRepository('mnh'))->defaults();

        $add('njch_national_payer_mapping_365', (int)$njch['national_payer']['company_id'] === 365, (string)$njch['national_payer']['company_id']);
        $add('njch_tcs_mapping_170', (int)$njch['tiered_payers']['tcs']['company_id'] === 170, (string)$njch['tiered_payers']['tcs']['company_id']);
        $add('njch_gosi_mapping_406', (int)$njch['tiered_payers']['gosi']['company_id'] === 406, (string)$njch['tiered_payers']['gosi']['company_id']);
        $add('mnh_national_payer_mapping_9002', (int)$mnh['national_payer']['company_id'] === 9002, (string)$mnh['national_payer']['company_id']);
        $add('mnh_tcs_mapping_2009', (int)$mnh['tiered_payers']['tcs']['company_id'] === 2009, (string)$mnh['tiered_payers']['tcs']['company_id']);
        $add('mnh_gosi_mapping_3005', (int)$mnh['tiered_payers']['gosi']['company_id'] === 3005, (string)$mnh['tiered_payers']['gosi']['company_id']);

        $expectedIcu = ['Intr ICU', 'ICU', 'NICU', 'PICU'];
        $add('icu_type_contract_exact_four_values', (array)$njch['national_payer']['icu_types'] === $expectedIcu, implode('|', (array)$njch['national_payer']['icu_types']));
        $add('mnh_icu_type_contract_exact_four_values', (array)$mnh['national_payer']['icu_types'] === $expectedIcu, implode('|', (array)$mnh['national_payer']['icu_types']));
        $add('national_short_stay_threshold_strictly_less_than_30', (int)$njch['national_payer']['short_stay_days_less_than'] === 30, 'service uses total_los < threshold');
        $add('national_short_stay_icu_rate_4746_87', abs((float)$njch['national_payer']['short_stay_icu_rate'] - 4746.87) < 0.001, (string)$njch['national_payer']['short_stay_icu_rate']);
        $add('national_standard_rate_2373', abs((float)$njch['national_payer']['standard_rate'] - 2373.00) < 0.001, (string)$njch['national_payer']['standard_rate']);
        $add('national_nicu_type_exact_nicu', (array)$njch['national_payer']['nicu_types'] === ['NICU'], implode('|', (array)$njch['national_payer']['nicu_types']));
        $add('national_nicu_day_limit_14_inclusive', (int)$njch['national_payer']['nicu_days_up_to'] === 14, (string)$njch['national_payer']['nicu_days_up_to']);
        $add('national_nicu_rate_days_1_14_5232_15', abs((float)$njch['national_payer']['nicu_rate_days_1_to_limit'] - 5232.15) < 0.001, (string)$njch['national_payer']['nicu_rate_days_1_to_limit']);
        $add('national_nicu_rate_after_14_3251_77', abs((float)$njch['national_payer']['nicu_rate_after_limit'] - 3251.77) < 0.001, (string)$njch['national_payer']['nicu_rate_after_limit']);
        $add('mnh_nicu_rule_matches_branch_equivalent_national_payer', (array)$mnh['national_payer']['nicu_types'] === ['NICU'] && (int)$mnh['national_payer']['nicu_days_up_to'] === 14 && abs((float)$mnh['national_payer']['nicu_rate_days_1_to_limit'] - 5232.15) < 0.001 && abs((float)$mnh['national_payer']['nicu_rate_after_limit'] - 3251.77) < 0.001, 'MNH 9002 uses the same approved NICU schedule');
        $add('shared_tier_1_3_2250', abs((float)$njch['tier_schedule']['days_1_3'] - 2250.00) < 0.001, (string)$njch['tier_schedule']['days_1_3']);
        $add('shared_tier_4_8_1950', abs((float)$njch['tier_schedule']['days_4_8'] - 1950.00) < 0.001, (string)$njch['tier_schedule']['days_4_8']);
        $add('shared_tier_9_plus_1750', abs((float)$njch['tier_schedule']['days_9_plus'] - 1750.00) < 0.001, (string)$njch['tier_schedule']['days_9_plus']);

        $njchRows = [
            $this->row(365, 1, 1, 'NICU'),
            $this->row(365, 14, 14, 'NICU'),
            $this->row(365, 15, 15, 'NICU'),
            $this->row(365, 29, 29, 'ICU'),
            $this->row(365, 29, 29, 'Intr ICU'),
            $this->row(365, 29, 29, 'PICU'),
            $this->row(365, 29, 29, 'Ward'),
            $this->row(365, 30, 30, 'ICU'),
            $this->row(170, 3, 3, 'Ward'),
            $this->row(170, 4, 4, 'Ward'),
            $this->row(170, 9, 9, 'Ward'),
            $this->row(406, 3, 3, 'Ward'),
            $this->row(406, 4, 4, 'Ward'),
            $this->row(406, 9, 9, 'Ward'),
            $this->row(1, 4, 4, 'Ward', 7864.66, 0.0),
            $this->row(777, 5, 5, 'Ward', 0.0, 12836.52),
        ];
        $njchReport = (new InpatientDailyRevenueService('njch', $njch))->build($njchRows);
        $p = $njchReport['patients'];
        $add('njch_365_nicu_day_1_uses_5232_15', abs((float)$p[0]['daily_revenue'] - 5232.15) < 0.001, (string)$p[0]['daily_revenue']);
        $add('njch_365_nicu_day_14_inclusive_uses_5232_15', abs((float)$p[1]['daily_revenue'] - 5232.15) < 0.001, (string)$p[1]['daily_revenue']);
        $add('njch_365_nicu_day_15_uses_3251_77', abs((float)$p[2]['daily_revenue'] - 3251.77) < 0.001, (string)$p[2]['daily_revenue']);
        $add('njch_365_short_stay_icu_uses_4746_87', abs((float)$p[3]['daily_revenue'] - 4746.87) < 0.001, (string)$p[3]['daily_revenue']);
        $add('njch_365_short_stay_intr_icu_uses_4746_87', abs((float)$p[4]['daily_revenue'] - 4746.87) < 0.001, (string)$p[4]['daily_revenue']);
        $add('njch_365_short_stay_picu_uses_4746_87', abs((float)$p[5]['daily_revenue'] - 4746.87) < 0.001, (string)$p[5]['daily_revenue']);
        $add('njch_365_short_stay_non_icu_uses_2373', abs((float)$p[6]['daily_revenue'] - 2373.00) < 0.001, (string)$p[6]['daily_revenue']);
        $add('njch_365_day_30_icu_uses_2373', abs((float)$p[7]['daily_revenue'] - 2373.00) < 0.001, (string)$p[7]['daily_revenue']);
        $add('njch_tcs_1_3', abs((float)$p[8]['daily_revenue'] - 2250.00) < 0.001, (string)$p[8]['daily_revenue']);
        $add('njch_tcs_4_8', abs((float)$p[9]['daily_revenue'] - 1950.00) < 0.001, (string)$p[9]['daily_revenue']);
        $add('njch_tcs_9_plus', abs((float)$p[10]['daily_revenue'] - 1750.00) < 0.001, (string)$p[10]['daily_revenue']);
        $add('njch_gosi_406_uses_tcs_tier_1_3', abs((float)$p[11]['daily_revenue'] - 2250.00) < 0.001, (string)$p[11]['daily_revenue']);
        $add('njch_gosi_406_uses_tcs_tier_4_8', abs((float)$p[12]['daily_revenue'] - 1950.00) < 0.001, (string)$p[12]['daily_revenue']);
        $add('njch_gosi_406_uses_tcs_tier_9_plus', abs((float)$p[13]['daily_revenue'] - 1750.00) < 0.001, (string)$p[13]['daily_revenue']);
        $add('cash_patient_share_per_continuous_los', abs((float)$p[14]['daily_revenue'] - 1966.17) < 0.001, (string)$p[14]['daily_revenue']);
        $add('other_insurance_company_share_per_continuous_los', abs((float)$p[15]['daily_revenue'] - 2567.30) < 0.001, (string)$p[15]['daily_revenue']);

        $mnhRows = [
            $this->row(9002, 14, 14, 'NICU'),
            $this->row(9002, 15, 15, 'NICU'),
            $this->row(9002, 29, 29, 'ICU'),
            $this->row(9002, 29, 29, 'Ward'),
            $this->row(2009, 3, 3, 'Ward'),
            $this->row(3005, 4, 4, 'Ward'),
            $this->row(3005, 9, 9, 'Ward'),
        ];
        $mnhReport = (new InpatientDailyRevenueService('mnh', $mnh))->build($mnhRows);
        $m = $mnhReport['patients'];
        $add('mnh_9002_nicu_day_14_uses_5232_15', abs((float)$m[0]['daily_revenue'] - 5232.15) < 0.001, (string)$m[0]['daily_revenue']);
        $add('mnh_9002_nicu_day_15_uses_3251_77', abs((float)$m[1]['daily_revenue'] - 3251.77) < 0.001, (string)$m[1]['daily_revenue']);
        $add('mnh_9002_short_stay_icu_4746_87', abs((float)$m[2]['daily_revenue'] - 4746.87) < 0.001, (string)$m[2]['daily_revenue']);
        $add('mnh_9002_short_stay_non_icu_2373', abs((float)$m[3]['daily_revenue'] - 2373.00) < 0.001, (string)$m[3]['daily_revenue']);
        $add('mnh_tcs_2009_uses_shared_tiers', abs((float)$m[4]['daily_revenue'] - 2250.00) < 0.001, (string)$m[4]['daily_revenue']);
        $add('mnh_gosi_3005_uses_shared_tier_4_8', abs((float)$m[5]['daily_revenue'] - 1950.00) < 0.001, (string)$m[5]['daily_revenue']);
        $add('mnh_gosi_3005_uses_shared_tier_9_plus', abs((float)$m[6]['daily_revenue'] - 1750.00) < 0.001, (string)$m[6]['daily_revenue']);

        $root = \base_path();
        $repoSource = (string)file_get_contents($root . '/app/Repositories/InpatientDailyRevenueRepository.php');
        $branchResolverSource = (string)file_get_contents($root . '/app/Repositories/InpatientDailyRevenueBranchResolver.php');
        $serviceSource = (string)file_get_contents($root . '/app/Services/InpatientDailyRevenueService.php');
        $settingsRepoSource = (string)file_get_contents($root . '/app/Repositories/InpatientDailyRevenueRuleSettingsRepository.php');
        $settingsControllerSource = (string)file_get_contents($root . '/app/Controllers/InpatientDailyRevenueSettingsController.php');
        $viewSource = (string)file_get_contents($root . '/app/Views/inpatient_daily_revenue/index.php');
        $settingsViewSource = (string)file_get_contents($root . '/app/Views/inpatient_daily_revenue/settings.php');
        $routeSource = (string)file_get_contents($root . '/public/index.php');
        $layoutSource = (string)file_get_contents($root . '/app/Views/layouts/main.php');
        $xlsxSource = (string)file_get_contents($root . '/app/Services/XlsxExportService.php');
        $templateXlsxSource = (string)file_get_contents($root . '/app/Services/TemplateXlsxExportService.php');
        $hybridXlsxSource = (string)file_get_contents($root . '/app/Services/HybridXlsxExportService.php');
        $exportConfigSource = (string)file_get_contents($root . '/config/inpatient_daily_revenue_export.php');
        $masterTemplatePath = $root . '/resources/templates/daily_inpatient_revenue_master.xlsx';
        $sqlSource = (string)file_get_contents($root . '/database/inpatient_daily_revenue_engine.sql');
        $oracleLiveToolSource = (string)file_get_contents($root . '/tools/test_inpatient_daily_revenue_p11_1_r3_oracle_live.php');

        $add('oracle_icu_type_join_present', stripos($repoSource, 'stp_nursingunit_type nut') !== false && stripos($repoSource, 'nut.desc_en AS nursing_unit_type') !== false, 'STP_NURSINGUNIT_TYPE.DESC_EN');
        $add('oracle_icu_type_reaches_final_result_set', preg_match('/ap\.nurs_cat,\s*ap\.nursing_unit_type,\s*ap\.bed_counts/is', $repoSource) === 1, 'nursing_unit_type is selected for the calculation service');
        $add('mnh_missing_static_branch_id_no_longer_blocks_runtime', strpos($repoSource, "oracle_branch_id'] ?? 0") === false && strpos($repoSource, 'InpatientDailyRevenueBranchResolver') !== false, 'repository uses deterministic branch resolver');
        $add('branch_resolver_uses_hospital_main_data_read_only_identity', stripos($branchResolverSource, 'FROM hospital_main_data') !== false && stripos($branchResolverSource, 'hosp_en_name') !== false, 'read-only hospital identity resolution');
        $add('branch_resolver_has_mnh_name_aliases', strpos($branchResolverSource, "'mnh' => ['mnh', 'madina', 'medina', 'madinah'") !== false, 'MNH aliases included');
        $add('branch_resolver_has_single_active_inpatient_fallback', stripos($branchResolverSource, 'SINGLE_ACTIVE_INPATIENT_BRANCH') !== false && stripos($branchResolverSource, 'FROM rcp_bed_trans bt') !== false, 'deterministic active-branch fallback');
        $add('branch_resolver_contains_no_oracle_write_dml', preg_match('/\b(INSERT|UPDATE|DELETE|MERGE|COMMIT|ROLLBACK)\b/i', $branchResolverSource) !== 1, 'Oracle writes NONE');
        $add('oracle_los_applies_to_all_payers_without_company_specific_bind', strpos($repoSource, ':national_payer_id_') === false && stripos($repoSource, 'f_get_first_admission_date') === false, 'one continuous LOS source for every payer');
        $add('oracle_active_census_and_patient_keys_materialized_for_performance', substr_count($repoSource, 'SELECT /*+ MATERIALIZE */ DISTINCT') >= 2, 'active census and active patient keys are materialization candidates');
        $add('oracle_continuous_los_scans_only_current_active_patient_keys', stripos($repoSource, 'active_patient_keys AS') !== false && stripos($repoSource, 'JOIN active_patient_keys k') !== false && stripos($repoSource, 'SELECT /*+ MATERIALIZE */ DISTINCT hosp_id, patientid') !== false, 'performance guard limits RCP_VISIT history to current census');
        $add('oracle_continuous_los_uses_rcp_visit_classcode_sequence', stripos($repoSource, 'FROM rcp_visit v') !== false && stripos($repoSource, 'LAG(v.classcode) OVER') !== false && stripos($repoSource, 'WHEN s.classcode = 1') !== false, 'ordered visit sequence with CLASSCODE=1');
        $add('oracle_non_inpatient_visit_breaks_inpatient_chain', stripos($repoSource, 'NVL(s.previous_classcode, -1) <> 1') !== false, 'any prior non-inpatient class starts a new inpatient run');
        $add('oracle_current_run_start_uses_first_visit_start_date', stripos($repoSource, 'MIN(r.visit_start_date) AS continuous_los_start_date') !== false && stripos($repoSource, 'r.inpatient_run_no = current_visit.inpatient_run_no') !== false, 'first date in current uninterrupted inpatient run');
        $add('oracle_all_patient_los_and_total_los_use_continuous_start', substr_count($repoSource, 'TRUNC(SYSDATE) - TRUNC(NVL(c.continuous_los_start_date, a.visit_start_date)) + 1') >= 2, 'LOS and Total LOS share the same continuous inpatient start');
        $add('oracle_no_hardcoded_365_los_logic', stripos($repoSource, 'WHERE financlassid = 365') === false && stripos($repoSource, 'WHEN a.financlassid = 365') === false, 'payer-independent LOS engine');
        $add('no_direct_legacy_revenue_procedure_call', preg_match('/\bSP_IPD_OPD_VAT_REVENUE\s*\(/i', $repoSource) !== 1 && preg_match('/\bSP_INPATIENT_REVENUE_DATA\s*\(/i', $repoSource) !== 1, 'repository execution path');
        $add('residence_package_flag_still_uses_r_alias', stripos($repoSource, 'NVL(r.in_out_pkg, 0)') !== false && stripos($repoSource, 'REG_PACKAGES.IN_OUT_PKG') === false, 'PACC_PAT_RES_TRAN alias r');
        $add('oracle_runtime_query_is_read_only', preg_match('/\b(INSERT|UPDATE|DELETE|MERGE|COMMIT|ROLLBACK)\b/i', $repoSource) !== 1, 'Oracle writes NONE');
        $add('database_reference_sql_matches_runtime_continuous_los_contract', stripos($sqlSource, 'stp_nursingunit_type nut') !== false && stripos($sqlSource, 'active_patient_keys AS') !== false && stripos($sqlSource, 'LAG(v.classcode) OVER') !== false && stripos($sqlSource, 'MIN(r.visit_start_date) AS continuous_los_start_date') !== false, 'reference SQL aligned with runtime continuous LOS engine');
        $add('live_oracle_read_only_proof_tool_present', strpos($oracleLiveToolSource, 'LIVE_READ_ONLY_SCHEMA_AND_CURRENT_INPATIENT_QUERY_MULTI_BRANCH') !== false && strpos($oracleLiveToolSource, 'currentInpatientsWithRevenue()') !== false && strpos($oracleLiveToolSource, "'oracle_writes' => 'NONE'") !== false, 'live current inpatient query + read-only declaration');
        $add('live_oracle_proof_tool_contains_no_write_dml', preg_match('/\b(INSERT|UPDATE|DELETE|MERGE|COMMIT|ROLLBACK)\b/i', $oracleLiveToolSource) !== 1, 'no write DML in live proof tool');
        $add('live_oracle_proof_requires_njch_and_mnh_nonzero_rows', strpos($oracleLiveToolSource, "['njch', 'mnh']") !== false && strpos($oracleLiveToolSource, 'Ready branch returned zero active inpatient rows') !== false, 'both ready branches must prove live data');
        $add('live_oracle_proof_validates_continuous_los_for_every_row', strpos($oracleLiveToolSource, 'continuous_los_rows_validated') !== false && strpos($oracleLiveToolSource, 'Continuous LOS contract failed for a live current-inpatient row.') !== false && strpos($oracleLiveToolSource, '$los !== $totalLos') !== false, 'every live row must have positive equal LOS/Total LOS from the shared continuous stay source');
        $add('live_oracle_proof_records_query_performance_telemetry', strpos($oracleLiveToolSource, 'query_elapsed_ms') !== false && strpos($oracleLiveToolSource, '$queryStarted = microtime(true);') !== false, 'records live query elapsed time without arbitrary pass/fail threshold');

        $add('settings_screen_route_registered', strpos($routeSource, "case 'inpatient-daily-revenue-settings':") !== false, 'GET + POST route');
        $add('settings_save_is_csrf_protected', strpos($settingsControllerSource, 'Csrf::validate') !== false, 'CSRF validation');
        $add('settings_edit_requires_finance_role', strpos($settingsControllerSource, "dashboard_role_fin") !== false && strpos($settingsControllerSource, 'private function canEdit(): bool') !== false, 'existing finance permission');
        $add('settings_storage_is_local_not_oracle', strpos($settingsRepoSource, "storage_path('inpatient_daily_revenue_rules/") !== false && stripos($settingsRepoSource, 'Database::') === false, 'local atomic settings persistence');
        $add('settings_atomic_write_backup_and_audit', strpos($settingsRepoSource, "LOCK_EX") !== false && strpos($settingsRepoSource, "rename(") !== false && strpos($settingsRepoSource, 'backupCurrentFile') !== false && strpos($settingsRepoSource, 'appendAudit') !== false, 'atomic save + backup + audit');
        $add('settings_windows_safe_swap_and_audit_rollback', strpos($settingsRepoSource, ".rollback.") !== false && strpos($settingsRepoSource, 'automatic rollback could not restore') !== false && strpos($settingsRepoSource, '@unlink($target)') !== false, 'same-directory swap with rollback on activation/audit failure');
        $add('settings_view_has_all_required_business_sections', strpos($settingsViewSource, 'national_payer') !== false && strpos($settingsViewSource, 'tier_schedule') !== false && strpos($settingsViewSource, 'tiered_payers') !== false && strpos($settingsViewSource, 'icu_types') !== false && strpos($settingsViewSource, 'nicu_rate_days_1_to_limit') !== false && strpos($settingsViewSource, 'nicu_rate_after_limit') !== false && strpos($settingsViewSource, 'Other insurance daily revenue') !== false, 'national + NICU + shared tiers + payer mappings + ICU types + other insurance policy');
        $add('settings_navigation_visible_only_to_finance_manager_role', strpos($layoutSource, '$canManageDailyRevenueSettings') !== false && strpos($layoutSource, "'visible' => \$canManageDailyRevenueSettings") !== false, 'not exposed to general executive users');
        $add('settings_nicu_rule_is_configurable_and_persisted', strpos($settingsRepoSource, 'nicu_days_up_to') !== false && strpos($settingsRepoSource, 'nicu_rate_days_1_to_limit') !== false && strpos($settingsRepoSource, 'nicu_rate_after_limit') !== false && strpos($settingsViewSource, 'rules[national_payer][nicu_days_up_to]') !== false, 'NICU threshold and both rates are managed in the protected settings screen');
        $add('settings_all_payer_los_source_is_continuous_inpatient_chain', substr_count($settingsRepoSource, "'los_source' => 'continuous_inpatient_chain_from_rcp_visit_classcode_1'") >= 4, 'national + tiered + cash + other insurance');
        $add('service_nicu_rule_precedes_general_icu_rule', strpos($serviceSource, 'if ($isNicu)') !== false && strpos($serviceSource, 'national_nicu_days_1_to_limit') !== false && strpos($serviceSource, 'national_short_stay_icu') !== false && strpos($serviceSource, 'if ($isNicu)') < strpos($serviceSource, 'national_short_stay_icu'), 'NICU special rate has explicit priority');

        $add('executive_screen_rule_panel_removed', strpos($viewSource, 'Approved calculation rules') === false && strpos($viewSource, 'قواعد الحساب المعتمدة') === false && strpos($viewSource, 'idr-rule-panel') === false, 'no rule panel');
        $add('executive_screen_calculation_method_column_removed', strpos($viewSource, "'Calculation', 'طريقة الحساب'") === false && strpos($viewSource, 'method_label') === false && strpos($viewSource, 'idr-method-pill') === false, 'no calculation method shown');
        $add('executive_screen_contains_no_fixed_rule_values', strpos($viewSource, '5232.15') === false && strpos($viewSource, '3251.77') === false && strpos($viewSource, '4746.87') === false && strpos($viewSource, '2373') === false && strpos($viewSource, '2250') === false && strpos($viewSource, '1950') === false && strpos($viewSource, '1750') === false, 'results only');
        $add('error_state_uses_na_not_false_zero', strpos($viewSource, "\$hasLoadError ? 'N/A'") !== false, 'N/A on load error');

        $add('xlsx_contains_no_calculation_rules_section', strpos($xlsxSource . $templateXlsxSource . $hybridXlsxSource, 'Approved Calculation Rules') === false && strpos($xlsxSource . $templateXlsxSource . $hybridXlsxSource, 'Uses the same LOS schedule as TCS.') === false && strpos($xlsxSource . $templateXlsxSource . $hybridXlsxSource, 'business_rules') === false, 'no calculation-rule content in workbook export path');
        $add('xlsx_hybrid_exporter_is_default', strpos($xlsxSource, "'hybrid_final'") !== false && strpos($xlsxSource, 'new HybridXlsxExportService') !== false && strpos($exportConfigSource, "'default_mode' => 'hybrid_final'") !== false, 'hybrid_final is the default export mode');
        $add('xlsx_hybrid_uses_code_driven_summary_and_daily', strpos($hybridXlsxSource, 'buildSummarySheet($report)') !== false && strpos($hybridXlsxSource, 'buildManualFriendlyDailyRevenueSheet($report)') !== false, 'Summary and Daily Revenue use the proven code-driven generator');
        $add('xlsx_hybrid_cell_chart_no_drawing_enabled', strpos($hybridXlsxSource, "'drawing' => false") !== false && strpos($hybridXlsxSource, 'STYLE_CHART_BAR_PURPLE') !== false && strpos($hybridXlsxSource, 'Daily Revenue Distribution (SR)') !== false, 'Revenue Chart uses Excel-safe worksheet cells with no drawing or chart package parts');
        $add('xlsx_hybrid_no_drawing_package_parts', strpos($hybridXlsxSource, "'xl/drawings/drawing1.xml'") === false && strpos($hybridXlsxSource, "'xl/charts/chart1.xml'") === false, 'no drawing XML is emitted, preventing Excel Desktop repair');
        $add('xlsx_hybrid_cell_bars_are_visible_without_support_table', strpos($hybridXlsxSource, "'hidden_columns' => []") !== false && strpos($hybridXlsxSource, 'barSegments') !== false, 'cell-based proportional bars remain visible without hidden drawing dependencies');
        $add('xlsx_summary_has_unit_average_column', strpos($hybridXlsxSource, '$unitAverage = $unitPatients > 0 ? ($unitRevenue / $unitPatients) : 0.0;') !== false || strpos($hybridXlsxSource, '$unitAverage = $unitPatients > 0 ? ($unitRevenue / $unitPatients) : 0;') !== false || strpos($hybridXlsxSource, '$unitAverage = $unitPatients > 0 ? ($unitRevenue / $unitPatients) : 0.0') !== false, 'summary care-area average remains dynamically populated');
        $add('xlsx_detail_has_unit_average_below_each_unit', strpos($hybridXlsxSource, 'Average Daily Revenue per Patient') !== false && strpos($hybridXlsxSource, '$unitAverage = $patientCountUnit > 0 ? ($unitRevenue / $patientCountUnit) : 0.0;') !== false, 'average remains below every unit subtotal');
        $add('xlsx_rollback_modes_preserved', strpos($exportConfigSource, "'legacy_r9'") !== false && strpos($exportConfigSource, "'template_final'") !== false && strpos($exportConfigSource, "'template_r10b'") !== false, 'legacy and both template rollback modes remain available');
        $add('xlsx_template_rollback_assets_present', is_file($masterTemplatePath) && filesize($masterTemplatePath) > 5000 && is_file($root . '/resources/templates/daily_inpatient_revenue_master_r10b_backup.xlsx'), 'template rollback assets remain present');
        $add('xlsx_old_national_rule_text_removed', strpos($xlsxSource . $templateXlsxSource . $hybridXlsxSource, 'Total LOS <= 30: 4,746.87') === false, 'old <=30 rule absent');
        $add('php74_compatibility_runtime_files', $this->php74Compatible([$repoSource, $branchResolverSource, $serviceSource, $settingsRepoSource, $settingsControllerSource, $viewSource, $settingsViewSource, $xlsxSource, $templateXlsxSource, $hybridXlsxSource]), 'no PHP 8-only syntax markers');

        $njchReport['business_rules'] = $njch;
        $njchReport['hospital_code'] = 'NJCH';
        $njchReport['hospital_name'] = 'New Jeddah';
        $tmp = sys_get_temp_dir() . '/ddb_idr_rules_qa_' . bin2hex(random_bytes(6)) . '.xlsx';
        try {
            (new XlsxExportService())->createFinalWorkbookFile($tmp, $njchReport);
            $signature = is_file($tmp) ? (string)file_get_contents($tmp, false, null, 0, 2) : '';
            $add('xlsx_runtime_created', is_file($tmp) && filesize($tmp) > 5000 && $signature === 'PK', is_file($tmp) ? (string)filesize($tmp) : 'missing');
            $archive = new PharData($tmp);
            $summaryXml = isset($archive['xl/worksheets/sheet1.xml']) ? (string)$archive['xl/worksheets/sheet1.xml']->getContent() : '';
            $dailyXml = isset($archive['xl/worksheets/sheet2.xml']) ? (string)$archive['xl/worksheets/sheet2.xml']->getContent() : '';
            $chartSheetXml = isset($archive['xl/worksheets/sheet3.xml']) ? (string)$archive['xl/worksheets/sheet3.xml']->getContent() : '';
            $chartXml = isset($archive['xl/charts/chart1.xml']) ? (string)$archive['xl/charts/chart1.xml']->getContent() : '';
            $drawingXml = isset($archive['xl/drawings/drawing1.xml']) ? (string)$archive['xl/drawings/drawing1.xml']->getContent() : '';
            $workbookXml = isset($archive['xl/workbook.xml']) ? (string)$archive['xl/workbook.xml']->getContent() : '';
            $allWorkbookText = $summaryXml . $dailyXml . $chartSheetXml . $chartXml;
            $sheetCount = substr_count($workbookXml, '<x:sheet ') + substr_count($workbookXml, '<sheet ');
            $add('xlsx_runtime_three_requested_sheets', $sheetCount === 3 && strpos($workbookXml, 'Summary') !== false && strpos($workbookXml, 'Daily Revenue') !== false && strpos($workbookXml, 'Revenue Chart') !== false, 'Summary + Daily Revenue + Revenue Chart');
            $add('xlsx_runtime_obsolete_audit_sheets_absent', strpos($workbookXml, 'Detailed Audit') === false && strpos($workbookXml, 'Needs Review') === false, 'obsolete sheets remain absent');
            $add('xlsx_runtime_calculation_rules_absent_everywhere', stripos($allWorkbookText, 'Calculation Rules') === false && stripos($allWorkbookText, 'Total LOS &lt; 30') === false && stripos($allWorkbookText, 'Uses the same LOS schedule as TCS') === false, 'no calculation-rule content in workbook parts');
            $add('xlsx_runtime_summary_unit_average_present', strpos($summaryXml, 'Average / Patient (SR)') !== false, 'summary care-area daily revenue average column');
            $add('xlsx_runtime_detail_unit_average_present', strpos($dailyXml, 'Average Daily Revenue per Patient') !== false, 'average below each unit subtotal');
            $add('xlsx_runtime_hybrid_populated_all_current_units', substr_count($dailyXml, 'Unit Daily Revenue Total') === count($njchReport['units'] ?? []), 'one subtotal for every current unit from the code-driven detail generator');
            $add('xlsx_runtime_chart_uses_excel_safe_cells_only', strpos($chartSheetXml, 'Daily Revenue Distribution') !== false && strpos($chartSheetXml, 'Top 5 Payers') !== false && strpos($chartSheetXml, 'Total Daily Revenue') !== false, 'Revenue Chart is a worksheet-cell visual, not a drawing object');
            $add('xlsx_runtime_no_drawing_xml_part', $drawingXml === '' && !isset($archive['xl/drawings/drawing1.xml']), 'no drawing1.xml can be removed by Excel Desktop');
            $add('xlsx_runtime_no_chart_xml_part', $chartXml === '' && !isset($archive['xl/charts/chart1.xml']), 'no chart1.xml dependency remains');
            $add('xlsx_runtime_no_sheet3_drawing_relationship', !isset($archive['xl/worksheets/_rels/sheet3.xml.rels']), 'sheet3 has no drawing relationship');
            $add('xlsx_runtime_hybrid_architecture_preserves_legacy_sheets_and_has_no_drawing_parts', isset($archive['xl/styles.xml']) && !isset($archive['xl/drawings/drawing1.xml']) && !isset($archive['xl/charts/chart1.xml']) && !isset($archive['xl/worksheets/_rels/sheet3.xml.rels']) && strpos($summaryXml, 'Revenue by Care Area') !== false && strpos($dailyXml, 'Attending Doctor') !== false && strpos($chartSheetXml, 'Daily Revenue Distribution') !== false, 'code-driven Summary/Daily plus Excel-safe cell chart preserved');
        } catch (Throwable $e) {
            $add('xlsx_runtime_created', false, $e->getMessage());
        } finally {
            @unlink($tmp);
            @unlink($tmp . '.zip');
        }

        $failures = count(array_filter($checks, static fn(array $check): bool => $check['status'] === 'FAIL'));
        return [
            'phase' => 'H11.0-P11.1-R10F',
            'release' => '11.0.11.13',
            'title' => 'Daily Inpatient Revenue Native Chart Drawing Repair Closure',
            'checks' => $checks,
            'pass_gates' => count($checks) - $failures,
            'fail_gates' => $failures,
            'oracle_writes' => 'NONE',
            'status' => $failures === 0 ? 'PASS' : 'FAIL',
        ];
    }

    /** @return array<string,mixed> */
    private function row(int $companyId, int $los, int $totalLos, string $unitType, float $patientShare = 0.0, float $companyShare = 0.0): array
    {
        return [
            'financlassid' => $companyId,
            'financial_class' => 'PAYER ' . $companyId,
            'los' => $los,
            'total_los' => $totalLos,
            'patient_share_total' => $patientShare,
            'company_share_total' => $companyShare,
            'unit_name' => $unitType === 'Ward' ? 'Ward A' : $unitType,
            'nursing_unit_type' => $unitType,
            'bed_counts' => 20,
        ];
    }

    /** @param array<int,string> $sources */
    private function php74Compatible(array $sources): bool
    {
        foreach ($sources as $source) {
            if (preg_match('/\bmatch\s*\(/', $source) === 1
                || strpos($source, '?->') !== false
                || stripos($source, 'str_contains(') !== false
                || stripos($source, 'str_starts_with(') !== false
                || stripos($source, 'str_ends_with(') !== false
                || preg_match('/\breadonly\s+(?:class|public|protected|private)|\benum\s+[A-Za-z_]/', $source) === 1) {
                return false;
            }
        }
        return true;
    }
}
