<?php

declare(strict_types=1);

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

use App\Services\MultiBranchOutpatientParityService;

$root = dirname(__DIR__);
$format = strtolower((string)($_GET['format'] ?? 'text'));
$runLive = (string)($_GET['run_live'] ?? '1') !== '0';
if ($format === 'json') {
    ini_set('display_errors', '0');
}

$remote = (string)($_SERVER['REMOTE_ADDR'] ?? '');
$isLocal = in_array($remote, ['127.0.0.1', '::1', 'localhost', ''], true);
$providedToken = (string)($_GET['token'] ?? '');
$expectedToken = trim((string)env('DDB_QA_TOKEN', ''));
$tokenOk = $expectedToken !== '' && hash_equals($expectedToken, $providedToken);
if (!$isLocal && !$tokenOk) {
    http_response_code(403);
    header('Content-Type: text/plain; charset=UTF-8');
    echo "Forbidden. H11.0-P4 QA is local-only unless DDB_QA_TOKEN is configured.\n";
    exit;
}

$currentYear = (int)date('Y');
$year = filter_var($_GET['year'] ?? null, FILTER_VALIDATE_INT);
$year = $year !== false && $year !== null ? (int)$year : $currentYear - 1;
$fromDate = (string)($_GET['from_date'] ?? sprintf('%04d-01-01', $year));
$toDate = (string)($_GET['to_date'] ?? sprintf('%04d-03-31', $year));

$checks = [];
$add = static function (string $name, bool $ok, string $detail = '') use (&$checks): void {
    $checks[] = ['name' => $name, 'status' => $ok ? 'PASS' : 'FAIL', 'detail' => $detail];
};

$version = [];
if (is_file($root . '/DDB_VERSION.json')) {
    $decoded = json_decode((string)file_get_contents($root . '/DDB_VERSION.json'), true);
    $version = is_array($decoded) ? $decoded : [];
}

$currentSource = is_file($root . '/app/Services/MultiBranchPatientActivityService.php')
    ? (string)file_get_contents($root . '/app/Services/MultiBranchPatientActivityService.php') : '';
$legacySource = is_file($root . '/app/Repositories/LegacyMultiBranchPatientActivityRepository.php')
    ? (string)file_get_contents($root . '/app/Repositories/LegacyMultiBranchPatientActivityRepository.php') : '';
$paritySource = is_file($root . '/app/Services/MultiBranchOutpatientParityService.php')
    ? (string)file_get_contents($root . '/app/Services/MultiBranchOutpatientParityService.php') : '';
$controllerSource = is_file($root . '/app/Controllers/OperationsController.php')
    ? (string)file_get_contents($root . '/app/Controllers/OperationsController.php') : '';
$viewSource = is_file($root . '/app/Views/operations/module.php')
    ? (string)file_get_contents($root . '/app/Views/operations/module.php') : '';
$i18nSource = is_file($root . '/config/i18n.php')
    ? (string)file_get_contents($root . '/config/i18n.php') : '';

$installedRelease = (string)($version['release'] ?? '');
$add('target_release_compatible',
    $installedRelease !== '' && version_compare($installedRelease, '11.0.4', '>='),
    $installedRelease);

$add('full_historical_gmov_contract',
    stripos($legacySource, 'rcp_visit') !== false
    && stripos($legacySource, 'rcp_service_reservation') !== false
    && stripos($legacySource, 'v.classcode = 2') !== false
    && stripos($legacySource, "r.servstatus NOT IN ('C', 'F')") !== false
    && stripos($legacySource, 'r.sched_serial IS NOT NULL') !== false
    && stripos($legacySource, 'activity.month_no (+) = months.code') !== false,
    'Exact recovered gmov query contract');

$add('three_branch_execution_contract',
    strpos($legacySource, "['njch', 'jckh', 'mnh']") !== false
    && strpos($currentSource, "['njch', 'jckh', 'mnh']") !== false,
    'NJCH + JCKH + MNH');

