<?php

declare(strict_types=1);

namespace App\Services;

use App\Repositories\DiagnosticsRepository;
use App\Repositories\LegacyDiagnosticsRepository;

final class LegacyBatchBReadyScopeParityService
{
    /** @var array<int, string> */
    private const FUNCTIONS = ['plts', 'prts'];

    /**
     * Exact READY-scope proof for the final two historical three-branch
     * composite monthly diagnostic functions.
     *
     * JCKH remains DEFERRED_NOT_READY. Therefore both functions remain
     * PARTIAL_DEFERRED_BRANCH even after zero-difference proof on NJCH + MNH.
     *
     * @return array<string, mixed>
     */
    public function run(
        int $year,
        int $compareYear,
        string $fromDate,
        string $toDate
    ): array {
        $branches = BranchReadinessPolicy::blockingQaBranches();
        $deferredBranches = BranchReadinessPolicy::deferredBranches();
        $modes = ['year', 'range'];

        $datasets = [];
        $details = [];
        $functionResults = [];
        $maxDifference = 0.0;
        $failedDatasets = 0;
        $identityMismatches = 0;

        foreach (self::FUNCTIONS as $functionKey) {
            $functionDatasetCount = 0;
            $functionValueChecks = 0;
            $functionFailures = 0;
            $functionMaxDifference = 0.0;

            foreach ($branches as $branch) {
                foreach ($modes as $mode) {
                    $rangeFrom = $mode === 'range' ? $fromDate : null;
                    $rangeTo = $mode === 'range' ? $toDate : null;

                    $pair = $this->executeFunction(
                        $functionKey,
                        $branch,
                        $year,
                        $compareYear,
                        $rangeFrom,
                        $rangeTo
                    );

                    $comparison = $this->compareMonthlyDataset(
                        $functionKey,
                        $branch,
                        $mode,
                        $pair['legacy'],
                        $pair['current']
                    );

                    $datasets[] = $comparison;
                    $functionDatasetCount++;
                    $functionValueChecks += (int)$comparison['value_checks'];
                    $functionMaxDifference = max(
                        $functionMaxDifference,
                        (float)$comparison['max_difference']
                    );
                    $maxDifference = max(
                        $maxDifference,
                        (float)$comparison['max_difference']
                    );
                    $identityMismatches += (int)$comparison['identity_mismatches'];

                    if (($comparison['status'] ?? 'FAIL') !== 'PASS') {
                        $failedDatasets++;
                        $functionFailures++;
                    }

                    foreach ((array)$comparison['details'] as $detail) {
                        $details[] = $detail;
                    }
                }
            }

            $functionResults[$functionKey] = [
                'status' => (
                    $functionDatasetCount === 4
                    && $functionFailures === 0
                    && $functionValueChecks === 96
                    && $functionMaxDifference === 0.0
                ) ? 'PASS' : 'FAIL',
                'datasets' => $functionDatasetCount,
                'value_checks' => $functionValueChecks,
                'failures' => $functionFailures,
                'max_difference' => $functionMaxDifference,
                'promotion_status' => 'PARTIAL_DEFERRED_BRANCH',
                'matched_promotion' => false,
            ];
        }

        $valueChecks = count($details);
        $status = (
            count($branches) === 2
            && count(self::FUNCTIONS) === 2
            && count($datasets) === 8
            && $valueChecks === 192
            && $failedDatasets === 0
            && $identityMismatches === 0
            && $maxDifference === 0.0
            && $this->allFunctionsPass($functionResults)
        ) ? 'PASS' : 'FAIL';

        return [
            'schema_version' => '1.0',
            'phase' => 'H11.0-P9',
            'batch' => 'Legacy Batch B',
            'functions' => self::FUNCTIONS,
            'function_count' => count(self::FUNCTIONS),
            'historical_contracts' => $this->historicalContracts(),
            'source_evidence_boundary' => 'FULL_HISTORICAL_FUNCTION_BODIES_RECOVERED',
            'branch_readiness_policy' => 'READY_BRANCHES_ONLY_JCKH_DEFERRED',
            'active_qa_branches' => $branches,
            'deferred_branches' => $deferredBranches,
            'database_update_branches' => BranchReadinessPolicy::databaseUpdateBranches(),
            'modes' => $modes,
            'modes_checked' => count($modes),
            'dataset_checks' => count($datasets),
            'value_checks' => $valueChecks,
            'identity_mismatches' => $identityMismatches,
            'failed_datasets' => $failedDatasets,
            'max_difference' => $maxDifference,
            'function_results' => $functionResults,
            'datasets' => $datasets,
            'details' => $details,
            'write_operations' => 'NONE',
            'matched_promotions' => 0,
            'ready_scope_contracts_proven' => $status === 'PASS' ? 2 : 0,
            'promotion_policy' => 'NO_MATCHED_PROMOTION_WHILE_JCKH_DEFERRED_FOR_INHERENT_THREE_BRANCH_COMPOSITES',
            'legacy_promotion_status' => $status === 'PASS'
                ? 'TWO_FUNCTIONS_READY_SCOPE_PROVEN_PARTIAL_DEFERRED_BRANCH'
                : 'NOT_PROVEN',
            'partial_ready_scope_proven_after_pass' => [
                'count' => $status === 'PASS' ? 6 : 4,
                'of_partial_functions' => 6,
                'functions' => $status === 'PASS'
                    ? ['gmov', 'padm', 'perv', 'popr', 'plts', 'prts']
                    : ['gmov', 'padm', 'perv', 'popr'],
            ],
            'remaining_partial_ready_scope_unproven_after_pass' => $status === 'PASS'
                ? []
                : ['plts', 'prts'],
            'baseline_before' => [
                'known' => 31,
                'matched' => 23,
                'partial' => 6,
                'missing' => 2,
                'matched_pct' => 74.2,
            ],
            'baseline_after_live_pass' => [
                'known' => 31,
                'matched' => 23,
                'partial' => 6,
                'missing' => 2,
                'matched_pct' => 74.2,
            ],
            'status' => $status,
        ];
    }

