package copy_mission

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 ExpandCopyMissionGraphLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *ExpandCopyMissionGraphLogic) ExpandCopyMissionGraph(req *types.ExpandCopyMissionGraphHandlerReq) (*types.ExpandKnowledgeGraphData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	personaID := strings.TrimSpace(req.PersonaID)
	missionID := strings.TrimSpace(req.ID)
	seed := strings.TrimSpace(req.SeedQuery)
	if seed == "" {
		return nil, app.For(code.Persona).InputMissingRequired("seed_query is required")
	}
	mission, err := l.svcCtx.CopyMission.Get(l.ctx, tenantID, uid, personaID, missionID)
	if err != nil {
		return nil, err
	}
	if strings.TrimSpace(mission.ResearchMap.AudienceSummary) == "" {
		return nil, app.For(code.Persona).InputMissingRequired("請先產生研究地圖再擴展延伸知識")
	}
	if err := requireMemberAiReady(l.ctx, l.svcCtx, tenantID, uid); 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{
		"tenant_id":       tenantID,
		"owner_uid":       uid,
		"persona_id":      personaID,
		"copy_mission_id": missionID,
		"seed_query":      seed,
		"supplemental":    req.Supplemental,
		"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-copy-mission-graph",
		Scope:        "copy_mission",
		ScopeID:      missionID,
		TenantID:     tenantID,
		OwnerUID:     uid,
		Payload:      payload,
	})
	if err != nil {
		return nil, err
	}
	return &types.ExpandKnowledgeGraphData{
		JobID:   run.ID.Hex(),
		Status:  string(run.Status),
		Message: "延伸知識擴展中，完成後可勾選節點用於產文",
	}, nil
}