<?php

namespace App\Services;

use App\Models\SystemException;
use Illuminate\Support\Facades\Http;
use Slowlyo\OwlAdmin\Services\AdminService;

class SystemExceptionService extends AdminService
{
    protected string $modelName = SystemException::class;

    /**
     * 使用 AI 分析异常
     */
    public function analyze($id)
    {
        $exception = $this->query()->findOrFail($id);

        // 调用免费的 AI API (这里以 ChatGPT 为例)
        $response = Http::post('https://api.openai.com/v1/chat/completions', [
            'model' => 'gpt-3.5-turbo',
            'messages' => [
                [
                    'role' => 'system',
                    'content' => '你是一个PHP专家,请分析这个异常并提供解决方案。'
                ],
                [
                    'role' => 'user',
                    'content' => "异常类型: {$exception->type}\n异常信息: {$exception->message}\n文件: {$exception->file}:{$exception->line}\n堆栈信息: {$exception->trace}"
                ]
            ]
        ], [
            'Authorization' => 'Bearer ' . config('services.openai.api_key')
        ]);

        if ($response->successful()) {
            $solution = $response->json('choices.0.message.content');

            $exception->update([
                'status' => 1, // 处理中
                'solution' => $solution
            ]);

            return [
                'status' => true,
                'message' => 'AI分析完成'
            ];
        }

        return [
            'status' => false,
            'message' => 'AI分析失败: ' . $response->body()
        ];
    }

    /**
     * 批量AI分析
     */
    public function batchAnalyze()
    {
        $exceptions = $this->query()->where('status', 0)->limit(10)->get();

        foreach ($exceptions as $exception) {
            $this->analyze($exception->id);
        }

        return [
            'status' => true,
            'message' => '批量分析任务已提交'
        ];
    }

    /**
     * 标记为已处理
     */
    public function markHandled($id)
    {
        $this->query()->findOrFail($id)->update([
            'status' => 2,
            'handler' => auth()->user()->name,
            'handled_at' => now()
        ]);

        return [
            'status' => true,
            'message' => '已标记为处理完成'
        ];
    }

    /**
     * 标记为忽略
     */
    public function ignore($id)
    {
        $this->query()->findOrFail($id)->update([
            'status' => 3,
            'handler' => auth()->user()->name,
            'handled_at' => now()
        ]);

        return [
            'status' => true,
            'message' => '已标记为忽略'
        ];
    }
}