<?php
namespace CAE\Modules\ContentEngine;

use RuntimeException;

class OpenAIClient
{
    private string $apiKey;
    private string $model;
    private int    $maxTokens;
    private float  $temperature;
    private int    $timeout;

    public function __construct()
    {
        $config            = require ROOT_PATH . '/config/openai.php';
        $this->apiKey      = $config['api_key']     ?? '';
        $this->model       = $config['model']        ?? 'gpt-4o';
        $this->maxTokens   = $config['max_tokens']   ?? 4096;
        $this->temperature = (float)($config['temperature'] ?? 0.7);
        $this->timeout     = $config['timeout']      ?? 120;

        if (empty($this->apiKey)) {
            throw new RuntimeException('OpenAI API key not configured. Set OPENAI_API_KEY environment variable or update config/openai.php.');
        }
    }

    /**
     * Send a chat completion request.
     *
     * @return array{content: string, input_tokens: int, output_tokens: int, model: string}
     */
    public function chat(string $systemPrompt, string $userPrompt): array
    {
        $payload = json_encode([
            'model'       => $this->model,
            'max_tokens'  => $this->maxTokens,
            'temperature' => $this->temperature,
            'messages'    => [
                ['role' => 'system', 'content' => $systemPrompt],
                ['role' => 'user',   'content' => $userPrompt],
            ],
        ]);

        $ch = curl_init('https://api.openai.com/v1/chat/completions');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $payload,
            CURLOPT_TIMEOUT        => $this->timeout,
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $this->apiKey,
            ],
            CURLOPT_SSL_VERIFYPEER => true,
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlErr  = curl_error($ch);
        curl_close($ch);

        if ($curlErr) {
            throw new RuntimeException('OpenAI request failed: ' . $curlErr);
        }

        $data = json_decode($response, true);

        if ($httpCode !== 200) {
            $errMsg = $data['error']['message'] ?? "HTTP {$httpCode}";
            throw new RuntimeException('OpenAI API error: ' . $errMsg);
        }

        if (empty($data['choices'][0]['message']['content'])) {
            throw new RuntimeException('OpenAI returned empty content');
        }

        return [
            'content'       => trim($data['choices'][0]['message']['content']),
            'input_tokens'  => $data['usage']['prompt_tokens']     ?? 0,
            'output_tokens' => $data['usage']['completion_tokens'] ?? 0,
            'model'         => $data['model'] ?? $this->model,
        ];
    }
}
