using iyixiGames.AI.Configurations;
using iyixiGames.AI.DTOs.DeepSeek;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Threading.Tasks;

namespace iyixiGames.AI.Services
{
    /// <summary>
    /// DeepSeek AI 服务的实现。
    /// </summary>
    public class DeepSeekService : IDeepSeekService
    {
private readonly HttpClient _httpClient;
        private readonly DeepSeekConfig _config;
        private readonly ILogger<DeepSeekService> _logger;

        public DeepSeekService(HttpClient httpClient, IOptions<DeepSeekConfig> config, ILogger<DeepSeekService> logger)
        {
            _httpClient = httpClient;
            _config = config.Value;
            _logger = logger;

            _httpClient.BaseAddress = new Uri(_config.BaseUrl);
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _config.ApiKey);
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }

        public async Task<DeepSeekChatCompletionResponse?> GetChatCompletionAsync(
            List<DeepSeekMessage> messages,
            string? model = null,
            int? maxTokens = null,
            double? temperature = null)
        {
            if (string.IsNullOrEmpty(_config.ApiKey))
            {
                _logger.LogError("DeepSeek API Key 未配置。");
                return null;
            }

            var requestBody = new DeepSeekChatCompletionRequest
            {
                Model = model ?? _config.Model,
                Messages = messages,
                MaxTokens = maxTokens,
                Temperature = temperature
            };

            HttpResponseMessage? response = null; // 声明 response 变量在 try 块外部

            try
            {
                _logger.LogInformation("正在调用 DeepSeek API: {BaseUrl}chat/completions", _config.BaseUrl);
                
                // 发送请求
                response = await _httpClient.PostAsJsonAsync("chat/completions", requestBody);

                // 检查响应是否成功，如果不是成功状态码，会抛出 HttpRequestException
                // 但此时 response 对象仍然有效，我们可以读取其内容
                response.EnsureSuccessStatusCode(); 

                var result = await response.Content.ReadFromJsonAsync<DeepSeekChatCompletionResponse>();
                _logger.LogInformation("DeepSeek API 调用成功。");
                return result;
            }
            catch (HttpRequestException httpEx) // 捕获 HttpRequestException
            {
                string errorContent = "无法获取响应内容。";
                if (response != null) // 如果 response 对象存在，尝试读取其内容
                {
                    try
                    {
                        errorContent = await response.Content.ReadAsStringAsync();
                    }
                    catch (Exception contentReadEx)
                    {
                        _logger.LogError(contentReadEx, "读取 DeepSeek API 错误响应内容时失败。");
                    }
                }
                
                // 使用 httpEx.StatusCode (在 .NET 5+ 可用) 或 默认值
                var statusCode = httpEx.StatusCode.HasValue ? $"HTTP {httpEx.StatusCode.Value}" : "未知";
                
                _logger.LogError(httpEx, "调用 DeepSeek API 失败：{StatusCode}. 响应内容: {ErrorContent}", statusCode, errorContent);
                return null;
            }
            catch (Exception ex) // 捕获其他通用异常
            {
                _logger.LogError(ex, "调用 DeepSeek API 时发生未知错误。");
                return null;
            }
        }

        public async Task<string?> GetTextResponseAsync(string prompt)
        {
            var messages = new List<DeepSeekMessage>
            {
                new DeepSeekMessage { Role = "user", Content = prompt }
            };

            var response = await GetChatCompletionAsync(messages);

            if (response?.Choices != null && response.Choices.Count > 0)
            {
                return response.Choices[0].Message.Content;
            }

            return null;
        }
    }
}