<?php
// app/api/openai_client.php - tiny HTTP client for OpenAI Responses API (stream + non-stream)
require_once __DIR__ . '/../config.php';

function openai_base() { return rtrim(envv('OPENAI_BASE_URL', 'https://api.openai.com/v1'), '/'); }
function openai_key() { return envv('OPENAI_API_KEY'); }
function openai_model() { return envv('OPENAI_MODEL', 'gpt-5'); }

if (!function_exists('curl_stream_request')) {
    function curl_stream_request($url, $headers, $payload, $on_chunk) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use ($on_chunk) {
            $on_chunk($data);
            return strlen($data);
        });
        curl_setopt($ch, CURLOPT_TIMEOUT, 0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_exec($ch);
        $err = curl_error($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);
        if ($err) {
            throw new Exception('cURL error: ' . $err);
        }
        return $info;
    }
}

function openai_stream_responses($body, $on_chunk) {
    $url = openai_base() . '/responses';
    $headers = [
        'Authorization: Bearer ' . openai_key(),
        'Content-Type: application/json',
        'Accept: text/event-stream'
    ];
    $payload = json_encode($body);
    return curl_stream_request($url, $headers, $payload, $on_chunk);
}

function openai_create($body) {
    $url = openai_base() . '/responses';
    $headers = [
        'Authorization: Bearer ' . openai_key(),
        'Content-Type: application/json'
    ];
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $res = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    if ($err) throw new Exception('OpenAI request failed: ' . $err);
    return json_decode($res, true);
}
