<?php
/**
 * Groq API wrapper for the EduTrack blog generator.
 */

require_once __DIR__ . '/db.php';

/**
 * Send a chat completion request to Groq.
 * Returns the decoded JSON response array or throws on failure.
 *
 * @param array $messages  [['role'=>'system','content'=>'...'], ...]
 * @param bool  $json_mode Force JSON object response
 */
function groq_chat(array $messages, bool $json_mode = false): array
{
    $key = blog_groq_key();
    if ($key === '') {
        throw new RuntimeException('GROQ_API_KEY is not set in .env');
    }

    $payload = [
        'model'       => GROQ_MODEL,
        'messages'    => $messages,
        'temperature' => 0.7,
        'max_tokens'  => 4096,
    ];
    if ($json_mode) {
        $payload['response_format'] = ['type' => 'json_object'];
    }

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

    $response  = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_err  = curl_error($ch);
    curl_close($ch);

    if ($curl_err) {
        throw new RuntimeException('Groq cURL error: ' . $curl_err);
    }

    $decoded = json_decode($response ?: '{}', true);

    if ($http_code !== 200) {
        $msg = $decoded['error']['message'] ?? ('HTTP ' . $http_code);
        throw new RuntimeException('Groq API error: ' . $msg);
    }

    $content = $decoded['choices'][0]['message']['content'] ?? '';
    if ($content === '') {
        throw new RuntimeException('Groq returned empty content');
    }

    if ($json_mode) {
        $parsed = json_decode($content, true);
        if (!is_array($parsed)) {
            throw new RuntimeException('Groq JSON parse failed: ' . $content);
        }
        return $parsed;
    }

    return ['content' => $content];
}
