<?php

declare(strict_types=1);

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

use App\Services\BranchReadinessPolicy;
use App\Services\SpecialtyTotalRevenueParityService;

$root = dirname(__DIR__);
$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: application/json; charset=UTF-8');
    echo json_encode(['status' => 'FAIL', 'error' => 'Forbidden']);
    exit;
}

$year = filter_var($_GET['year'] ?? null, FILTER_VALIDATE_INT);
$compareYear = filter_var($_GET['compare_year'] ?? null, FILTER_VALIDATE_INT);

if ($year === false || $year === null) {
    $year = (int)date('Y') - 1;
}
if ($compareYear === false || $compareYear === null) {
    $compareYear = (int)$year - 1;
}

$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/Repositories/SpecialtyFinanceRepository.php')
    ? (string)file_get_contents($root . '/app/Repositories/SpecialtyFinanceRepository.php')
    : '';

$legacySource = is_file($root . '/app/Repositories/LegacySpecialtyFinanceRepository.php')
    ? (string)file_get_contents($root . '/app/Repositories/LegacySpecialtyFinanceRepository.php')
    : '';

$paritySource = is_file($root . '/app/Services/SpecialtyTotalRevenueParityService.php')
    ? (string)file_get_contents($root . '/app/Services/SpecialtyTotalRevenueParityService.php')
    : '';

$controllerSource = is_file($root . '/app/Controllers/SpecialtyFinanceController.php')
    ? (string)file_get_contents($root . '/app/Controllers/SpecialtyFinanceController.php')
    : '';

$viewSource = is_file($root . '/app/Views/specialty_finance/index.php')
    ? (string)file_get_contents($root . '/app/Views/specialty_finance/index.php')
    : '';

$languageSource = is_file($root . '/app/Executive/Language/ExecutiveLanguage.php')
    ? (string)file_get_contents($root . '/app/Executive/Language/ExecutiveLanguage.php')
    : '';

$combined = strtolower(
    $currentSource . "\n"
    . $legacySource . "\n"
    . $paritySource . "\n"
    . $controllerSource . "\n"
    . $viewSource
);

$writeDetected = preg_match(
    '/\b(insert\s+into|update\s+[a-z0-9_]+\s+set|delete\s+from|create\s+table|alter\s+table|drop\s+table)\b/i',
    $combined
) === 1;

$add(
    'target_release_11_0_6',
    (string)($version['release'] ?? '') === '11.0.6',
    (string)($version['release'] ?? '')
);

$add(
    'current_exact_method_present',
    strpos($currentSource, 'function specialtyTotalRevenueRanking') !== false,
    'SpecialtyFinanceRepository::specialtyTotalRevenueRanking'
);

$add(
    'independent_legacy_exact_method_present',
    strpos($legacySource, 'function specialtyTotalRevenueRanking') !== false
    && strpos($legacySource, 'new SpecialtyFinanceRepository') === false,
    'Independent LegacySpecialtyFinanceRepository path'
);

$add(
    'historical_table_preserved',
    strpos($legacySource, 'KPI_DOCTOR_PERF_DETAIL_JOB') !== false,
    'KPI_DOCTOR_PERF_DETAIL_JOB'
);

$add(
    'historical_sum_distinct_tot_rev_preserved',
    strpos($legacySource, 'SUM(DISTINCT TOT_REV)') !== false,
    'SUM(DISTINCT TOT_REV)'
);

$add(
    'historical_specialty_grouping_preserved',
    strpos($legacySource, 'GROUP BY SPECIAL_SPEC_ID, SPECIAL_SPEC_EN_NAME') !== false,
    'SPECIAL_SPEC_ID + SPECIAL_SPEC_EN_NAME'
);

$add(
    'historical_year_filter_preserved',
    strpos($legacySource, 'WHERE YEARID = :legacy_year') !== false,
    'YEARID = selected year'
);

$add(
    'historical_minimum_50000_preserved',
    strpos($legacySource, 'WHERE Month_Wise_Count > 50000') !== false,
    '> 50000'
);

$add(
    'historical_descending_order_preserved',
    strpos($legacySource, 'ORDER BY Month_Wise_Count DESC') !== false,
    'Descending metric order'
);

