<?php
// app/api/stream.php - streams OpenAI Responses API events to the browser and saves to DB
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/openai_client.php';

// CORS (optional adjust for your domain)
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit; }

// SSE headers
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');

// Keep PHP from buffering
@ini_set('output_buffering', 'off');
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
while (ob_get_level() > 0) { ob_end_flush(); }
ob_implicit_flush(1);

$input = json_decode(file_get_contents('php://input'), true);
$message = isset($input['message']) ? trim($input['message']) : '';
$conversation_id = isset($input['conversation_id']) ? intval($input['conversation_id']) : 1;
$model = isset($input['model']) ? $input['model'] : openai_model();

if (!$message) {
    echo "event: error\n";
    echo "data: " . json_encode(['error' => 'empty message']) . "\n\n";
    flush();
    exit;
}
if (!openai_key()) {
    echo "event: error\n";
    echo "data: " . json_encode(['error' => 'OPENAI_API_KEY not set']) . "\n\n";
    flush();
    exit;
}

$pdo = db();

// Insert user message
$stmt = $pdo->prepare("INSERT INTO messages (conversation_id, role, content) VALUES (?, 'user', ?)");
$stmt->execute([$conversation_id, $message]);
$user_msg_id = $pdo->lastInsertId();

// Fetch last 12 messages for simple prompt concatenation
$stmt = $pdo->prepare("SELECT role, content FROM messages WHERE conversation_id = ? ORDER BY id DESC LIMIT 12");
$stmt->execute([$conversation_id]);
$rows = array_reverse($stmt->fetchAll());

$prompt = "You are ChatGPT-like assistant. Be concise and helpful.\n\n";
foreach ($rows as $r) {
    $prompt .= strtoupper($r['role']) . ": " . $r['content'] . "\n\n";
}
$prompt .= "ASSISTANT:";

$body = [
    'model' => $model,
    'input' => $prompt,
    'stream' => true,
    'temperature' => 0.5
];

$assistant_text = '';

try {
    openai_stream_responses($body, function($chunk) use (&$assistant_text) {
        // Proxy raw SSE from OpenAI while also extracting deltas for buffering
        // We forward lines as-is, and also try to capture text deltas from responses API
        $lines = preg_split("/\r?\n/", $chunk);
        $current_event = null;
        foreach ($lines as $line) {
            if (strpos($line, 'event: ') === 0) {
                $current_event = trim(substr($line, 7));
            }
            if (strpos($line, 'data: ') === 0) {
                $data = trim(substr($line, 6));
                // Append to buffer if this is a text delta
                if ($current_event === 'response.output_text.delta') {
                    $j = json_decode($data, true);
                    if ($j && isset($j['delta'])) {
                        $assistant_text .= $j['delta'];
                    } elseif ($j && isset($j['text'])) {
                        $assistant_text .= $j['text'];
                    }
                }
            }
            // Forward original line to client
            echo $line . "\n";
        }
        echo "\n";
        flush();
    });
} catch (Exception $e) {
    echo "event: error\n";
    echo "data: " . json_encode(['error' => $e->getMessage()]) . "\n\n";
    flush();
    exit;
}

// After stream ends, save assistant message
if (trim($assistant_text) !== '') {
    $stmt = $pdo->prepare("INSERT INTO messages (conversation_id, role, content) VALUES (?, 'assistant', ?)");
    $stmt->execute([$conversation_id, $assistant_text]);
}
