<?php

namespace Mtc\Plugins\BlockManager\Services;

/**
 * Maintains the frontend LESS aggregator for shipped-block instance styles.
 *
 * Each shipped block whose containers carry per-instance styling writes a
 * stylesheet at sites/default/css/block_manager_blocks/{slug}.less (token
 * references preserved as @vars). This service (re)generates
 * sites/default/css/block_manager_blocks.less — a flat list of @import lines —
 * which sites/default/includes.less imports once, so Vite compiles the lot into
 * app.css with variables.less in scope (design tokens resolve).
 *
 * Parallel to VariantStyleAggregator but for a different lifecycle (block ship
 * vs variant publish) and a different source directory, so the two stay
 * independent. Output is sorted for deterministic, churn-free diffs.
 */
class BlockStyleAggregator
{
    private const BLOCKS_DIR_RELATIVE = 'sites/default/css/block_manager_blocks';
    private const AGGREGATOR_RELATIVE = 'sites/default/css/block_manager_blocks.less';

    /**
     * Scan the per-block styles directory and rewrite the aggregator LESS file.
     *
     * @return string Absolute path to the (re)written aggregator file.
     */
    public function rebuild(): string
    {
        $blocksDir = base_path(self::BLOCKS_DIR_RELATIVE);
        $aggregatorPath = base_path(self::AGGREGATOR_RELATIVE);

        $files = glob("{$blocksDir}/*.less") ?: [];
        sort($files);

        $lines = ['/* AUTO-GENERATED by BlockStyleAggregator — do not edit by hand. */'];
        foreach ($files as $file) {
            $lines[] = "@import './block_manager_blocks/" . basename($file) . "';";
        }

        file_put_contents($aggregatorPath, implode("\n", $lines) . "\n");

        return $aggregatorPath;
    }
}
