<?php

namespace App\SiteReadiness;

class ReadinessReport
{
    /** @param ReadinessCheck[] $coreChecks */
    public function __construct(private array $coreChecks)
    {
    }

    public function run(): array
    {
        try {
            $checks = \HooksAdapter::apply_filters('site_readiness_checks', $this->coreChecks);
            if (!is_array($checks)) {
                $checks = $this->coreChecks;
            }
        } catch (\Throwable) {
            $checks = $this->coreChecks;
        }

        $groups = [];
        $summary = ['ok' => 0, 'warn' => 0, 'fail' => 0];

        foreach ($checks as $check) {
            if (!$check instanceof ReadinessCheck) {
                continue;
            }

            try {
                $group  = $check->group();
                $label  = $check->label();
                $result = $check->run();
                $hint   = $check->hint();
            } catch (\Throwable $e) {
                $groups['Errors'][] = [
                    'label'  => get_class($check),
                    'status' => Status::FAIL,
                    'detail' => 'Check threw: ' . $e->getMessage(),
                    'hint'   => 'This check errored; investigate the check class.',
                ];
                $summary['fail']++;
                continue;
            }

            $groups[$group][] = [
                'label'  => $label,
                'status' => $result->status,
                'detail' => $result->detail,
                'hint'   => $hint,
            ];

            if ($result->status === Status::OK)   { $summary['ok']++; }
            if ($result->status === Status::WARN) { $summary['warn']++; }
            if ($result->status === Status::FAIL) { $summary['fail']++; }
        }

        return ['groups' => $groups, 'summary' => $summary];
    }
}
