<?php

declare(strict_types=1);

namespace App\Config;

/**
 * YAML-backed deterministic list-intent configuration.
 *
 * This class intentionally has no PHP fallback values. Missing or invalid
 * configuration must be fixed in config/retriex/intent.yaml.
 */
final class IntentLightConfig
{
    /**
     * @param array<string, mixed> $config
     */
    public function __construct(private readonly array $config)
    {
    }

    public function getListThreshold(): int
    {
        return $this->requiredPositiveInt('list_threshold');
    }

    /** @return string[] */
    public function getQuantityWords(): array
    {
        return $this->requiredStringList('quantity_words');
    }

    /** @return string[] */
    public function getStrongPatterns(): array
    {
        return $this->requiredStringList('strong_patterns');
    }

    private function requiredPositiveInt(string $key): int
    {
        if (!array_key_exists($key, $this->config)) {
            throw new \InvalidArgumentException(sprintf('Missing required RetrieX light intent config key "%s".', $key));
        }

        $value = $this->config[$key];

        if (is_int($value)) {
            $intValue = $value;
        } elseif (is_string($value) && preg_match('/^-?\d+$/', trim($value)) === 1) {
            $intValue = (int) trim($value);
        } else {
            throw new \InvalidArgumentException(sprintf('RetrieX light intent config key "%s" must be an integer.', $key));
        }

        if ($intValue <= 0) {
            throw new \InvalidArgumentException(sprintf('RetrieX light intent config key "%s" must be greater than 0.', $key));
        }

        return $intValue;
    }

    /** @return string[] */
    private function requiredStringList(string $key): array
    {
        if (!array_key_exists($key, $this->config)) {
            throw new \InvalidArgumentException(sprintf('Missing required RetrieX light intent config key "%s".', $key));
        }

        $value = $this->config[$key];

        if (!is_array($value)) {
            throw new \InvalidArgumentException(sprintf('RetrieX light intent config key "%s" must be a list.', $key));
        }

        $out = [];
        foreach ($value as $item) {
            if (!is_scalar($item)) {
                continue;
            }

            $item = trim((string) $item);
            if ($item === '') {
                continue;
            }

            if (!in_array($item, $out, true)) {
                $out[] = $item;
            }
        }

        if ($out === []) {
            throw new \InvalidArgumentException(sprintf('RetrieX light intent config key "%s" must not be empty.', $key));
        }

        return $out;
    }
}
