<?php

namespace App\Services;

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

class KnowledgeGraphService
{
    protected string $baseUrl;

    public function __construct()
    {
        // 从配置文件读取base_url，如果没有配置则使用容器服务名
        $this->baseUrl = config('services.knowledge_api.base_url', env('KNOWLEDGE_API_BASE', env('KNOWLEDGE_API_BASE_URL', 'http://localhost:5011')));
        $this->baseUrl = rtrim($this->baseUrl, '/');
    }

    /**
     * 获取知识点列表
     */
    public function listKnowledgePoints(int $page = 1, int $perPage = 100): array
    {
        try {
            $response = Http::timeout(10)
                ->withHeaders(['Accept' => 'application/json'])
                ->get($this->baseUrl . '/knowledge-points/', [
                    'page' => $page,
                    'per_page' => $perPage
                ]);

            if ($response->successful()) {
                $data = $response->json();
                $points = $data['data'] ?? $data ?? [];

                // 格式化知识点数据
                $formattedPoints = array_map(function($kp) {
                    return [
                        'id' => (string)($kp['id'] ?? $kp['kp_id'] ?? uniqid()),
                        'kp_code' => $kp['kp_code'] ?? $kp['kp_id'] ?? $kp['code'] ?? 'KP_UNKNOWN',
                        'cn_name' => $kp['cn_name'] ?? $kp['kp_name'] ?? $kp['name'] ?? $kp['kp_code'] ?? '未知知识点',
                        'category' => $kp['category'] ?? '数学',
                        'phase' => $kp['phase'] ?? '',
                        'grade' => $kp['grade'] ?? null,
                        'importance' => $kp['importance'] ?? 0,
                        'description' => $kp['description'] ?? '',
                    ];
                }, $points);

                // 返回标准格式：{data: [...], meta: {...}}
                return [
                    'data' => $formattedPoints,
                    'meta' => $data['meta'] ?? []
                ];
            }

            Log::warning('知识图谱API调用失败', [
                'status' => $response->status(),
                'url' => $this->baseUrl . '/knowledge-points',
                'response' => $response->json()
            ]);
        } catch (\Exception $e) {
            Log::error('获取知识点列表失败', [
                'error' => $e->getMessage()
            ]);
        }

        // 返回备用数据
        $fallback = $this->getFallbackKnowledgePoints();
        return [
            'data' => $fallback,
            'meta' => ['total' => count($fallback)]
        ];
    }

    /**
     * 根据知识点代码获取技能列表
     */
    public function getSkillsByKnowledgePoint(string $kpCode): array
    {
        try {
            $response = Http::timeout(10)
                ->withHeaders(['Accept' => 'application/json'])
                ->get($this->baseUrl . "/graph/node/{$kpCode}");

            if ($response->successful()) {
                $data = $response->json();
                $skills = $data['skills'] ?? [];

                return array_map(function($skill) {
                    return [
                        'code' => $skill['skill_code'] ?? '',
                        'name' => $skill['skill_name'] ?? '',
                        'weight' => $skill['weight'] ?? 0,
                    ];
                }, $skills);
            }

            Log::warning('获取技能列表失败', [
                'status' => $response->status(),
                'kp_code' => $kpCode
            ]);
        } catch (\Exception $e) {
            Log::error('获取技能列表异常', [
                'kp_code' => $kpCode,
                'error' => $e->getMessage()
            ]);
        }

        return [];
    }

    /**
     * 获取所有技能列表
     */
    public function listSkills(int $page = 1, int $perPage = 50): array
    {
        // ... (existing code)
        try {
            $response = Http::timeout(10)
                ->get($this->baseUrl . '/skills/', [
                    'page' => $page,
                    'per_page' => $perPage
                ]);

            if ($response->successful()) {
                $data = $response->json();
                $skills = $data['data'] ?? $data ?? [];

                // 格式化技能数据
                return array_map(function($skill) {
                    return [
                        'id' => (string)($skill['id'] ?? $skill['skill_code'] ?? uniqid()),
                        'code' => $skill['skill_code'] ?? $skill['code'] ?? 'SK_UNKNOWN',
                        'name' => $skill['skill_name'] ?? $skill['name'] ?? $skill['skill_code'] ?? '未知技能',
                        'category' => $skill['skill_type'] ?? $skill['category'] ?? '基础技能'
                    ];
                }, $skills);
            }

            Log::warning('技能API调用失败', [
                'status' => $response->status()
            ]);
        } catch (\Exception $e) {
            Log::error('获取技能列表失败', [
                'error' => $e->getMessage()
            ]);
        }

        // 返回备用数据
        return $this->getFallbackSkills();
    }

