<?php

declare(strict_types=1);

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

use App\Services\BranchReadinessPolicy;
use App\Services\SpecialtyNetRevenueAliasParityService;

$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')
    : '';

$serviceSource = is_file($root . '/app/Services/SpecialtyNetRevenueAliasParityService.php')
    ? (string)file_get_contents($root . '/app/Services/SpecialtyNetRevenueAliasParityService.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')
    : '';

$contractSource = is_file($root . '/docs/legacy/H11_0_P7_SPECIALTY_NET_REVENUE_ALIAS_CONTRACT.md')
    ? (string)file_get_contents($root . '/docs/legacy/H11_0_P7_SPECIALTY_NET_REVENUE_ALIAS_CONTRACT.md')
    : '';

$combined = strtolower(
    $currentSource . "\n"
    . $legacySource . "\n"
    . $serviceSource . "\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|merge\s+into)\b/i',
    $combined
) === 1;

$release = (string)($version['release'] ?? '');

$add(
    'target_release_11_0_7',
    $release === '11.0.7',
    $release
);

$add(
    'dispatcher_alias_mapping_recovered',
    strpos($contractSource, '`special_net_rev`') !== false
    && strpos($contractSource, '`net_rev`') !== false
    && strpos($contractSource, '`get_net_rev`') !== false,
    'special_net_rev + net_rev -> get_net_rev'
);

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

$add(
    'independent_legacy_exact_method_present',
    strpos($legacySource, 'function specialtyNetRevenueRanking') !== 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_net_preserved',
    stripos($legacySource, 'SUM(DISTINCT net_rev_after_drug_moh)') !== false,
    'SUM(DISTINCT NET_REV_AFTER_DRUG_MOH)'
);

$add(
    'historical_specialty_grouping_preserved',
    stripos($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_threshold_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_net_chart_uses_exact_contract',
    strpos($controllerSource, '$repo->specialtyNetRevenueRanking($year)') !== false
    && strpos($viewSource, 'data-legacy-aliases="special_net_rev net_rev"') !== false,
    'Real Specialty Finance page'
);

$add(
    'no_new_page_specific_css_or_js',
    !is_file($root . '/public/assets/css/specialty-net-revenue-p7.css')
    && !is_file($root . '/public/assets/js/specialty-net-revenue-p7.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 SpecialtyNetRevenueAliasParityService())->run(
        (int)$year,
        (int)$compareYear
    );

    $add(
        'live_aliases_2_of_2',
        (int)($parity['aliases_checked'] ?? 0) === 2,
        (string)($parity['aliases_checked'] ?? 0) . '/2'
    );

    $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_alias_contract_checks_8_of_8',
        (int)($parity['alias_contract_checks'] ?? 0) === 8
        && (int)($parity['alias_contract_failures'] ?? 1) === 0,
        'checks=' . (string)($parity['alias_contract_checks'] ?? 0)
        . '; failures=' . (string)($parity['alias_contract_failures'] ?? 0)
    );

    $add(
        'live_value_checks_present',
        (int)($parity['value_checks'] ?? 0) > 0,
        (string)($parity['value_checks'] ?? 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_source_and_alias_boundary',
        ($parity['source_evidence_boundary'] ?? '')
        === 'FULL_HISTORICAL_FUNCTION_BODY_AND_DISPATCHER_ALIAS_MAPPING_RECOVERED',
        (string)($parity['source_evidence_boundary'] ?? 'missing')
    );

    $add(
        'live_two_matched_promotions',
        (int)($parity['matched_promotions'] ?? 0) === 2,
        (string)($parity['matched_promotions'] ?? 0)
    );

    $add(
        'live_legacy_progress_23_matched_6_partial',
        (int)($parity['baseline_after_live_pass']['matched'] ?? 0) === 23
        && (int)($parity['baseline_after_live_pass']['partial'] ?? 0) === 6,
        '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_aliases_2_of_2', false, 'Execution error');
    $add('live_dataset_checks_4_of_4', false, 'Execution error');
    $add('live_alias_contract_checks_8_of_8', false, 'Execution error');
    $add('live_value_checks_present', false, 'Execution error');
    $add('live_identity_mismatches_zero', false, 'Execution error');
    $add('live_max_difference_zero', false, 'Execution error');
    $add(
        'live_full_source_and_alias_boundary',
        true,
        'FULL_HISTORICAL_FUNCTION_BODY_AND_DISPATCHER_ALIAS_MAPPING_RECOVERED'
    );
    $add('live_two_matched_promotions', false, 'not proven');
    $add('live_legacy_progress_23_matched_6_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-P7',
    'title' => 'Specialty Net Revenue Dispatcher Alias Contract Correction',
    'legacy_aliases' => ['special_net_rev', 'net_rev'],
    'legacy_function' => 'get_net_rev',
    'year' => (int)$year,
    'compare_year' => (int)$compareYear,
    'source_evidence_boundary' => 'FULL_HISTORICAL_FUNCTION_BODY_AND_DISPATCHER_ALIAS_MAPPING_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
);
