<?php

namespace App\Services;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\File;

class UiTextCatalogService
{
    public function __construct(private BladeUiTranslationService $bladeUi)
    {
    }

    /** @return Collection<string,string> */
    public function catalog(): Collection
    {
        $english = trans('ui', [], 'en');
        $named = collect(is_array($english) ? $english : [])
            ->mapWithKeys(fn (mixed $value, string $key): array => ['ui.'.$key => (string) $value]);

        $knownText = $named
            ->values()
            ->map(fn (string $value): string => $this->bladeUi->normalize($value))
            ->filter()
            ->flip();

        $automatic = collect();

        foreach (File::allFiles(resource_path('views')) as $file) {
            if ($file->getExtension() !== 'php' || ! str_ends_with($file->getFilename(), '.blade.php')) {
                continue;
            }

            foreach ($this->bladeUi->extract(File::get($file->getPathname())) as $key => $value) {
                if ($knownText->has($this->bladeUi->normalize($value))) {
                    continue;
                }

                $automatic->put($key, $value);
            }
        }

        return $named->sortKeys()
            ->merge($automatic->sortBy(fn (string $value): string => mb_strtolower($value)));
    }
}
