package threads_account

import (
	"context"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	liboutreach "haixun-backend/internal/library/outreach"
	libownpost "haixun-backend/internal/library/ownpost"
	domai "haixun-backend/internal/model/ai/domain/usecase"
	aiusecase "haixun-backend/internal/model/ai/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GenerateOwnPostReplyDraftLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGenerateOwnPostReplyDraftLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GenerateOwnPostReplyDraftLogic {
	return &GenerateOwnPostReplyDraftLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GenerateOwnPostReplyDraftLogic) GenerateOwnPostReplyDraft(
	req *types.GenerateOwnPostReplyDraftHandlerReq,
) (*types.GenerateOwnPostReplyDraftData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	if req.MediaID == "" {
		return nil, app.For(code.ThreadsAccount).InputMissingRequired("media_id is required")
	}

	account, err := l.svcCtx.ThreadsAccount.Get(l.ctx, tenantID, uid, req.ID)
	if err != nil {
		return nil, err
	}

	credential, err := l.svcCtx.ThreadsAccount.ResolveMemberAiCredential(l.ctx, tenantID, uid)
	if err != nil {
		return nil, err
	}
	providerID, err := aiusecase.MapWorkerProvider(credential.Provider)
	if err != nil {
		return nil, err
	}

	personaID := strings.TrimSpace(req.PersonaID)
	if personaID == "" {
		personaID = strings.TrimSpace(account.PersonaID)
	}
	if personaID == "" {
		return nil, app.For(code.ThreadsAccount).InputMissingRequired("請先選擇人設（persona_id）")
	}
	persona, err := l.svcCtx.Persona.Get(l.ctx, tenantID, uid, personaID)
	if err != nil {
		return nil, err
	}
	personaBlock := liboutreach.FormatVoicePersonaBlock(persona)
	if strings.TrimSpace(personaBlock) == "" {
		return nil, app.For(code.ThreadsAccount).InputMissingRequired("所選人設尚未填寫語氣或 8D 風格，請先到人設頁補齊")
	}

	accountName := account.DisplayName
	if accountName == "" {
		accountName = account.Username
	}

	text, err := libownpost.GenerateReplyDraft(l.ctx, l.svcCtx.AI, domai.GenerateRequest{
		Provider: providerID,
		Model:    credential.Model,
		Credential: domai.Credential{
			APIKey: credential.APIKey,
		},
	}, libownpost.ReplyDraftInput{
		AccountName:     accountName,
		PersonaBlock:    personaBlock,
		PostText:        req.PostText,
		ReplyText:       req.ReplyText,
		ReplyToID:       req.ReplyToID,
		ThreadPostText:  req.ThreadPostText,
		ParentReplyText: req.ParentReplyText,
	})
	if err != nil {
		return nil, app.For(code.AI).SvcThirdParty("AI 回覆草稿生成失敗：" + err.Error())
	}
	return &types.GenerateOwnPostReplyDraftData{Text: text}, nil
}
