package persona

import (
	"context"
	"fmt"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	jobdom "haixun-backend/internal/model/job/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

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

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

func (l *StartPersonaTopicMatrixJobLogic) StartPersonaTopicMatrixJob(req *types.StartPersonaTopicMatrixJobHandlerReq) (*types.StartPersonaTopicMatrixJobData, 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")
	}
	if _, err := l.svcCtx.Persona.Get(l.ctx, tenantID, uid, personaID); err != nil {
		return nil, err
	}
	credential, err := l.svcCtx.ThreadsAccount.ResolveMemberAiCredential(l.ctx, tenantID, uid)
	if err != nil {
		return nil, err
	}

	count := req.DraftCount
	if count <= 0 {
		count = 5
	}
	if count > 5 {
		count = 5
	}

	run, err := l.svcCtx.Job.CreateRun(l.ctx, jobdom.CreateRunRequest{
		TemplateType: "generate-topic-matrix",
		Scope:        "persona",
		ScopeID:      personaID,
		TenantID:     tenantID,
		OwnerUID:     uid,
		Payload: map[string]any{
			"tenant_id":       tenantID,
			"owner_uid":       uid,
			"persona_id":      personaID,
			"content_plan_id": strings.TrimSpace(req.ContentPlanID),
			"topic":           topic,
			"brief":           strings.TrimSpace(req.Brief),
			"use_web_search":  req.UseWebSearch,
			"draft_count":     count,
			"ai_provider":     credential.Provider,
			"ai_model":        credential.Model,
		},
	})
	if err != nil {
		return nil, err
	}

	return &types.StartPersonaTopicMatrixJobData{
		JobID:      run.ID.Hex(),
		Status:     string(run.Status),
		AiProvider: credential.Provider,
		AiModel:    credential.Model,
		Message:    fmt.Sprintf("話題矩陣已在背景執行（%s / %s），可自由切換頁面", credential.Provider, credential.Model),
	}, nil
}
