<?php
namespace boru\ai\Provider;

class ProviderRegistry
{
    /** @var ProviderInterface[] */
    protected $providers = array();

    /** @var array */
    protected $modelPrefixes = array();

    public function register(ProviderInterface $provider)
    {
        $this->providers[$provider->name()] = $provider;
        return $this;
    }

    public function has($name)
    {
        return isset($this->providers[$name]);
    }

    public function get($name)
    {
        if (!$this->has($name)) {
            throw new \InvalidArgumentException('Unknown provider: ' . $name);
        }
        return $this->providers[$name];
    }

    public function all()
    {
        return $this->providers;
    }

    public function mapModelPrefix($prefix, $providerName)
    {
        $this->modelPrefixes[(string)$prefix] = (string)$providerName;
        return $this;
    }

    public function resolveByModel($model)
    {
        $model = (string)$model;

        foreach ($this->modelPrefixes as $prefix => $providerName) {
            if ($prefix !== '' && strpos(strtolower($model), strtolower($prefix)) === 0) {
                if ($this->has($providerName)) {
                    return $this->get($providerName);
                }
            }
        }

        foreach ($this->providers as $provider) {
            if ($provider->supportsModel($model)) {
                return $provider;
            }
        }

        return false;
    }
}
