<?php
/**
 * Heuristic detection of external class naming frameworks on Bricks sites.
 *
 * @package LolaCoreForBricks
 */

declare(strict_types=1);

namespace LolaCoreForBricks\Support;

/**
 * Proposes a likely external utility framework from existing global class names.
 */
final class ExternalFrameworkDetector
{
    /**
     * @return array{framework: string, confidence: int, suggested_pattern: string, sample_classes: string[]}|null
     */
    public function detect(): ?array
    {
        $names = $this->loadClassNames();
        if ($names === []) {
            return null;
        }

        $scores = [
            'tailwind'  => 0,
            'bootstrap' => 0,
            'bem'       => 0,
        ];

        foreach ($names as $name) {
            $lower = strtolower($name);
            if (preg_match('/^(flex|grid|hidden|block|inline|relative|absolute|fixed|sticky|overflow|rounded|shadow|opacity|z-\d|p-\d|m-\d|px-|py-|pt-|pb-|pl-|pr-|mx-|my-|mt-|mb-|ml-|mr-|text-|font-|leading-|tracking-|bg-|border-|w-|h-|min-|max-|gap-|space-|items-|justify-|self-|order-|col-|row-span)/', $lower) === 1) {
                ++$scores['tailwind'];
            }
            if (preg_match('/^(container|row|col-|btn-|d-|justify-content-|align-items-|text-start|text-center|text-end|g-\d|offset-)/', $lower) === 1) {
                ++$scores['bootstrap'];
            }
            if (preg_match('/^[a-z][a-z0-9-]*(__[a-z0-9-]+)?(--[a-z0-9-]+)?$/', $lower) === 1) {
                ++$scores['bem'];
            }
        }

        arsort($scores);
        $framework  = (string) array_key_first($scores);
        $score      = (int) ($scores[$framework] ?? 0);
        $threshold  = max(3, (int) ceil(count($names) * 0.15));

        if ($score < $threshold) {
            return null;
        }

        $confidence = (int) min(100, round(($score / max(1, count($names))) * 100));

        return [
            'framework'         => $framework,
            'confidence'        => $confidence,
            'suggested_pattern' => $this->suggestedPattern($framework),
            'sample_classes'    => array_slice($names, 0, 5),
        ];
    }

    /**
     * @return string[]
     */
    private function loadClassNames(): array
    {
        $raw = get_option(BricksMetaKeys::OPTION_GLOBAL_CLASSES, []);
        if (!is_array($raw)) {
            return [];
        }

        $names = [];
        foreach ($raw as $class) {
            if (!is_array($class)) {
                continue;
            }

            $name = trim((string) ($class['name'] ?? ''));
            if ($name !== '') {
                $names[] = $name;
            }
        }

        return $names;
    }

    private function suggestedPattern(string $framework): string
    {
        return match ($framework) {
            'tailwind'  => '/^[a-z0-9:-]+$/',
            'bootstrap' => '/^(container|row|col-[a-z0-9-]+|btn-[a-z0-9-]+|d-[a-z-]+|text-[a-z]+|g-[0-9]+|offset-[0-9]+)$/',
            'bem'       => '/^[a-z][a-z0-9-]*(__[a-z0-9-]+)?(--[a-z0-9-]+)?$/',
            default     => '/^[a-z][a-z0-9-]*([.-][a-z0-9-]+)*$/',
        };
    }
}
