<?php

declare(strict_types=1);

namespace ProPresenter\Parser;

use Rv\Data\ProLabelsDocument;

/**
 * Wraps the protobuf {@see ProLabelsDocument} — the global ProPresenter
 * `Labels` file which lists every named label and its UI color.
 *
 * Labels are identified by name only (there is no UUID field). Names are
 * expected to be unique inside the document; if the source file violates
 * that, the first occurrence wins for {@see getLabelByName()} but every
 * label is preserved in {@see getLabels()} in document order.
 */
class LabelLibrary
{
    /** @var Label[] */
    private array $labels = [];

    /** @var array<string, Label> */
    private array $labelsByName = [];

    /** @var array<string, Label> */
    private array $labelsByNameLower = [];

    public function __construct(
        private readonly ProLabelsDocument $document,
    ) {
        foreach ($this->document->getLabels() as $labelProto) {
            $label = new Label($labelProto);
            $this->labels[] = $label;

            $name = $label->getName();
            if ($name === '') {
                continue;
            }

            $this->labelsByName[$name] ??= $label;
            $this->labelsByNameLower[strtolower($name)] ??= $label;
        }
    }

    /**
     * @return Label[]
     */
    public function getLabels(): array
    {
        return $this->labels;
    }

    public function count(): int
    {
        return count($this->labels);
    }

    /**
     * Exact-name lookup. Use {@see findLabelByName()} for a
     * case-insensitive variant.
     */
    public function getLabelByName(string $name): ?Label
    {
        return $this->labelsByName[$name] ?? null;
    }

    /**
     * Case-insensitive name lookup.
     */
    public function findLabelByName(string $name): ?Label
    {
        return $this->labelsByNameLower[strtolower($name)] ?? null;
    }

    /**
     * Get the underlying protobuf ProLabelsDocument.
     */
    public function getDocument(): ProLabelsDocument
    {
        return $this->document;
    }
}