$add('no_emergency_exclusion_in_gmov',
    stripos($legacySource, 'outpta_emergency_type') === false
    && stripos($legacySource, 'clinic_id') === false
    && stripos($currentSource, 'outpta_emergency_type') === false
    && stripos($currentSource, 'clinic_id') === false,
    'Historical gmov does not exclude ER');

$add('independent_current_and_legacy_paths',
    strpos($currentSource, 'new LegacyMultiBranchPatientActivityRepository(') === false
    && strpos($legacySource, 'new MultiBranchPatientActivityService(') === false
    && strpos($paritySource, 'new MultiBranchPatientActivityService()') !== false
    && strpos($paritySource, 'new LegacyMultiBranchPatientActivityRepository()') !== false,
    'Independent execution paths');

$add('real_visits_workspace_integration',
    strpos($controllerSource, 'MultiBranchPatientActivityService') !== false
    && strpos($viewSource, 'data-legacy-function="gmov"') !== false,
    'Visits workspace');

$add('bilingual_business_wording',
    strpos($i18nSource, "'visits.multi_branch_title' => 'Outpatient visits across branches'") !== false
    && strpos($i18nSource, "'visits.multi_branch_title' => 'زيارات العيادات الخارجية حسب الفرع'") !== false,
    'EN + AR');

$writeText = strtolower($currentSource . "\n" . $legacySource . "\n" . $paritySource);
$hasWrite = preg_match('/\b(insert\s+into|update\s+[a-z0-9_]+\s+set|delete\s+from|create\s+table|alter\s+table)\b/i', $writeText) === 1;
$add('oracle_write_operations_none', !$hasWrite, 'SELECT only');

$resolverSource = is_file($root . '/app/Services/BranchOracleAccessResolver.php')
    ? (string)file_get_contents($root . '/app/Services/BranchOracleAccessResolver.php') : '';
$databaseSource = is_file($root . '/app/Core/Database.php')
    ? (string)file_get_contents($root . '/app/Core/Database.php') : '';

$add('root_branch_resolver_present',
    strpos($resolverSource, 'DISCOVER_VALIDATE_CACHE_NO_GUESSING') !== false,
    'Shared branch Oracle resolver');

$add('configured_service_sid_recovery_present',
    strpos($resolverSource, 'CONFIGURED_SERVICE_AS_SID_RECOVERY') !== false,
    'SERVICE_NAME to SID recovery');

$add('dynamic_db_link_catalog_discovery_present',
    strpos($resolverSource, 'user_db_links') !== false
    && strpos($resolverSource, 'all_db_links') !== false,
    'Oracle catalog discovery');

$add('tns_and_legacy_config_discovery_present',
    strpos($resolverSource, 'discoverTnsCandidates') !== false
    && strpos($resolverSource, 'discoverLegacyConfigCandidates') !== false,
    'TNS + legacy local configuration');

$add('dynamic_database_read_only_transport_present',
    strpos($databaseSource, 'fetchAllUsingDatabaseConfig') !== false,
    'Central Database read-only dynamic connection');

$parity = null;
$liveError = '';
$connectivityDiagnostics = [];
$parityService = new MultiBranchOutpatientParityService();

