<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class MathRecSysService
{
    private string $baseUrl;
    private int $timeout;
    private string $apiKey;

    public function __construct()
    {
        $this->baseUrl = config('services.mathrecsys.base_url', 'http://localhost:5010');
        $this->timeout = config('services.mathrecsys.timeout', 30);
        $this->apiKey = config('services.mathrecsys.api_key', '');
    }

    /**
     * 智能融合分析 - 核心智能分析引擎
     *
     * @param array $data 分析数据
     * @return array
     */
    public function smartAnalyze(array $data): array
    {
        try {
            Log::info('调用MathRecSys智能分析', ['data' => $data]);

            $response = Http::timeout($this->timeout)
                ->withHeaders([
                    'Content-Type' => 'application/json',
                    'Accept' => 'application/json',
                ])
                ->post($this->baseUrl . '/api/fusion/smart-analyze', $data);

            if ($response->failed()) {
                Log::error('MathRecSys智能分析失败', [
                    'status' => $response->status(),
                    'body' => $response->body()
                ]);
                throw new \Exception('智能分析失败: ' . $response->body());
            }

            $result = $response->json();
            Log::info('MathRecSys智能分析成功', ['result' => $result]);

            return $result;

        } catch (\Exception $e) {
            Log::error('MathRecSys智能分析异常', ['error' => $e->getMessage()]);
            throw $e;
        }
    }

    /**
     * 获取学生能力画像
     *
     * @param string $studentId 学生ID
     * @return array
     */
    public function getStudentProfile(string $studentId): array
    {
        try {
            Log::info('获取学生能力画像', ['student_id' => $studentId]);

            $response = Http::timeout($this->timeout)
                ->get($this->baseUrl . '/api/student/profile/' . $studentId);

            if ($response->failed()) {
                Log::error('获取学生画像失败', [
                    'status' => $response->status(),
                    'body' => $response->body()
                ]);
                throw new \Exception('获取学生画像失败');
            }

            $result = $response->json();
            Log::info('获取学生画像成功', ['result' => $result]);

            return $result;

        } catch (\Exception $e) {
            Log::error('获取学生画像异常', ['error' => $e->getMessage()]);
            throw $e;
        }
    }

    /**
     * 获取班级整体分析
     *
     * @param string $classId 班级ID
     * @return array
     */
    public function getClassAnalysis(string $classId): array
    {
        try {
            Log::info('获取班级整体分析', ['class_id' => $classId]);

            $response = Http::timeout($this->timeout)
                ->get($this->baseUrl . '/api/analysis/class/' . $classId);

            if ($response->failed()) {
                throw new \Exception('获取班级分析失败');
            }

            $result = $response->json();
            Log::info('获取班级分析成功', ['result' => $result]);

            return $result;

        } catch (\Exception $e) {
            Log::error('获取班级分析异常', ['error' => $e->getMessage()]);
            throw $e;
        }
    }

    /**
     * 获取知识图谱
     *
     * @param string|null $focus 焦点知识点
     * @return array
     */
    public function getKnowledgeGraph(?string $focus = null): array
    {
        try {
            $params = [];
            if ($focus) {
                $params['focus'] = $focus;
            }

            Log::info('获取知识图谱', $params);

            $response = Http::timeout($this->timeout)
                ->get($this->baseUrl . '/api/knowledge/graph', $params);

            if ($response->failed()) {
                throw new \Exception('获取知识图谱失败');
            }

            $result = $response->json();
            Log::info('获取知识图谱成功', ['nodes_count' => count($result['nodes'] ?? [])]);

            return $result;

        } catch (\Exception $e) {
            Log::error('获取知识图谱异常', ['error' => $e->getMessage()]);
            throw $e;
        }
    }

    /**
     * 获取知识点详情
     *
     * @param string $kpId 知识点ID
     * @return array
     */
    public function getKnowledgePoint(string $kpId): array
    {
        try {
            Log::info('获取知识点详情', ['kp_id' => $kpId]);

            $response = Http::timeout($this->timeout)
                ->get($this->baseUrl . '/api/knowledge/point/' . $kpId);

            if ($response->failed()) {
                throw new \Exception('获取知识点详情失败');
            }

            return $response->json();

        } catch (\Exception $e) {
            Log::error('获取知识点详情异常', ['error' => $e->getMessage()]);
            throw $e;
        }
    }

    /**
     * 获取题目推荐
     *
     * @param string $studentId 学生ID
     * @param array $options 选项
     * @return array
     */
    public function getRecommendations(string $studentId, array $options = []): array
    {
        try {
            $data = array_merge(['student_id' => $studentId], $options);

            Log::info('获取题目推荐', $data);

            $response = Http::timeout($this->timeout)
                ->post($this->baseUrl . '/api/recommend', $data);

            if ($response->failed()) {
                throw new \Exception('获取推荐失败');
            }

            $result = $response->json();
            Log::info('获取推荐成功', ['count' => count($result['data'] ?? [])]);

            return $result;

        } catch (\Exception $e) {
            Log::error('获取推荐异常', ['error' => $e->getMessage()]);
            throw $e;
        }
    }

    /**
     * 更新学生掌握度
     *
     * @param string $studentId 学生ID
     * @param array $masteryData 掌握度数据
     * @return array
     */
    public function updateMastery(string $studentId, array $masteryData): array
    {
        try {
            Log::info('更新学生掌握度', [
                'student_id' => $studentId,
                'data' => $masteryData
            ]);

            $response = Http::timeout($this->timeout)
                ->put($this->baseUrl . '/api/student/mastery/' . $studentId, $masteryData);

            if ($response->failed()) {
                throw new \Exception('更新掌握度失败');
            }

            return $response->json();

        } catch (\Exception $e) {
            Log::error('更新掌握度异常', ['error' => $e->getMessage()]);
            throw $e;
        }
    }

    /**
     * 获取学习轨迹
     *
     * @param string $studentId 学生ID
     * @param string|null $startDate 开始日期
     * @param string|null $endDate 结束日期
     * @return array
     */
    public function getLearningTrajectory(string $studentId, ?string $startDate = null, ?string $endDate = null): array
    {
        try {
            $params = ['student_id' => $studentId];
            if ($startDate) {
                $params['start_date'] = $startDate;
            }
            if ($endDate) {
                $params['end_date'] = $endDate;
            }

            Log::info('获取学习轨迹', $params);

            $response = Http::timeout($this->timeout)
                ->get($this->baseUrl . '/api/student/trajectory', $params);

            if ($response->failed()) {
                throw new \Exception('获取学习轨迹失败');
            }

            return $response->json();

        } catch (\Exception $e) {
            Log::error('获取学习轨迹异常', ['error' => $e->getMessage()]);
            throw $e;
        }
    }

    /**
     * 获取薄弱知识点
     *
     * @param string $studentId 学生ID
     * @return array
     */
    public function getWeakPoints(string $studentId): array
    {
        try {
            Log::info('获取薄弱知识点', ['student_id' => $studentId]);

            $response = Http::timeout($this->timeout)
                ->get($this->baseUrl . '/api/student/weak-points/' . $studentId);

            if ($response->failed()) {
                throw new \Exception('获取薄弱知识点失败');
            }

            return $response->json();

        } catch (\Exception $e) {
            Log::error('获取薄弱知识点异常', ['error' => $e->getMessage()]);
            throw $e;
        }
    }

    /**
     * 获取学习建议
     *
     * @param string $studentId 学生ID
     * @param array $options 选项
     * @return array
     */
    public function getLearningSuggestions(string $studentId, array $options = []): array
    {
        try {
            $data = array_merge(['student_id' => $studentId], $options);

            Log::info('获取学习建议', $data);

            $response = Http::timeout($this->timeout)
                ->post($this->baseUrl . '/api/suggestions', $data);

            if ($response->failed()) {
                throw new \Exception('获取学习建议失败');
            }

            return $response->json();

        } catch (\Exception $e) {
            Log::error('获取学习建议异常', ['error' => $e->getMessage()]);
            throw $e;
        }
    }

    /**
     * 检查服务健康状态
     *
     * @return bool
     */
    public function isHealthy(): bool
    {
        try {
            $response = Http::timeout(5)
                ->get($this->baseUrl . '/health');

            return $response->successful() && ($response->json()['status'] ?? '') === 'ok';
        } catch (\Exception $e) {
            Log::warning('MathRecSys服务健康检查失败', ['error' => $e->getMessage()]);
            return false;
        }
    }
}
