<?php
/**
 * Chat API Endpoint
 * Flutter AI Assistant - Groq API Integration
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display, but log
ini_set('log_errors', 1);

// Load configuration
require_once '../config.php';

// Check if streaming is requested
$isStreaming = isset($_GET['stream']) && $_GET['stream'] === 'true';

// Set headers
if ($isStreaming) {
    // Disable output buffering for streaming
    @ini_set('output_buffering', 'off');
    @ini_set('zlib.output_compression', false);
    while (ob_get_level()) ob_end_flush();
    ob_implicit_flush(true);
    
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    header('Connection: keep-alive');
    header('X-Accel-Buffering: no'); // For nginx
} else {
    header('Content-Type: application/json');
}
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit();
}

// Get request body
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// Validate input
if (!isset($data['message']) || empty(trim($data['message']))) {
    http_response_code(400);
    echo json_encode(['error' => ERROR_NO_MESSAGE]);
    exit();
}

$userMessage = trim($data['message']);
$history = isset($data['history']) ? $data['history'] : [];

// Build messages array for API
$messages = [];

// Add system prompt
$messages[] = [
    'role' => 'system',
    'content' => SYSTEM_PROMPT
];

// Add conversation history
foreach ($history as $msg) {
    if (isset($msg['role']) && isset($msg['content'])) {
        $messages[] = [
            'role' => $msg['role'],
            'content' => $msg['content']
        ];
    }
}

// Add current user message
$messages[] = [
    'role' => 'user',
    'content' => $userMessage
];

// Prepare API request
$apiData = [
    'model' => AI_MODEL,
    'messages' => $messages,
    'temperature' => TEMPERATURE,
    'max_tokens' => MAX_TOKENS,
    'top_p' => 1,
    'stream' => $isStreaming
];

// Make API request to Groq
try {
    $ch = curl_init(GROQ_API_URL);
    
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($apiData),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . GROQ_API_KEY
        ],
        CURLOPT_TIMEOUT => API_TIMEOUT,
        CURLOPT_SSL_VERIFYPEER => true
    ]);
    
    // Handle streaming vs non-streaming
    if ($isStreaming) {
        // For streaming, we need to handle the response differently
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($curl, $data) {
            // Parse SSE data from Groq
            $lines = explode("\n", $data);
            foreach ($lines as $line) {
                if (strpos($line, 'data: ') === 0) {
                    $jsonData = substr($line, 6);
                    if ($jsonData === '[DONE]') {
                        echo "data: [DONE]\n\n";
                        ob_flush();
                        flush();
                        continue;
                    }
                    
                    $chunk = json_decode($jsonData, true);
                    if (isset($chunk['choices'][0]['delta']['content'])) {
                        $content = $chunk['choices'][0]['delta']['content'];
                        echo "data: " . json_encode(['content' => $content]) . "\n\n";
                        ob_flush();
                        flush();
                    }
                }
            }
            return strlen($data);
        });
        
        curl_exec($ch);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        if ($curlError) {
            echo "data: " . json_encode(['error' => 'Connection error: ' . $curlError]) . "\n\n";
            ob_flush();
            flush();
        }
        
    } else {
        // Non-streaming response (original behavior)
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        
        curl_close($ch);
        
        // Check for cURL errors
        if ($curlError) {
            throw new Exception('Connection error: ' . $curlError);
        }
        
        // Check HTTP status
        if ($httpCode !== 200) {
            $errorData = json_decode($response, true);
            $errorMsg = isset($errorData['error']['message']) 
                ? $errorData['error']['message'] 
                : 'API request failed';
            throw new Exception($errorMsg);
        }
        
        // Parse response
        $responseData = json_decode($response, true);
        
        if (!isset($responseData['choices'][0]['message']['content'])) {
            throw new Exception(ERROR_INVALID_RESPONSE);
        }
        
        $aiResponse = $responseData['choices'][0]['message']['content'];
        
        // Return successful response
        echo json_encode([
            'success' => true,
            'response' => $aiResponse,
            'model' => AI_MODEL,
            'timestamp' => time()
        ]);
    }
    
} catch (Exception $e) {
    // Log error (in production, use proper logging)
    error_log('Chat API Error: ' . $e->getMessage());
    
    // Return error response
    if (!$isStreaming) {
        http_response_code(500);
        echo json_encode([
            'error' => $e->getMessage(),
            'success' => false
        ]);
    } else {
        echo "data: " . json_encode(['error' => $e->getMessage()]) . "\n\n";
        ob_flush();
        flush();
    }
}
