<?php
/**
 * Live Bricks design-system metrics for memory bootstrap and overview.
 *
 * @package LolaCoreForBricks
 */

declare(strict_types=1);

namespace LolaCoreForBricks\Support;

use LolaCoreForBricks\BricksEnv;
use LolaCoreForBricks\Governance\DeadCodeFinder;
use LolaCoreForBricks\Index\IndexReader;

/**
 * Collects query-live counts used by Door 7 and compliance reporting.
 */
final class BricksMemoryMetrics
{
    /**
     * @return array<string, mixed>|null
     */
    public function collect(): ?array
    {
        if (!BricksEnv::isAvailable() || !BricksEnv::meetsFloor()) {
            return null;
        }

        $classesTotal  = $this->countOptionItems(BricksMetaKeys::OPTION_GLOBAL_CLASSES);
        $variablesTotal = $this->countOptionItems(BricksMetaKeys::OPTION_GLOBAL_VARIABLES);
        $unusedClasses = (new DeadCodeFinder())->findUnusedClasses(['limit' => 1000, 'offset' => 0]);
        $unusedVars    = (new DeadCodeFinder())->findUnusedVariables(['limit' => 1000, 'offset' => 0]);
        $convention    = DesignConventionStore::get();
        $detection     = (new ExternalFrameworkDetector())->detect();
        $coverage      = (new IndexReader())->coverage();

        return [
            'global_classes_total'  => $classesTotal,
            'global_classes_unused' => (int) ($unusedClasses['total'] ?? 0),
            'variables_total'       => $variablesTotal,
            'variables_unused'      => (int) ($unusedVars['total'] ?? 0),
            'components_total'      => $this->countOptionItems(BricksMetaKeys::OPTION_COMPONENTS),
            'templates_total'       => $this->countPublishedPosts('bricks_template'),
            'css_loading'           => BricksEnv::cssLoadingMode(),
            'index_coverage'        => $coverage,
            'convention'            => $convention,
            'detected_framework'    => $detection,
        ];
    }

    private function countOptionItems(string $optionName): int
    {
        $value = get_option($optionName, []);
        if (!is_array($value)) {
            return 0;
        }

        return count($value);
    }

    private function countPublishedPosts(string $postType): int
    {
        $counts = wp_count_posts($postType);
        if (!is_object($counts) || !isset($counts->publish)) {
            return 0;
        }

        return (int) $counts->publish;
    }
}
