<?php

namespace ZenoChatbot\Services\LLMService\AIClient;

use ZenoChatbot\Services\LLMService\AIClient\Config\AiConfig;
use ZenoChatbot\Services\LLMService\AIClient\Builders\PromptBuilder;

if (!defined('ABSPATH')) {
    exit;
}

class AiClient
{
    private ?AiConfig $config = null;

    /**
     * Initialize an AiClient with optional configuration.
     * Accepts either an AiConfig instance or an array which will be built via ConfigBuilder.
     *
     * @param AiConfig|array|null $config
     * @return self
     */
    public static function config($config = null): self
    {
        $c = new static();
        if (is_array($config)) {
            $c->config = \ZenoChatbot\Services\LLMService\AIClient\Config\AiConfig::fromArray($config)->build();
        } else {
            $c->config = $config;
        }
        return $c;
    }

    public function prompt(string $text): PromptBuilder
    {
        return new PromptBuilder($this->config, $text);
    }

    /**
     * Perform a minimal, provider-agnostic connection test using the configured provider/model/key.
     * On success returns a standardized array (provider, model, message, usage). On failure, throws.
     */
    public function testConnection(): array
    {
        if (!$this->config) {
            throw new \RuntimeException('AiClient: testConnection requires a configuration.');
        }

        // Build an effective config with safe/cheap params
        $base = $this->config->toArray();
        $effConfig = \ZenoChatbot\Services\LLMService\AIClient\Config\ConfigBuilder::create()
            ->fromArray([
                'provider'    => $base['provider'] ?? '',
                'model'       => $base['model'] ?? '',
                'api_key'     => $base['api_key'] ?? '',
                'temperature' => 0.0,
                'max_tokens'  => min(5, (int)($base['max_tokens'] ?? 5)),
            ])->build();

        $payload = [
            'message' => 'Say hello',
            'system_prompts' => ['Connection test'],
            'context' => [],
            'resources' => [],
            'require_citations' => false,
            'fallback' => null,
            'candidate_count' => 1,
            'temperature' => $effConfig->getTemperature(),
            'max_tokens' => $effConfig->getMaxTokens(),
        ];

        $providerClass = $effConfig->getProviderClass();

        /** @var \ZenoChatbot\Services\LLMService\AIClient\Results\GenerativeAiResult $res */
        $provider = new $providerClass();
        $res = $provider->text()->generate($payload, $effConfig);
        $usage = $res->getTokenUsage();
        $usageArr = $usage ? $usage->toArray() : null;

        return [
            'success'  => true,
            'provider' => $base['provider'] ?? '',
            'model'    => $effConfig->getModel(),
            'message'  => 'Connection successful',
            'usage'    => $usageArr,
        ];
    }

}

