using System.Collections.Concurrent;
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using OpenAI.Chat;
using Volo.Abp.Application.Services;
using Volo.Abp.Users;
using Yi.Framework.AiHub.Application.Contracts.Dtos;
using Yi.Framework.AiHub.Domain.Entities;
using Yi.Framework.AiHub.Domain.Entities.Model;
using Yi.Framework.AiHub.Domain.Extensions;
using Yi.Framework.AiHub.Domain.Managers;
using Yi.Framework.AiHub.Domain.Shared.Dtos;
using Yi.Framework.Rbac.Application.Contracts.IServices;
using Yi.Framework.Rbac.Domain.Shared.Dtos;
using Yi.Framework.SqlSugarCore.Abstractions;

namespace Yi.Framework.AiHub.Application.Services;

/// <summary>
/// ai服务
/// </summary>
public class AiChatService : ApplicationService
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
    private readonly AiBlacklistManager _aiBlacklistManager;
    private readonly ILogger<AiChatService> _logger;
    private readonly AiGateWayManager _aiGateWayManager;

    public AiChatService(IHttpContextAccessor httpContextAccessor,
        AiBlacklistManager aiBlacklistManager,
        ISqlSugarRepository<AiModelEntity> aiModelRepository,
        ILogger<AiChatService> logger, AiGateWayManager aiGateWayManager)
    {
        _httpContextAccessor = httpContextAccessor;
        _aiBlacklistManager = aiBlacklistManager;
        _aiModelRepository = aiModelRepository;
        _logger = logger;
        _aiGateWayManager = aiGateWayManager;
    }


    /// <summary>
    /// 查询已登录的账户信息
    /// </summary>
    /// <returns></returns>
    [Route("ai-chat/account")]
    [Authorize]
    public async Task<UserRoleMenuDto> GetAsync()
    {
        var accountService = LazyServiceProvider.GetRequiredService<IAccountService>();
        var output = await accountService.GetAsync();
        return output;
    }

    /// <summary>
    /// 获取模型列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<ModelGetListOutput>> GetModelAsync()
    {
        var output = await _aiModelRepository._DbQueryable
            .OrderByDescending(x => x.OrderNum)
            .Select(x => new ModelGetListOutput
            {
                Id = x.Id,
                Category = "chat",
                ModelId = x.ModelId,
                ModelName = x.Name,
                ModelDescribe = x.Description,
                ModelPrice = 0,
                ModelType = "1",
                ModelShow = "0",
                SystemPrompt = null,
                ApiHost = null,
                ApiKey = null,
                Remark = x.Description
            }).ToListAsync();
        return output;
    }


    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="input"></param>
    /// <param name="cancellationToken"></param>
    public async Task PostSendAsync(SendMessageInput input, CancellationToken cancellationToken)
    {
        //除了免费模型，其他的模型都要校验
        if (!input.Model.Contains("DeepSeek-R1"))
        {
            //有token，需要黑名单校验
            if (CurrentUser.IsAuthenticated)
            {
                await _aiBlacklistManager.VerifiyAiBlacklist(CurrentUser.GetId());
                if (!CurrentUser.IsAiVip())
                {
                    throw new UserFriendlyException("该模型需要VIP用户才能使用，请购买VIP后重新登录重试");
                }
            }
            else
            {
                throw new UserFriendlyException("未登录用户，只能使用未加速的DeepSeek-R1，请登录后重试");
            }
        }

        var history = new List<ChatMessage>();
        foreach (var aiChatContextDto in input.Messages)
        {
            if (aiChatContextDto.Role == "assistant")
            {
                history.Add(ChatMessage.CreateAssistantMessage(aiChatContextDto.Content));
            }
            else if (aiChatContextDto.Role == "user")
            {
                history.Add(ChatMessage.CreateUserMessage(aiChatContextDto.Content));
            }
        }

        //ai网关代理httpcontext
        await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input.Model, history,
            CurrentUser.Id, input.SessionId, cancellationToken);
    }
}