<?php

namespace Mtc\Plugins\BlockManager\Services;

use Mtc\Plugins\BlockManager\Models\BlockManagerVariantDraft;

/**
 * Detects when a Designer-published LESS file has drifted from what the
 * generator would emit for the current draft — typically because a developer
 * hand-edited the file between publishes. The Designer UI surfaces this so
 * the next publish can prompt: overwrite / merge / open in editor.
 *
 * Byte-diff against the generator output is the v1 contract — cheap, correct,
 * and aligned with the @designer-meta round-trip guarantees (the meta header
 * is part of the byte stream, so any tampering with it also flags as drift).
 */
class VariantConflictDetector
{
    public function __construct(private VariantLessGenerator $generator)
    {
    }

    /**
     * @return array{has_conflict: bool, reason: string|null}
     */
    public function detect(BlockManagerVariantDraft $draft): array
    {
        $path = $this->resolveLessPath($draft);
        if ($path === null) {
            return ['has_conflict' => false, 'reason' => null];
        }

        $onDisk   = (string) file_get_contents($path);
        $expected = $this->generator->generate($draft);

        if ($onDisk === $expected) {
            return ['has_conflict' => false, 'reason' => null];
        }

        return [
            'has_conflict' => true,
            'reason'       => "Local edit detected — on-disk LESS at {$path} diverges from the Designer's regenerated output.",
        ];
    }

    private function resolveLessPath(BlockManagerVariantDraft $draft): ?string
    {
        $audited = $draft->published_less_path;
        if (is_string($audited) && is_file($audited)) {
            return $audited;
        }
        $canonical = base_path("plugins/BlockManager/elements/{$draft->element_type}/styles/{$draft->variant_slug}.less");
        return is_file($canonical) ? $canonical : null;
    }
}
