<?php
declare(strict_types=1);

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

use App\Services\SpecialtyFinanceActivityParityService;

$root = dirname(__DIR__);
$version = json_decode((string)file_get_contents($root . '/DDB_VERSION.json'), true);
$serviceSource = (string)file_get_contents(
    $root . '/app/Services/SpecialtyFinanceActivityParityService.php'
);
$repo = (string)file_get_contents(
    $root . '/app/Repositories/SpecialtyFinanceRepository.php'
);
$view = (string)file_get_contents(
    $root . '/app/Views/specialty_finance/index.php'
);
$env = (string)file_get_contents($root . '/.env');

$service = new SpecialtyFinanceActivityParityService('njch');
$reflection = new ReflectionClass($service);

$periodMethod = $reflection->getMethod('periodMap');
$periodMethod->setAccessible(true);
$monthlyMethod = $reflection->getMethod('monthlyMap');
$monthlyMethod->setAccessible(true);
$zeroPeriodMethod = $reflection->getMethod('zeroOnlyPeriodIdentities');
$zeroPeriodMethod->setAccessible(true);
$zeroMonthlyMethod = $reflection->getMethod('zeroOnlyMonthlyIdentities');
$zeroMonthlyMethod->setAccessible(true);

$samplePeriod = [
    [
        'id' => '101',
        'label' => 'Current only',
        'current_outpatient_visits' => 14,
        'current_admissions' => 2,
        'compare_outpatient_visits' => 0,
        'compare_admissions' => 0,
    ],
    [
        'id' => '103',
        'label' => 'Compare only',
        'current_outpatient_visits' => 0,
        'current_admissions' => 0,
        'compare_outpatient_visits' => 8,
        'compare_admissions' => 1,
    ],
];

$sampleMonthly = [
    [
        'id' => '103',
        'label' => 'Compare only',
        'month_id' => 1,
        'current_outpatient_visits' => 0,
        'current_admissions' => 0,
        'compare_outpatient_visits' => 4,
        'compare_admissions' => 1,
    ],
    [
        'id' => '99',
        'label' => 'Current only',
        'month_id' => 4,
        'current_outpatient_visits' => 7,
        'current_admissions' => 1,
        'compare_outpatient_visits' => 0,
        'compare_admissions' => 0,
    ],
];

$currentPeriod = $periodMethod->invoke($service, $samplePeriod, 'current');
$comparePeriod = $periodMethod->invoke($service, $samplePeriod, 'compare');
$currentMonthly = $monthlyMethod->invoke($service, $sampleMonthly, 'current');
$compareMonthly = $monthlyMethod->invoke($service, $sampleMonthly, 'compare');
$zeroComparePeriod = $zeroPeriodMethod->invoke($service, $samplePeriod, 'compare');
$zeroCurrentMonthly = $zeroMonthlyMethod->invoke($service, $sampleMonthly, 'current');

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.12.1',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P12.0.1',
    'period_zero_side_filtered' => array_keys($currentPeriod) === [101]
        && array_keys($comparePeriod) === [103],
    'monthly_zero_side_filtered' => array_keys($currentMonthly) === ['99|4']
        && array_keys($compareMonthly) === ['103|1'],
    'zero_period_diagnostics' => $zeroComparePeriod === ['101'],
    'zero_monthly_diagnostics' => $zeroCurrentMonthly === ['103|1'],
    'actual_values_preserved' => (float)$currentPeriod[101]['outpatient_visits'] === 14.0
        && (float)$comparePeriod[103]['admissions'] === 1.0,
    'normalization_rule_in_result' => strpos(
        $serviceSource,
        "'normalization' =>"
    ) !== false,
    'zero_only_check_present' => strpos(
        $serviceSource,
        "'zero_only_side_rows_normalized'"
    ) !== false,
    'combined_query_preserved' => strpos(
        $repo,
        'WHERE ABS(current_outpatient_visits)'
    ) !== false,
    'repository_unchanged_by_hotfix' => (
        $version['r45_p12_0_1']['repository_query_changed'] ?? true
    ) === false,
    'specialty_finance_view_unchanged' => hash('sha256', $view) === 'ba42e9ac6a5ce61d6384d439674d16adcd3f3a898f0cb884ee39af1d690ded86',
    'php7_match_absent' => preg_match(
        '/\bmatch\s*\(/',
        $serviceSource
    ) !== 1,
    'php7_nullsafe_absent' => strpos($serviceSource, '?->') === false,
    'revenue_summary_enabled' => preg_match(
        '/^USE_REVENUE_SUMMARY=1$/m',
        $env
    ) === 1,
    'revenue_summary_age_30' => preg_match(
        '/^REVENUE_SUMMARY_MAX_AGE_HOURS=30$/m',
        $env
    ) === 1,
    'oracle_writes_none' => (
        $version['r45_p12_0_1']['oracle_writes'] ?? ''
    ) === 'NONE',
];

$failed = [];
foreach ($checks as $name => $passed) {
    if (!$passed) {
        $failed[] = $name;
    }
}

echo json_encode([
    'schema' => 'R45_P12_0_1_STATIC_QA',
    'checks' => $checks,
    'passed' => count($checks) - count($failed),
    'failed' => $failed,
    'oracle_writes' => 'NONE',
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;

exit($failed === [] ? 0 : 1);
