<?php


namespace App\Http\Services;

use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

class DeepSeekService extends BaseService
{
    public function chatCompletionsByAlphaChain($textInfo) {
        // 确保实时输出缓冲
        ini_set('output_buffering', 'off');
        ini_set('zlib.output_compression', 0);
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        header('X-Accel-Buffering: no');

        $client = new Client();

        // DeepSeek API参数（根据实际文档调整）
        $apiKey = env('DS_API_KEY');
        $url = env('DS_API_URL');
        $data = [
            'model' => 'deepseek-chat',
            'messages' => [['role' => 'user', 'content' => $textInfo['text']]],
            'stream' => true  // 关键：启用流式模式
        ];

        try {
            $response = $client->post($url, [
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Bearer ' . $apiKey
                ],
                'json' => $data,
                'stream' => true  // Guzzle启用流式接收
            ]);

            $body = $response->getBody();

            // 逐块读取流式数据
            while (!$body->eof()) {
                $chunk = $body->read(1024);  // 读取数据块

                // 处理数据格式（示例按SSE格式处理）
                foreach (explode("\n", $chunk) as $line) {
                    $line = trim($line);
                    if (strpos($line, 'data: ') === 0) {
                        $data = substr($line, 6);
                        if ($data === '[DONE]') break;

                        $json = json_decode($data, true);
                        // 提取内容（根据实际响应结构调整）
                        $content = $json['choices'][0]['delta']['content'] ?? '';
                        echo "data: " . json_encode(['content' => $content], JSON_UNESCAPED_UNICODE) . "\n\n";
                        ob_flush();
                        flush();
                    }
                }

                if (connection_aborted()) break;  // 客户端断开连接时终止
            }
        } catch (Exception $e) {
            echo "data: " . json_encode(['error' => $e->getMessage()]) . "\n\n";
            ob_flush();
            flush();
        }

    }



}