    /**
     * @return array{legacy: array<int, array<string, mixed>>, current: array<int, array<string, mixed>>}
     */
    private function executeFunction(
        string $functionKey,
        string $branch,
        int $year,
        int $compareYear,
        ?string $fromDate,
        ?string $toDate
    ): array {
        $legacy = new LegacyDiagnosticsRepository($branch);
        $current = new DiagnosticsRepository($branch);

        if ($functionKey === 'plts') {
            return [
                'legacy' => $legacy->monthlyLabTests(
                    $year,
                    $compareYear,
                    $fromDate,
                    $toDate
                ),
                'current' => $current->monthlyLabTests(
                    $year,
                    $compareYear,
                    $fromDate,
                    $toDate
                ),
            ];
        }

        if ($functionKey === 'prts') {
            return [
                'legacy' => $legacy->monthlyRadiologyTests(
                    $year,
                    $compareYear,
                    $fromDate,
                    $toDate
                ),
                'current' => $current->monthlyRadiologyTests(
                    $year,
                    $compareYear,
                    $fromDate,
                    $toDate
                ),
            ];
        }

        throw new \InvalidArgumentException('Unknown H11.0-P9 function: ' . $functionKey);
    }

    /**
     * @param array<int, array<string, mixed>> $legacyRows
     * @param array<int, array<string, mixed>> $currentRows
     * @return array<string, mixed>
     */
    private function compareMonthlyDataset(
        string $functionKey,
        string $branch,
        string $mode,
        array $legacyRows,
        array $currentRows
    ): array {
        $legacyMap = $this->monthMap($legacyRows);
        $currentMap = $this->monthMap($currentRows);
        $details = [];
        $maxDifference = 0.0;
        $identityMismatches = 0;
        $failures = 0;

        for ($month = 1; $month <= 12; $month++) {
            $legacyExists = array_key_exists($month, $legacyMap);
            $currentExists = array_key_exists($month, $currentMap);

            if (!$legacyExists || !$currentExists) {
                $identityMismatches++;
            }

            foreach (['current_value', 'compare_value'] as $series) {
                $legacyValue = $legacyExists
                    ? (float)($legacyMap[$month][$series] ?? 0)
                    : 0.0;
                $currentValue = $currentExists
                    ? (float)($currentMap[$month][$series] ?? 0)
                    : 0.0;
                $difference = abs($legacyValue - $currentValue);
                $rowPass = $legacyExists && $currentExists && $difference === 0.0;

                if (!$rowPass) {
                    $failures++;
                }

                $maxDifference = max($maxDifference, $difference);
                $details[] = [
                    'function' => $functionKey,
                    'branch' => $branch,
                    'mode' => $mode,
                    'month_id' => $month,
                    'month_name' => (string)(
                        $currentMap[$month]['month_name']
                        ?? $legacyMap[$month]['month_name']
                        ?? ''
                    ),
                    'series' => $series,
                    'legacy_exists' => $legacyExists,
                    'current_exists' => $currentExists,
                    'legacy_value' => $legacyValue,
                    'current_value' => $currentValue,
                    'difference' => $difference,
                    'status' => $rowPass ? 'PASS' : 'FAIL',
                ];
            }
        }

        return [
            'function' => $functionKey,
            'branch' => $branch,
            'mode' => $mode,
            'legacy_rows' => count($legacyRows),
            'current_rows' => count($currentRows),
            'value_checks' => count($details),
            'identity_mismatches' => $identityMismatches,
            'failures' => $failures,
            'max_difference' => $maxDifference,
            'details' => $details,
            'status' => (
                count($legacyRows) === 12
                && count($currentRows) === 12
                && count($details) === 24
                && $identityMismatches === 0
                && $failures === 0
                && $maxDifference === 0.0
            ) ? 'PASS' : 'FAIL',
        ];
    }