$add(
    'real_specialty_finance_page_integration',
    strpos($controllerSource, 'specialtyTotalRevenueRanking') !== false
    && strpos($viewSource, 'data-legacy-function="special_prof"') !== false,
    'Real Specialty Finance page'
);

$add(
    'shared_language_catalog_used_for_new_wording',
    strpos($languageSource, "'total_revenue' => 'Total Revenue'") !== false
    && strpos($languageSource, "'total_revenue' => 'إجمالي الإيراد'") !== false
    && strpos($viewSource, "exec_lang('total_revenue')") !== false,
    'Shared ExecutiveLanguage catalog'
);

$add(
    'no_new_page_specific_css_or_js',
    !is_file($root . '/public/assets/css/specialty-finance-p6.css')
    && !is_file($root . '/public/assets/js/specialty-finance-p6.js'),
    'Shared design/runtime only'
);

$add(
    'branch_readiness_policy_preserved',
    BranchReadinessPolicy::blockingQaBranches() === ['njch', 'mnh']
    && BranchReadinessPolicy::deferredBranches() === ['jckh'],
    'NJCH + MNH blocking; JCKH deferred'
);

$add(
    'oracle_write_operations_none',
    !$writeDetected,
    'SELECT only'
);

$parity = null;
$liveError = '';

try {
    $parity = (new SpecialtyTotalRevenueParityService())->run(
        (int)$year,
        (int)$compareYear
    );

    $add(
        'live_dataset_checks_4_of_4',
        (int)($parity['dataset_checks'] ?? 0) === 4
        && (int)($parity['failed_datasets'] ?? 1) === 0,
        'datasets=' . (string)($parity['dataset_checks'] ?? 0)
        . '; failed=' . (string)($parity['failed_datasets'] ?? 0)
    );

    $add(
        'live_identity_mismatches_zero',
        (int)($parity['identity_mismatches'] ?? 1) === 0,
        (string)($parity['identity_mismatches'] ?? 'missing')
    );

    $add(
        'live_max_difference_zero',
        (float)($parity['max_difference'] ?? -1) === 0.0,
        (string)($parity['max_difference'] ?? 'missing')
    );

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

    $add(
        'live_matched_promotion',
        ($parity['matched_promotion'] ?? false) === true,
        ($parity['matched_promotion'] ?? false) ? 'true' : 'false'
    );

    $add(
        'live_legacy_progress_21_matched_8_partial',
        (int)($parity['baseline_after_live_pass']['matched'] ?? 0) === 21
        && (int)($parity['baseline_after_live_pass']['partial'] ?? 0) === 8,
        'matched=' . (string)($parity['baseline_after_live_pass']['matched'] ?? 0)
        . '; partial=' . (string)($parity['baseline_after_live_pass']['partial'] ?? 0)
    );

    $add(
        'live_read_only',
        ($parity['write_operations'] ?? '') === 'NONE',
        (string)($parity['write_operations'] ?? 'unknown')
    );
} catch (Throwable $error) {
    $liveError = $error->getMessage();

    $add('live_dataset_checks_4_of_4', false, 'Execution error');
    $add('live_identity_mismatches_zero', false, 'Execution error');
    $add('live_max_difference_zero', false, 'Execution error');
    $add('live_full_historical_source_boundary', true, 'FULL_HISTORICAL_FUNCTION_BODY_RECOVERED');
    $add('live_matched_promotion', false, 'false');
    $add('live_legacy_progress_21_matched_8_partial', false, 'not proven');
    $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-P6',
    'title' => 'Specialty Total Revenue Legacy Recovery',
    'legacy_function' => 'special_prof',
    'legacy_function_name' => 'get_special_prof',
    'year' => (int)$year,
    'compare_year' => (int)$compareYear,
    'source_evidence_boundary' => 'FULL_HISTORICAL_FUNCTION_BODY_RECOVERED',
    'write_operations' => 'NONE',
    'checks' => $checks,
    'parity' => $parity,
    'live_error' => $liveError,
    'pass_gates' => count($checks) - $failures,
    'fail_gates' => $failures,
    'status' => $failures === 0 ? 'PASS' : 'FAIL',
];

header('Content-Type: application/json; charset=UTF-8');

echo json_encode(
    $result,
    JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);