if ($runLive) {
    try {
        $parity = $parityService->run($year, $fromDate, $toDate);
        $connectivityDiagnostics = $parityService->connectivityDiagnostics();
        $yearResult = $parity['modes']['year']['function'] ?? [];
        $rangeResult = $parity['modes']['date_range']['function'] ?? [];

        $add('live_year_mode_exact_parity',
            ($yearResult['status'] ?? '') === 'PASS'
            && (int)($yearResult['value_checks'] ?? 0) === 36
            && (float)($yearResult['max_difference'] ?? -1) === 0.0,
            'checks=' . (string)($yearResult['value_checks'] ?? 0)
            . '; max_difference=' . (string)($yearResult['max_difference'] ?? 'missing'));

        $add('live_date_range_exact_parity',
            ($rangeResult['status'] ?? '') === 'PASS'
            && (int)($rangeResult['value_checks'] ?? 0) === 36
            && (float)($rangeResult['max_difference'] ?? -1) === 0.0,
            'checks=' . (string)($rangeResult['value_checks'] ?? 0)
            . '; max_difference=' . (string)($rangeResult['max_difference'] ?? 'missing'));

        $add('live_two_of_two',
            (int)($parity['functions_checked'] ?? 0) === 2
            && (int)($parity['failures'] ?? 1) === 0,
            (string)($parity['functions_checked'] ?? 0) . '/2');

        $currentAccess = $parity['current_access_paths'] ?? [];
        $legacyAccess = $parity['legacy_access_paths'] ?? [];

        $add('all_three_current_branch_paths_resolved',
            isset($currentAccess['njch'], $currentAccess['jckh'], $currentAccess['mnh']),
            json_encode($currentAccess, JSON_UNESCAPED_SLASHES));

        $add('all_three_legacy_branch_paths_resolved',
            isset($legacyAccess['njch'], $legacyAccess['jckh'], $legacyAccess['mnh']),
            json_encode($legacyAccess, JSON_UNESCAPED_SLASHES));

        $add('full_historical_source_boundary',
            ($parity['source_evidence_boundary'] ?? '') === 'FULL_HISTORICAL_FUNCTION_BODY_RECOVERED',
            (string)($parity['source_evidence_boundary'] ?? 'missing'));

        $add('live_read_only',
            ($parity['write_operations'] ?? '') === 'NONE',
            (string)($parity['write_operations'] ?? 'unknown'));
    } catch (Throwable $e) {
        $liveError = $e->getMessage();
        $connectivityDiagnostics = $parityService->connectivityDiagnostics();
        $add('live_year_mode_exact_parity', false, 'Execution error');
        $add('live_date_range_exact_parity', false, 'Execution error');
        $add('live_two_of_two', false, '0/2');
        $add('all_three_current_branch_paths_resolved', false, 'Unavailable because live execution failed');
        $add('all_three_legacy_branch_paths_resolved', false, 'Unavailable because live execution failed');
        $add('full_historical_source_boundary', true, 'FULL_HISTORICAL_FUNCTION_BODY_RECOVERED');
        $add('live_read_only', true, 'NONE');
    }
}

$failures = count(array_filter($checks, static function (array $check): bool {
    return $check['status'] === 'FAIL';
}));

$result = [
    'schema_version' => '1.0',
    'phase' => 'H11.0-P4',
    'title' => 'Multi-Branch Outpatient Visits Legacy Recovery',
    'year' => $year,
    'range_from' => $fromDate,
    'range_to' => $toDate,
    'run_live' => $runLive,
    'source_evidence_boundary' => 'FULL_HISTORICAL_FUNCTION_BODY_RECOVERED',
    'write_operations' => 'NONE',
    'checks' => $checks,
    'parity' => $parity,
    'connectivity_diagnostics' => $connectivityDiagnostics,
    'live_error' => $liveError,
    'pass_gates' => count($checks) - $failures,
    'fail_gates' => $failures,
    'status' => $failures === 0 ? 'PASS' : 'FAIL',
];

if ($format === 'json') {
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

header('Content-Type: text/plain; charset=UTF-8');
echo "Multi-Branch Outpatient Visits Legacy Recovery QA\n";
echo "Phase: H11.0-P4\n";
echo "Write operations: NONE\n\n";

foreach ($checks as $check) {
    echo '[' . $check['status'] . '] ' . str_pad($check['name'], 48) . ' | ' . $check['detail'] . "\n";
}

if ($liveError !== '') {
    echo "\nLive execution error: " . $liveError . "\n";
}

echo "\nQA result: " . $result['status'] . "\n";
