<?php

namespace Mtc\Plugins\BlockManager\Services;

/**
 * Counts {token: ...} vs {raw: ...} value wraps across a variant's property
 * tree, walking every (state × breakpoint) cell. Surfaces drift from the
 * design system: a variant with many raws is a signal that a token is missing
 * — or that a designer used the raw-value escape hatch too liberally.
 *
 * Empty / null wrappers contribute to neither count — they are "inherit"
 * markers, not values.
 */
class VariantRawValueAuditor
{
    /**
     * @param array<string, mixed> $propertiesJson
     * @return array{raw_count: int, token_count: int}
     */
    public function audit(array $propertiesJson): array
    {
        $raw = 0;
        $token = 0;

        $base = $propertiesJson['base'] ?? null;
        if (!is_array($base)) {
            return ['raw_count' => 0, 'token_count' => 0];
        }

        foreach ($base as $stateCells) {
            if (!is_array($stateCells)) {
                continue;
            }
            foreach ($stateCells as $breakpointCell) {
                if (!is_array($breakpointCell)) {
                    continue;
                }
                foreach ($breakpointCell as $properties) {
                    if (!is_array($properties)) {
                        continue;
                    }
                    foreach ($properties as $wrap) {
                        if (!is_array($wrap)) {
                            continue;
                        }
                        if (isset($wrap['token']) && is_string($wrap['token']) && $wrap['token'] !== '') {
                            $token++;
                            continue;
                        }
                        if (array_key_exists('raw', $wrap) && $wrap['raw'] !== null && $wrap['raw'] !== '') {
                            $raw++;
                        }
                    }
                }
            }
        }

        return ['raw_count' => $raw, 'token_count' => $token];
    }
}
