<?php

namespace Mtc\Plugins\BlockManager\Services;

use Mtc\Plugins\BlockManager\Models\BlockManagerVariantDraft;
use RuntimeException;

/**
 * Adds (or updates in place) a variant entry in an element's manifest:
 *   plugins/BlockManager/elements/{element_type}/element.json
 *
 * Idempotent — if the variant_slug already appears in `variants[]`, the
 * entry is overwritten rather than duplicated. Returns the manifest path
 * for the publish service to include in its audit response.
 */
class VariantManifestPatcher
{
    public function patch(BlockManagerVariantDraft $draft): string
    {
        $path = $this->manifestPath($draft->element_type);
        if (!is_file($path)) {
            throw new RuntimeException("Element manifest not found: {$path}");
        }

        $raw = (string) file_get_contents($path);
        $manifest = json_decode($raw, true);
        if (!is_array($manifest)) {
            throw new RuntimeException("Manifest is not valid JSON: {$path}");
        }

        $variants = is_array($manifest['variants'] ?? null) ? $manifest['variants'] : [];

        $entry = [
            'id'    => $draft->variant_slug,
            'label' => $draft->label !== null && $draft->label !== ''
                ? $draft->label
                : $this->humanize($draft->variant_slug),
        ];

        $replaced = false;
        foreach ($variants as $i => $existing) {
            if (is_array($existing) && ($existing['id'] ?? null) === $draft->variant_slug) {
                $variants[$i] = $entry;
                $replaced = true;
                break;
            }
        }
        if (!$replaced) {
            $variants[] = $entry;
        }

        $manifest['variants'] = $variants;

        file_put_contents(
            $path,
            json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n"
        );

        return $path;
    }

    private function manifestPath(string $elementType): string
    {
        return base_path("plugins/BlockManager/elements/{$elementType}/element.json");
    }

    private function humanize(string $name): string
    {
        return ucwords(str_replace(['-', '_'], ' ', $name));
    }
}