    /**
     * @param array<int, array<string, mixed>> $rows
     * @return array<int, array<string, mixed>>
     */
    private function monthMap(array $rows): array
    {
        $map = [];

        foreach ($rows as $row) {
            $month = (int)($row['month_id'] ?? 0);

            if ($month >= 1 && $month <= 12) {
                $map[$month] = $row;
            }
        }

        return $map;
    }

    /** @param array<string, array<string, mixed>> $results */
    private function allFunctionsPass(array $results): bool
    {
        foreach (self::FUNCTIONS as $functionKey) {
            if (($results[$functionKey]['status'] ?? 'FAIL') !== 'PASS') {
                return false;
            }
        }

        return true;
    }

    /** @return array<string, array<string, mixed>> */
    private function historicalContracts(): array
    {
        return [
            'plts' => [
                'legacy_function' => 'get_lab_tests',
                'sources' => ['RCP_LAB_SERVICE_RESERVATION', 'SEC_LOOKUP_DETAIL'],
                'date_field' => 'RCP_LAB_SERVICE_RESERVATION.EXPECTEDDONEDATE',
                'rules' => [
                    'EXPECTEDDONEDATE <= SYSDATE',
                    'year mode uses EXTRACT(YEAR FROM EXPECTEDDONEDATE)',
                    'range mode uses inclusive from/to bounds',
                    'monthly grouping by EXPECTEDDONEDATE month number',
                ],
            ],
            'prts' => [
                'legacy_function' => 'get_rad_tests',
                'sources' => ['RCP_RAD_SERVICE_RESERVATION', 'SEC_LOOKUP_DETAIL'],
                'date_field' => 'RCP_RAD_SERVICE_RESERVATION.MACHINE_SCH_FROM',
                'rules' => [
                    'MACHINE_SCH_FROM <= SYSDATE',
                    'year mode uses EXTRACT(YEAR FROM MACHINE_SCH_FROM)',
                    'range mode uses inclusive from/to bounds',
                    'monthly grouping by MACHINE_SCH_FROM month number',
                ],
            ],
        ];
    }
}
