<?php
declare(strict_types=1);

/** Workflow triage tags — multiple labels per report allowed (e.g. duplicate + fixed). */
final class TagCatalog {
    /** @var list<array{id:string,label:string,bg:string}>|null */
    private static ?array $workflow = null;

    /** @return list<array{id:string,label:string,bg:string}> */
    public static function workflowPresets(): array {
        if (self::$workflow !== null) {
            return self::$workflow;
        }
        self::$workflow = [
            ['id' => 'in-progress', 'label' => 'in progress', 'bg' => '#3d8bfd'],
            ['id' => 'fixed', 'label' => 'fixed', 'bg' => '#047857'],
            ['id' => 'rejected', 'label' => 'rejected', 'bg' => '#dc2626'],
            ['id' => 'done', 'label' => 'done', 'bg' => '#5c6b82'],
            ['id' => 'not-reproducible', 'label' => 'not reproducible', 'bg' => '#d97706'],
            ['id' => 'not-a-bug', 'label' => 'not a bug', 'bg' => '#6b7280'],
            ['id' => 'duplicate', 'label' => 'duplicate', 'bg' => '#6d28d9'],
        ];
        return self::$workflow;
    }

    /** @return array<string, true> */
    public static function workflowIds(): array {
        $map = [];
        foreach (self::workflowPresets() as $tag) {
            $map[$tag['id']] = true;
        }
        return $map;
    }

    public static function isWorkflowId(string $id): bool {
        return isset(self::workflowIds()[$id]);
    }

    /**
     * @param list<string> $raw from query (?tag=fixed&tag=duplicate)
     * @return list<string>
     */
    public static function normalizeFilterIds(array $raw): array {
        $out = [];
        $seen = [];
        foreach ($raw as $item) {
            $id = strtolower(trim((string) $item));
            $id = preg_replace('/[^a-z0-9_-]+/i', '-', $id) ?? '';
            $id = trim($id, '-');
            if ($id === '' || strlen($id) > 32 || isset($seen[$id])) {
                continue;
            }
            if (isset(array_flip(report_reserved_tag_ids())[$id])) {
                continue;
            }
            $seen[$id] = true;
            $out[] = $id;
            if (count($out) >= 8) {
                break;
            }
        }
        return $out;
    }

    /**
     * Workflow presets first, then distinct custom tags from DB (excluding workflow ids).
     *
     * @return list<array{id:string,label:string,bg:string}>
     */
    public static function editorPresets(int $historicalLimit = 32): array {
        $map = [];
        foreach (self::workflowPresets() as $tag) {
            $map[$tag['id']] = $tag;
        }
        foreach (ReportRepository::listTagPresets($historicalLimit + 20) as $tag) {
            $id = (string) ($tag['id'] ?? '');
            if ($id === '' || isset($map[$id])) {
                continue;
            }
            $map[$id] = $tag;
        }
        return array_values($map);
    }
}
