package ai

import (
	"context"

	libprompt "haixun-backend/internal/library/prompt"
	domai "haixun-backend/internal/model/ai/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

type IslanderChatStreamLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewIslanderChatStreamLogic(ctx context.Context, svcCtx *svc.ServiceContext) *IslanderChatStreamLogic {
	return &IslanderChatStreamLogic{ctx: ctx, svcCtx: svcCtx}
}

func (l *IslanderChatStreamLogic) ChatStream(req *types.IslanderChatReq) (<-chan domai.StreamEvent, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	credential, err := l.svcCtx.ThreadsAccount.ResolveMemberAiCredential(l.ctx, tenantID, uid)
	if err != nil {
		return nil, err
	}
	system, err := libprompt.IslanderSystem(req.Context)
	if err != nil {
		return nil, err
	}
	return l.svcCtx.AI.StreamText(l.ctx, toCredentialGenerateRequest(req.Messages, credential, system))
}
