package biz

import (
	"ai_scheduler/internal/data/constants"
	errorcode "ai_scheduler/internal/data/error"
	"ai_scheduler/internal/data/impl"
	"ai_scheduler/internal/data/model"
	"ai_scheduler/internal/entitys"
	"ai_scheduler/internal/pkg/util"
	"context"
	"time"

	"github.com/gofiber/fiber/v2/utils"

	"ai_scheduler/internal/config"
)

type SessionBiz struct {
	sessionRepo *impl.SessionImpl
	sysRepo     *impl.SysImpl
	chatHisRepo *impl.ChatHisImpl

	conf *config.Config
}

func NewSessionBiz(conf *config.Config, sessionImpl *impl.SessionImpl, sysImpl *impl.SysImpl, chatImpl *impl.ChatHisImpl) *SessionBiz {
	return &SessionBiz{
		sessionRepo: sessionImpl,
		sysRepo:     sysImpl,
		chatHisRepo: chatImpl,
		conf:        conf,
	}
}

// InitSession 初始化会话 ，当天存在则返回会话,如果不存在则创建一个
func (s *SessionBiz) SessionInit(ctx context.Context, req *entitys.SessionInitRequest) (result *entitys.SessionInitResponse, err error) {

	// 获取系统配置
	sysConfig, err := s.GetSysConfig(req.SysId)
	if err != nil {
		return
	}
	result = &entitys.SessionInitResponse{
		Chat: make([]entitys.ChatHistory, 0),
	}

	// 获取 当天的最新session
	t := time.Now().Truncate(24 * time.Hour)
	session, has, err := s.sessionRepo.Take(
		s.sessionRepo.WithUserId(req.UserId), // 条件：用户ID
		s.sessionRepo.WithStartTime(t),       // 条件：会话开始时间
		s.sysRepo.WithSysId(sysConfig.SysID),
		s.sessionRepo.OrderByDesc("create_at"), // 条件：系统ID
	)
	if err != nil {
		return
	}
	if !has {
		// 不存在，创建一个
		session, err = s.CreateNew(sysConfig.SysID, req)
		if err != nil {
			return nil, err
		}
		chat := entitys.ChatHistory{
			SessionID: session.SessionID,
			Role:      constants.RoleSystem,
			Content:   sysConfig.Prologue,
		}
		result.Chat = append(result.Chat, chat)
		result.SessionId = session.SessionID
		result.Prologue = sysConfig.Prologue

		// 开场白写入会话历史
		//s.chatRepo.AsyncCreate(ctx, model.AiChatHi{
		//	SessionID: chat.SessionID,
		//	Role:      chat.Role.String(),
		//	Content:   chat.Content,
		//})

	} else {
		result.SessionId = session.SessionID
		result.Prologue = sysConfig.Prologue
		// 存在，返回会话历史
		var chatList []model.AiChatHi
		chatList, err = s.chatHisRepo.FindAll(
			s.chatHisRepo.WithSessionId(session.SessionID),      // 条件：会话ID
			s.chatHisRepo.OrderByDesc("create_at"),              // 排序：按创建时间降序
			s.chatHisRepo.WithLimit(constants.ChatHistoryLimit), // 限制返回条数
		)
		if err != nil {
			return
		}

		// 转换为 entitys.ChatHistory 类型
		for _, chat := range chatList {
			result.Chat = append(result.Chat, []entitys.ChatHistory{
				{
					SessionID: chat.SessionID,
					Role:      constants.RoleUser,
					Content:   chat.Ques,
					Prologue:  sysConfig.Prologue,
				},
				{
					SessionID: chat.SessionID,
					Role:      constants.RoleAssistant,
					Content:   chat.Ans,
					Prologue:  sysConfig.Prologue,
				},
			}...)
		}
	}

	return
}

func (s *SessionBiz) GetSysConfig(sysId string) (model.AiSy, error) {
	sysConfig, has, err := s.sysRepo.FindOne(s.sysRepo.WithSysId(sysId))
	if err != nil {
		return sysConfig, err
	} else if !has {
		err = errorcode.SysNotFound
		return sysConfig, err
	}
	return sysConfig, nil
}

func (s *SessionBiz) CreateNew(sysID int32, req *entitys.SessionInitRequest) (model.AiSession, error) {
	session := model.AiSession{
		SysID:      sysID,
		SessionID:  utils.UUID(),
		UserID:     req.UserId,
		UserName:   req.UserName,
		DingUserId: req.DingUserId,
	}
	err := s.sessionRepo.Create(&session)
	if err != nil {
		return session, err
	}
	return session, nil
}

// SessionList 会话列表
func (s *SessionBiz) SessionList(ctx context.Context, req *entitys.SessionListRequest) (list []model.AiSession, err error) {

	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 10
	}

	list, err = s.sessionRepo.FindAll(
		s.sessionRepo.WithUserId(req.UserId),                // 条件：用户ID
		s.sessionRepo.WithSysId(req.SysId),                  // 条件：系统ID
		s.sessionRepo.WithDeleteAt(),                        // 条件：未删除
		s.sessionRepo.PaginateScope(req.Page, req.PageSize), // 分页
		s.sessionRepo.OrderByDesc("create_at"),              // 排序：按创建时间降序
	)

	return
}

// DeleteSession 删除会话
func (s *SessionBiz) DeleteSession(ctx context.Context, req *entitys.SessionDeleteRequest) error {
	err := s.sessionRepo.Update(
		&model.AiSession{
			DeleteAt: util.AnyToPoint(time.Now()), // 设置删除时间
		},
		s.sessionRepo.WithSessionId(req.SessionId), // 条件：会话ID
	)
	if err != nil {
		return err
	}
	return nil
}

// RenameSession 会话重命名
func (s *SessionBiz) RenameSession(ctx context.Context, req *entitys.SessionRenameRequest) error {
	err := s.sessionRepo.Update(
		&model.AiSession{
			Title: req.NewName, // 设置会话名称
		},
		s.sessionRepo.WithSessionId(req.SessionId), // 条件：会话ID
	)
	if err != nil {
		return err
	}
	return nil
}
