<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Rules\Repository\Validation;

use PpPhp\Core\Platform\Rules\Repository\RuleRepositoryEntry;
use PpPhp\Core\Platform\Rules\Repository\RuleRepositoryRuntime;

final class RuleRepositoryVerifier
{
    public function verify(string $basePath): array
    {
        $runtime = RuleRepositoryRuntime::resetInstance($basePath);
        $runtime->clear();

        $entryOne = $runtime->register(RuleRepositoryEntry::create(
            'loan_high_value',
            'loan_rules',
            'High Value Loan Rule',
            'rule',
            '1.0.0',
            ['owner' => 'risk']
        ));

        $entryTwo = $runtime->register(RuleRepositoryEntry::create(
            'loan_high_value',
            'loan_rules',
            'High Value Loan Rule v2',
            'rule',
            '2.0.0',
            ['owner' => 'risk']
        ));

        $entryThree = $runtime->register(RuleRepositoryEntry::create(
            'loan_decision_table',
            'loan_rules',
            'Loan Decision Table',
            'decisionTable',
            '1.0.0',
            ['owner' => 'credit']
        ));

        $latest = $runtime->registry()->latest('loan_high_value');
        $deactivated = $runtime->deactivate($entryOne->entryId());
        $runtime->save();

        $second = RuleRepositoryRuntime::resetInstance($basePath);
        $second->hydrate();

        $summary = $second->summary();
        $stats = $summary['statistics'];

        $checks = [
            'register' => $entryOne->entryId() !== '' && $entryTwo->entryId() !== '' && $entryThree->entryId() !== '',
            'latest' => $latest !== null && $latest->version() === '2.0.0',
            'deactivate' => $deactivated === true,
            'registry' => count($second->registry()->forRuleSet('loan_rules')) === 3,
            'statistics' => ($stats['entries'] ?? 0) === 3 && ($stats['active'] ?? 0) === 2 && ($stats['inactive'] ?? 0) === 1,
            'persistence' => $second->store()->exists(),
            'hydration' => count($summary['entries']) === 3,
        ];

        $issues = [];
        foreach ($checks as $check => $ok) {
            if (!$ok) {
                $issues[] = ['check' => $check, 'message' => 'Rule repository verification failed: ' . $check];
            }
        }

        return [
            'ok' => !in_array(false, $checks, true),
            'checks' => $checks,
            'issues' => $issues,
            'summary' => [
                'entries' => $stats['entries'] ?? 0,
                'active' => $stats['active'] ?? 0,
                'inactive' => $stats['inactive'] ?? 0,
                'ruleSets' => $stats['ruleSets'] ?? 0,
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ],
        ];
    }
}
