package placement_topic

import (
	"context"
	"strings"

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

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

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

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

func (l *ExpandPlacementTopicGraphLogic) ExpandPlacementTopicGraph(req *types.ExpandPlacementTopicGraphHandlerReq) (*types.ExpandKnowledgeGraphData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	seed := strings.TrimSpace(req.SeedQuery)
	if seed == "" {
		return nil, app.For(code.Brand).InputMissingRequired("seed_query is required")
	}
	scope, err := resolveScope(l.ctx, l.svcCtx, tenantID, uid, req.ID)
	if err != nil {
		return nil, err
	}

	research, err := l.svcCtx.Placement.ResearchSettings(l.ctx, tenantID, uid)
	if err != nil {
		return nil, err
	}
	expandStrategy := placement.EffectiveExpandStrategy(research)
	if req.Supplemental && placement.WebSearchAvailable(research) {
		expandStrategy = libkg.ExpandStrategyBrave
	}
	memberCtx, err := l.svcCtx.ThreadsAccount.ResolveMemberPlacementContext(l.ctx, tenantID, uid, research)
	if err != nil {
		return nil, err
	}

	payload := map[string]any{
		"topic_id":        scope.TopicID,
		"brand_id":        scope.BrandID,
		"seed_query":      seed,
		"supplemental":    req.Supplemental,
		"regenerate_map":  req.RegenerateMap,
		"expand_strategy": expandStrategy.String(),
	}
	for key, value := range memberCtx.PayloadFields() {
		payload[key] = value
	}

	run, err := l.svcCtx.Job.CreateRun(l.ctx, jobdom.CreateRunRequest{
		TemplateType: "expand-graph",
		Scope:        "placement_topic",
		ScopeID:      scope.TopicID,
		Payload:      payload,
	})
	if err != nil {
		return nil, err
	}
	return &types.ExpandKnowledgeGraphData{
		JobID:   run.ID.Hex(),
		Status:  string(run.Status),
		Message: "研究地圖產生中，完成後可檢視延伸知識與參考連結",
	}, nil
}
