<?php

declare(strict_types=1);

namespace App\Services;

use App\Repositories\LegacySpecialtyFinanceRepository;
use App\Repositories\SpecialtyFinanceRepository;

final class SpecialtyFinanceParityService
{
    /** @var string */
    private $hospitalCode;

    /** @var LegacySpecialtyFinanceRepository */
    private $legacy;

    /** @var SpecialtyFinanceRepository */
    private $current;

    public function __construct(string $hospitalCode)
    {
        $this->hospitalCode = strtolower($hospitalCode);
        $this->legacy = new LegacySpecialtyFinanceRepository($this->hospitalCode);
        $this->current = new SpecialtyFinanceRepository($this->hospitalCode);
    }

    /** @return array<string, mixed> */
    public function run(int $year, int $compareYear): array
    {
        $periods = [
            'current_year' => $year,
            'compare_year' => $compareYear,
        ];

        $modes = [];
        $all = [];
        foreach ($periods as $mode => $periodYear) {
            $functions = [
                $this->compareScalar(
                    'moh_revn',
                    'get_moh_revn',
                    $periodYear,
                    $this->legacy->mohRevenue($periodYear),
                    $this->current->annualMetricTotal($periodYear, 'MOH')
                ),
                $this->compareScalar(
                    'drug_rev',
                    'get_drug_rev',
                    $periodYear,
                    $this->legacy->drugRevenue($periodYear),
                    $this->current->annualMetricTotal($periodYear, 'DRUG_REV')
                ),
            ];
            $modes[$mode] = ['year' => $periodYear, 'functions' => $functions];
            foreach ($functions as $row) {
                $all[] = $row;
            }
        }

        $failures = count(array_filter($all, static function (array $row): bool {
            return ($row['status'] ?? 'FAIL') !== 'PASS';
        }));
        $maxDifference = 0.0;
        foreach ($all as $row) {
            $maxDifference = max($maxDifference, (float)($row['max_difference'] ?? 0));
        }

        return [
            'schema_version' => '1.0',
            'phase' => '10.15',
            'hospital' => strtoupper($this->hospitalCode),
            'year' => $year,
            'compare_year' => $compareYear,
            'write_operations' => 'NONE',
            'source_contract' => [
                'moh_revn' => 'Dispatcher confirmed as get_moh_revn; reconstructed annual selected-branch contract on KPI_DOCTOR_PERF_DETAIL_JOB.MOH.',
                'drug_rev' => 'Dispatcher confirmed as get_drug_rev; reconstructed annual selected-branch contract on KPI_DOCTOR_PERF_DETAIL_JOB.DRUG_REV.',
                'aggregation_note' => 'Doctor-level values are deduplicated per doctor before final aggregation, preserving the established doctor KPI contract validated in Phase 10.13.',
                'source_evidence_boundary' => 'The full historical bodies of get_moh_revn and get_drug_rev remain unavailable. Phase 10.15 therefore validates independent reconstructed SQL parity for those two functions only.',
                'source_recovery_update' => 'The full get_net_rev historical body is recovered in H11.0-P7. Both special_net_rev and net_rev dispatcher aliases map to that same ranked specialty contract and are validated by SpecialtyNetRevenueAliasParityService.',
            ],
            'modes' => $modes,
            'checks' => $all,
            'functions_checked' => count($all),
            'max_difference' => $maxDifference,
            'failures' => $failures,
            'status' => $failures === 0 && count($all) === 4 && $maxDifference === 0.0 ? 'PASS' : 'FAIL',
        ];
    }

    /** @return array<string, mixed> */
    private function compareScalar(string $legacyKey, string $legacyFunction, int $year, float $legacyValue, float $newValue): array
    {
        $difference = abs($legacyValue - $newValue);
        return [
            'legacy_key' => $legacyKey,
            'legacy_function' => $legacyFunction,
            'comparison_type' => 'scalar_annual_total',
            'year' => $year,
            'legacy_value' => $legacyValue,
            'new_value' => $newValue,
            'difference' => $difference,
            'max_difference' => $difference,
            'status' => $difference === 0.0 ? 'PASS' : 'FAIL',
        ];
    }
}