    /**
     * 获取关联关系列表
     */
    public function listRelations(int $page = 1, int $perPage = 100): array
    {
        try {
            $response = Http::timeout(10)
                ->get($this->baseUrl . '/graph/relations', [
                    'page' => $page,
                    'per_page' => $perPage
                ]);

            if ($response->successful()) {
                $data = $response->json();
                $relations = $data['data'] ?? [];
                
                return array_map(function($rel) {
                    return [
                        'source_kp' => $rel['source'] ?? $rel['source_kp'] ?? '',
                        'target_kp' => $rel['target'] ?? $rel['target_kp'] ?? '',
                        'relation_type' => $rel['relation_type'] ?? 'PREREQUISITE',
                        'relation_direction' => $rel['relation_direction'] ?? 'DOWNSTREAM',
                        'weight' => $rel['weight'] ?? 0,
                        'description' => $rel['description'] ?? '',
                    ];
                }, $relations);
            }

            Log::warning('获取关联关系列表失败', [
                'status' => $response->status()
            ]);
        } catch (\Exception $e) {
            Log::error('获取关联关系列表异常', [
                'error' => $e->getMessage()
            ]);
        }

        return [];
    }

    /**
     * 导出完整图谱数据 (用于可视化)
     */
    public function exportGraph(): array
    {
        try {
            $response = Http::timeout(30)
                ->get($this->baseUrl . '/graph/export');

            if ($response->successful()) {
                return $response->json();
            }

            Log::warning('导出图谱数据失败', [
                'status' => $response->status()
            ]);
        } catch (\Exception $e) {
            Log::error('导出图谱数据异常', [
                'error' => $e->getMessage()
            ]);
        }

        return ['nodes' => [], 'edges' => []];
    }

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

