<?php
/**
 * Shared LiteLLM/OpenAI-compatible chat client.
 * Reads /etc/whp/ai-monitor.conf (the AI Dashboard config) so every
 * AI-touching feature in WHP routes through the same endpoint+key+model.
 */

if (!function_exists('litellm_chat')) {

    /**
     * @param string $tier      'advanced' or 'basic'
     * @param array  $messages  OpenAI-style [['role'=>..., 'content'=>...], ...]
     * @param array  $opts      Optional: 'response_format' (e.g. ['type'=>'json_object']),
     *                          'max_tokens', 'temperature', 'timeout' (default 60s),
     *                          'top_p', 'stop', 'tools', 'tool_choice', 'metadata',
     *                          'extra_body' (merged into request body, non-clobbering).
     *                          Per-message 'cache_control' rides inside $messages[].
     * @return array On success: {success: true, content, model, usage: {prompt_tokens,
     *                  completion_tokens, cached_tokens}}.
     *               On failure: {success: false, error}.
     */
    function litellm_chat(string $tier, array $messages, array $opts = []): array {
        $configFile = '/etc/whp/ai-monitor.conf';
        if (!file_exists($configFile)) {
            return ['success' => false, 'error' => 'AI service not configured on this server.'];
        }
        $config = parse_ini_file($configFile, true);
        $ai = $config['ai'] ?? [];
        $baseUrl    = rtrim($ai['base_url'] ?? '', '/');
        $apiKeyFile = $ai['api_key_file'] ?? '';
        $model      = ($tier === 'basic')
            ? ($ai['basic_model'] ?? $ai['advanced_model'] ?? '')
            : ($ai['advanced_model'] ?? $ai['basic_model'] ?? '');
        if (!$baseUrl || !$apiKeyFile || !$model || !file_exists($apiKeyFile)) {
            return ['success' => false, 'error' => 'AI service credentials are incomplete.'];
        }
        $apiKey = trim((string)file_get_contents($apiKeyFile));
        if ($apiKey === '') {
            return ['success' => false, 'error' => 'AI API key missing.'];
        }

        $body = ['model' => $model, 'messages' => $messages];
        $forwardKeys = [
            'response_format', 'max_tokens', 'temperature',
            'top_p', 'stop', 'tools', 'tool_choice', 'metadata',
        ];
        foreach ($forwardKeys as $k) {
            if (isset($opts[$k])) {
                $body[$k] = $opts[$k];
            }
        }
        if (isset($opts['extra_body']) && is_array($opts['extra_body'])) {
            foreach ($opts['extra_body'] as $k => $v) {
                if (!isset($body[$k])) {
                    $body[$k] = $v;
                }
            }
        }

        $ch = curl_init($baseUrl . '/chat/completions');
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => json_encode($body),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => $opts['timeout'] ?? 60,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $apiKey,
            ],
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlErr  = curl_error($ch);
        curl_close($ch);

        if ($response === false) {
            error_log('litellm_chat: curl error: ' . $curlErr);
            return ['success' => false, 'error' => 'Could not reach the AI service.'];
        }
        if ($httpCode !== 200) {
            error_log('litellm_chat: HTTP ' . $httpCode . ': ' . substr((string)$response, 0, 300));
            return ['success' => false, 'error' => 'AI service returned HTTP ' . $httpCode . '.'];
        }
        $data = json_decode($response, true);
        $content = $data['choices'][0]['message']['content'] ?? '';
        if ($content === '') {
            return ['success' => false, 'error' => 'AI service returned an empty response.'];
        }
        $usage = $data['usage'] ?? [];
        return [
            'success' => true,
            'content' => trim($content),
            'model'   => $data['model'] ?? $model,
            'usage'   => [
                'prompt_tokens'     => (int)($usage['prompt_tokens'] ?? 0),
                'completion_tokens' => (int)($usage['completion_tokens'] ?? 0),
                'cached_tokens'     => (int)(
                    $usage['prompt_tokens_details']['cached_tokens']
                    ?? $usage['cache_read_input_tokens']
                    ?? 0
                ),
            ],
        ];
    }
}
