package persona

import (
	"context"
	"fmt"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	libpersonacopy "haixun-backend/internal/library/personacopy"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

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

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

func (l *GeneratePersonaTopicMatrixLogic) GeneratePersonaTopicMatrix(req *types.GeneratePersonaTopicMatrixHandlerReq) (*types.GeneratePersonaTopicMatrixData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	personaID := strings.TrimSpace(req.ID)
	topic := strings.TrimSpace(req.Topic)
	if topic == "" {
		return nil, app.For(code.Persona).InputMissingRequired("topic is required")
	}

	created, err := libpersonacopy.RunTopicMatrix(l.ctx, libpersonacopy.TopicMatrixDeps{
		Persona:        l.svcCtx.Persona,
		CopyDraft:      l.svcCtx.CopyDraft,
		ContentOps:     l.svcCtx.ContentOps,
		ThreadsAccount: l.svcCtx.ThreadsAccount,
		Placement:      l.svcCtx.Placement,
		AI:             l.svcCtx.AI,
	}, libpersonacopy.TopicMatrixInput{
		TenantID:      tenantID,
		OwnerUID:      uid,
		PersonaID:     personaID,
		ContentPlanID: req.ContentPlanID,
		Topic:         topic,
		Brief:         req.Brief,
		UseWebSearch:  req.UseWebSearch,
		DraftCount:    req.DraftCount,
	}, nil)
	if err != nil {
		return nil, app.For(code.AI).SvcThirdParty("矩陣草稿生成失敗：" + err.Error())
	}

	list := make([]types.CopyDraftData, 0, len(created))
	for _, item := range created {
		list = append(list, toCopyDraftData(item))
	}

	return &types.GeneratePersonaTopicMatrixData{
		List:    list,
		Message: fmt.Sprintf("已產生 %d 篇矩陣草稿", len(list)),
	}, nil
}