            return $response->successful();
        } catch (\Exception $e) {
            Log::error('知识图谱服务健康检查失败', [
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }

    /**
     * 获取备用知识点数据
     */
    private function getFallbackKnowledgePoints(): array
    {
        return [
            ['id' => 'kp_1', 'kp_code' => 'KP1001', 'cn_name' => '因式分解基础', 'category' => '数学', 'phase' => '初中', 'importance' => 5, 'description' => ''],
            ['id' => 'kp_2', 'kp_code' => 'KP1002', 'cn_name' => '提取公因式', 'category' => '数学', 'phase' => '初中', 'importance' => 5, 'description' => ''],
            ['id' => 'kp_3', 'kp_code' => 'KP1003', 'cn_name' => '平方差公式', 'category' => '数学', 'phase' => '初中', 'importance' => 5, 'description' => ''],
            ['id' => 'kp_4', 'kp_code' => 'KP1004', 'cn_name' => '完全平方公式', 'category' => '数学', 'phase' => '初中', 'importance' => 5, 'description' => ''],
            ['id' => 'kp_5', 'kp_code' => 'KP1005', 'cn_name' => '分组分解法', 'category' => '数学', 'phase' => '初中', 'importance' => 4, 'description' => ''],
            ['id' => 'kp_6', 'kp_code' => 'KP1006', 'cn_name' => '十字相乘法', 'category' => '数学', 'phase' => '初中', 'importance' => 5, 'description' => ''],
            ['id' => 'kp_7', 'kp_code' => 'KP1007', 'cn_name' => '有理数运算', 'category' => '数学', 'phase' => '初中', 'importance' => 5, 'description' => ''],
            ['id' => 'kp_8', 'kp_code' => 'KP1008', 'cn_name' => '一元二次方程', 'category' => '数学', 'phase' => '初中', 'importance' => 5, 'description' => ''],
            ['id' => 'kp_9', 'kp_code' => 'KP1009', 'cn_name' => '不等式', 'category' => '数学', 'phase' => '初中', 'importance' => 4, 'description' => ''],
            ['id' => 'kp_10', 'kp_code' => 'KP1010', 'cn_name' => '函数基础', 'category' => '数学', 'phase' => '初中', 'importance' => 5, 'description' => ''],
        ];
    }

    /**
     * 获取备用技能数据
     */
    private function getFallbackSkills(): array
    {
        return [
            ['id' => 'sk_1', 'code' => 'SK001', 'name' => '计算能力', 'category' => '基础技能'],
            ['id' => 'sk_2', 'code' => 'SK002', 'name' => '逻辑推理', 'category' => '思维技能'],
            ['id' => 'sk_3', 'code' => 'SK003', 'name' => '模式识别', 'category' => '认知技能'],
            ['id' => 'sk_4', 'code' => 'SK004', 'name' => '代数运算', 'category' => '专业技能'],
            ['id' => 'sk_5', 'code' => 'SK005', 'name' => '解题能力', 'category' => '专业技能'],
            ['id' => 'sk_6', 'code' => 'SK006', 'name' => '分析能力', 'category' => '思维技能'],
            ['id' => 'sk_7', 'code' => 'SK007', 'name' => '抽象思维', 'category' => '高级技能'],
            ['id' => 'sk_8', 'code' => 'SK008', 'name' => '创新思维', 'category' => '高级技能'],
        ];
    }
    /**
     * 导入知识图谱数据
     */
    public function importGraph(array $treeData, array $edgesData): bool
    {
        try {
            $response = Http::timeout(60) // 导入可能耗时较长
                ->post($this->baseUrl . '/import/graph', [
                    'tree_data' => $treeData,
                    'edges_data' => $edgesData
                ]);

            if ($response->successful()) {
                $result = $response->json();
                Log::info('知识图谱导入成功', [
                    'response' => $result
                ]);
                return true;
            }

            $errorBody = $response->body();
            Log::error('知识图谱导入失败', [
                'status' => $response->status(),
                'body' => $errorBody
            ]);

            // 尝试解析错误信息
            try {
                $errorData = json_decode($errorBody, true);
                if (isset($errorData['detail'])) {
                    throw new \Exception('API错误: ' . $errorData['detail']);
                }
            } catch (\Exception $e) {
                // 忽略JSON解析错误，使用原始错误信息
            }

            throw new \Exception("API请求失败 (HTTP {$response->status()}): {$errorBody}");
        } catch (\Exception $e) {
            Log::error('知识图谱导入异常', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            // 重新抛出异常，让上层处理
            throw $e;
        }
    }

    /**
     * 获取单个知识点详情
     */
    public function getKnowledgePoint(string $code): ?array
    {
        try {
            $response = Http::timeout(10)
                ->get($this->baseUrl . "/knowledge-points/{$code}");

            if ($response->successful()) {
                return $response->json();
            }
        } catch (\Exception $e) {
            Log::error('获取知识点详情失败', ['error' => $e->getMessage()]);
        }
        return null;
    }

    /**
     * 创建知识点
     */
    public function createKnowledgePoint(array $data): bool
    {
        try {
            $response = Http::timeout(10)
                ->post($this->baseUrl . '/knowledge-points/', $data);

            return $response->successful();
        } catch (\Exception $e) {
            Log::error('创建知识点失败', ['error' => $e->getMessage()]);
            return false;
        }
    }

    /**
     * 更新知识点
     */
    public function updateKnowledgePoint(string $code, array $data): bool
    {
        try {
            $response = Http::timeout(10)
                ->patch($this->baseUrl . "/knowledge-points/{$code}", $data);

            return $response->successful();
        } catch (\Exception $e) {
            Log::error('更新知识点失败', ['error' => $e->getMessage()]);
            return false;
        }
    }

    /**
     * 删除知识点
     */
    public function deleteKnowledgePoint(string $code): bool
    {
        try {
            $response = Http::timeout(10)
                ->delete($this->baseUrl . "/knowledge-points/{$code}");

            return $response->successful();
        } catch (\Exception $e) {
            Log::error('删除知识点失败', ['error' => $e->getMessage()]);
            return false;
        }
    }

    /**
     * 获取学生的知识点掌握度数据
     */
    public function getStudentMastery($studentId)
    {
        try {
            // 这里应该调用LearningAnalytics API
            $response = Http::timeout(10)
                ->get("http://localhost:5010/api/mastery/{$studentId}");

            if ($response->successful()) {
                return $response->json();
            }
        } catch (\Exception $e) {
            Log::warning('获取学生掌握度数据失败', [
                'student_id' => $studentId,
                'error' => $e->getMessage(),
            ]);
        }

        // 返回模拟数据
        return [
            'masteries' => [
                ['kp_code' => 'R01', 'mastery_level' => 0.85, 'confidence_level' => 0.8],
                ['kp_code' => 'R02', 'mastery_level' => 0.72, 'confidence_level' => 0.75],
                ['kp_code' => 'R03', 'mastery_level' => 0.65, 'confidence_level' => 0.7],
                ['kp_code' => 'R04', 'mastery_level' => 0.45, 'confidence_level' => 0.65],
                ['kp_code' => 'R05', 'mastery_level' => 0.30, 'confidence_level' => 0.6],
            ]
        ];
    }

    /**
     * 获取学生掌握度统计信息
     */
    public function getStudentStatistics($studentId)
    {
        try {
            $response = Http::timeout(10)
                ->get("http://localhost:5010/api/mastery/{$studentId}/statistics");

            if ($response->successful()) {
                return $response->json();
            }
        } catch (\Exception $e) {
            Log::warning('获取学生统计信息失败', [
                'student_id' => $studentId,
                'error' => $e->getMessage(),
            ]);
        }

        // 返回模拟数据
        return [
            'total_knowledge_points' => 5,
            'average_mastery' => 0.594,
            'high_mastery_count' => 1,
            'medium_mastery_count' => 2,
            'low_mastery_count' => 2,
        ];
    }

    /**
     * 获取掌握度颜色
     */
    public function getMasteryColor($mastery)
    {
        if ($mastery >= 0.8) return '#10b981'; // 绿色
        if ($mastery >= 0.6) return '#3b82f6'; // 蓝色
        if ($mastery >= 0.4) return '#f59e0b'; // 黄色
        if ($mastery >= 0.2) return '#f97316'; // 橙色
        return '#ef4444'; // 红色
    }
}
